--- /dev/null
+fr.gouv.finances.cp.xemelios.ui.tools.SwingToolServiceProviderFactory
--- /dev/null
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<project name="XEMELIOS-core" default="usage" basedir=".">
+ <import file="../../common-tasks.xml"/>
+ <description>Builds, tests, and runs the project XEMELIOS xemelios-core</description>
+ <property file="${user.home}/.ant.properties"/>
+
+ <target name="usage">
+ <echo> Using ${ant.version} These are targets supported by this ANT build script: compile -
+ compile all .java files, except thoses in ./tmp folder. clean - deletes all compiled and
+ generated files and resources. jars - build jar files. Do not call this script directly,
+ use the one located at root of projet (in ../..) instead. </echo>
+ </target>
+
+ <target name="compile" depends="mk-output-dirs,define-compile-debug,prepare">
+ <javac srcdir="java" destdir="build/classes" debug="${compile.debug}" encoding="ISO-8859-1">
+ <classpath>
+ <fileset dir="lib" includes="*.jar"/>
+ <pathelement path="../starter/build/classes"/>
+ <pathelement path="../xml-marshall/build/classes"/>
+ <pathelement path="../core/build/classes"/>
+ <fileset dir="../core/lib/" includes="*.jar"/>
+ <pathelement path="../control-core/build/classes"/>
+ <pathelement path="../swing-utils/build/classes"/>
+ <fileset dir="../swing-utils/lib" includes="*.jar"/>
+ <pathelement path="../auth-std-db/build/classes"/>
+ <pathelement path="../api-plugin/build/classes"/>
+ </classpath>
+ </javac>
+ <copy todir="build/classes">
+ <fileset dir="java">
+ <include name="**/*"/>
+ <exclude name="**/*.java"/>
+ <exclude name="**/CVS/*"/>
+ <exclude name="**/*.form"/>
+ </fileset>
+ </copy>
+ </target>
+
+ <target name="jars" depends="prepare">
+ <copy file="manifest/manifest.txt" tofile="build/manifest.txt">
+ <filterset>
+ <filter token="version" value="${component.release}"/>
+ <filter token="name" value="${component.name}"/>
+ </filterset>
+ </copy>
+ <jar destfile="build/jars/${component.name}.jar" basedir="build/classes"
+ manifest="build/manifest.txt">
+ <metainf dir="META-INF" includes="**/*" excludes="**/CVS"/>
+ </jar>
+ </target>
+
+ <target name="clean">
+ <delete dir="build"/>
+ </target>
+
+
+ <target name="mk-output-dirs">
+ <mkdir dir="build/classes"/>
+ <mkdir dir="build/jars"/>
+ </target>
+
+ <target name="config" description="Genere l'arborescence de mise a jour" depends="get-configuration,prepare">
+ <property name="component.dir" value="build/config/source/${component.name}/${component.release}"/>
+ <copy file="component-definition-properties.xml" tofile="build/config/source/component-definition-properties.xml"/>
+ <mkdir dir="${component.dir}"/>
+ <copy todir="${component.dir}">
+ <fileset dir="lib" includes="*.jar"/>
+ <fileset dir="build/jars" includes="*.jar"/>
+ <fileset dir="res" includes="*.*"/>
+ <fileset dir="../resources/templates">
+ <include name="viewdoc.cmd"/>
+ <include name="CP.bat"/>
+ <include name="import-masse.bat"/>
+ </fileset>
+ </copy>
+ <antcall target="generate-update"/>
+ </target>
+
+ <target name="setup">
+ <copy todir="../../build/setup/root/lib">
+ <fileset dir="build/jars" includes="*.jar"/>
+ </copy>
+ <copy todir="../../build/setup/root/lib">
+ <fileset dir="lib" includes="*.jar"/>
+ </copy>
+ <copy todir="../../build/setup/root/resources">
+ <fileset dir="res">
+ <include name="**/*"/>
+ <exclude name="**/CVS"/>
+ <exclude name="log4j.*"/>
+ <exclude name="viewdoc.cmd"/>
+ </fileset>
+ </copy>
+ <copy todir="../../build/setup/root">
+ <fileset dir="res">
+ <include name="log4j.*"/>
+ <include name="viewdoc.cmd"/>
+ </fileset>
+ <fileset dir="lib">
+ <include name="RegAccess.dll"/>
+ </fileset>
+ </copy>
+ </target>
+
+</project>
--- /dev/null
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<component xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:noNamespaceSchemaLocation="../../defs/technical-component-definition.xsd">
+ <name>xemelios-core</name>
+ <description>Xemelios client-lourd</description>
+ <release>5.0.1.22</release>
+ <url>http://xemelios.org/updatesV5/xemelios-core</url>
+ <type>COMPOSANT</type>
+ <destination>
+ <base>${xemelios.root}/lib</base>
+ <file>
+ <name>log4j.xml</name>
+ <dest>${xemelios.root}</dest>
+ </file>
+ <file>
+ <name>modeleExcelHtml.xls</name>
+ <dest>${xemelios.root}/resources</dest>
+ </file>
+ <file>
+ <name>modeleExportXemelios.xls</name>
+ <dest>${xemelios.root}/resources</dest>
+ </file>
+ <file>
+ <name>modeleExportXemelios-97.xls</name>
+ <dest>${xemelios.root}/resources</dest>
+ </file>
+ <file>
+ <name>modeleExportXemelios-97SR1.xls</name>
+ <dest>${xemelios.root}/resources</dest>
+ </file>
+ <file>
+ <name>collapse-dwn.png</name>
+ <dest>${xemelios.root}/resources</dest>
+ </file>
+ <file>
+ <name>collapse-up.png</name>
+ <dest>${xemelios.root}/resources</dest>
+ </file>
+ <file>
+ <name>collapseAll.png</name>
+ <dest>${xemelios.root}/resources</dest>
+ </file>
+ <file>
+ <name>zoom.png.png</name>
+ <dest>${xemelios.root}/resources</dest>
+ </file>
+ <file>
+ <name>viewdoc.cmd</name>
+ <dest>${xemelios.root}</dest>
+ </file>
+ <file>
+ <name>XMLPrettyPrint.xsl</name>
+ <dest>${xemelios.root}/resources</dest>
+ </file>
+ <file>
+ <name>couri.ttf</name>
+ <dest>${xemelios.root}/resources</dest>
+ </file>
+ <file>
+ <name>CP.bat</name>
+ <dest>${xemelios.root}</dest>
+ </file>
+ <file>
+ <name>import-masse.bat</name>
+ <dest>${xemelios.root}</dest>
+ </file>
+ <file>
+ <name>logo_france.gif</name>
+ <dest>${xemelios.root}/resources</dest>
+ </file>
+ <file>
+ <name>logo_marianne.png</name>
+ <dest>${xemelios.root}/resources</dest>
+ </file>
+ <file>
+ <name>logo_ministere.png</name>
+ <dest>${xemelios.root}/resources</dest>
+ </file>
+ <file>
+ <name>navigate_beginning.png</name>
+ <dest>${xemelios.root}/resources</dest>
+ </file>
+ <file>
+ <name>print.png</name>
+ <dest>${xemelios.root}/resources</dest>
+ </file>
+
+ <file>
+ <name>navigate_beginning_inactive.png</name>
+ <dest>${xemelios.root}/resources</dest>
+ </file>
+ <file>
+ <name>navigate_close_criteres.png</name>
+ <dest>${xemelios.root}/resources</dest>
+ </file>
+ <file>
+ <name>navigate_close_infos.png</name>
+ <dest>${xemelios.root}/resources</dest>
+ </file>
+ <file>
+ <name>navigate_end.png</name>
+ <dest>${xemelios.root}/resources</dest>
+ </file>
+ <file>
+ <name>navigate_end_inactive.png</name>
+ <dest>${xemelios.root}/resources</dest>
+ </file>
+ <file>
+ <name>navigate_left.png</name>
+ <dest>${xemelios.root}/resources</dest>
+ </file>
+ <file>
+ <name>navigate_left_inactive.png</name>
+ <dest>${xemelios.root}/resources</dest>
+ </file>
+ <file>
+ <name>navigate_open_criteres.png</name>
+ <dest>${xemelios.root}/resources</dest>
+ </file>
+ <file>
+ <name>navigate_open_infos.png</name>
+ <dest>${xemelios.root}/resources</dest>
+ </file>
+ <file>
+ <name>navigate_right.png</name>
+ <dest>${xemelios.root}/resources</dest>
+ </file>
+ <file>
+ <name>navigate_right_inactive.png</name>
+ <dest>${xemelios.root}/resources</dest>
+ </file>
+ <file>
+ <name>navigate_summary.png</name>
+ <dest>${xemelios.root}/resources</dest>
+ </file>
+ </destination>
+ <requires>
+ <component-ref url="http://xemelios.org/updatesV5/core" release="5.0.0.14"/>
+ <component-ref url="http://xemelios.org/updatesV5/mysql-persistence" release="5.0.0.13"/>
+ <component-ref url="http://xemelios.org/updatesV5/control-core" release="5.0.0.2"/>
+ <component-ref url="http://xemelios.org/updatesV5/swing-utils" release="5.0.0.2"/>
+ <component-ref url="http://xemelios.org/updatesV5/auth-std-db" release="5.0.0.5"/>
+ <component-ref url="http://xemelios.org/updatesV5/api-plugin" release="5.0.0.2"/>
+ </requires>
+ <configurator>fr.gouv.finances.cp.xemelios.ui.patches.DateFormatPatch</configurator>
+ <release-notes>
+ <release v="5.0.1.22">
+ <note visibility="public">Chargement du menu des outils compagnons</note>
+ <note visibility="public">Correction Fiche anomalie FAP-MiniFin-Xemelios-0044</note>
+ </release>
+ <release v="5.0.1.21">
+ <note visibility="public">Ajout d'images pour les informations générales du Compte de Gestion SPL</note>
+ </release>
+ <release v="5.0.1.20">
+ <note visibility="public">Ajout d'images pour les informations générales du Compte de Gestion SPL</note>
+ </release>
+ <release v="5.0.1.19">
+ <note visibility="public">Modification de l'image du fond de la fenêtre XeMeLios</note>
+ <note visibility="dev">Correction de la NPE quand on annulait au choix du fichier en import d'archive</note>
+ </release>
+ <release v="5.0.1.18">
+ <note visibility="public">Changement de la splash-screen</note>
+ <note visibility="dev">Renforcement de tracking d'exception en sortie de XeMeLios</note>
+ </release>
+ <release v="5.0.1.17">
+ <note visibility="public">Correction du bug qui empêchait de quitter XeMeLios si on n'avait pas importé de fichier</note>
+ <note visibility="dev">Première implémentation du fournisseur de service pour les outils compagnons</note>
+ </release>
+ <release v="5.0.1.16">
+ <note visibility="public">Possibilité de supprimer une archive</note>
+ <note visibility="dev">Passage du user à l'importeur d'archive</note>
+ </release>
+ <release v="5.0.1.15">
+ <note visibility="public">Correction du bug sur l'ouverture du fichier en fin de recherche d'export</note>
+ <note visibility="public">Sauvegarder le repertoire d'import à la sortie de XeMeLios</note>
+ <note visibility="public">Correction de l'affichage de la barre de progression lors de l'import</note>
+ <note visibility="dev">Correction du ImportServiceSwingProvider (progression), suppression d'un displayProgression faussant l'avancement.</note>
+ <note visibility="public">Contrôle lors de l'import que le type de document peut être importé</note>
+ <note visibility="public">Correction FA 278 sur l'affichage du jour de la semaine dans les critères de type date</note>
+ <note visibility="dev">Formattage des Xemelios en XeMeLios (majuscules)</note>
+ </release>
+ <release v="5.0.1.14">
+ <note visibility="public">Correction du bug qui empêchait l'ouverture des fenêtres de recherche</note>
+ <note visibility="dev">Ajout du xemelios.date.format dans xemelios.properties</note>
+ </release>
+ <release v="5.0.1.13">
+ <note visibility="public">Correction de la FA 266 sur les exports avancés avec Excel 2000</note>
+ <note visibility="dev">Passage de jxl-2.6.12 à jxl-2.6.10 pour les problèmes de génération au format Excel 2003</note>
+ </release>
+ <release v="5.0.1.12">
+ <note visibility="public">Correction de la saisie dans les champs date qui était bloquée</note>
+ <note visibility="public">Pour les critères de type date, ajout d'une aide à la saisie avec un calendrier</note>
+ </release>
+ <release v="5.0.1.11">
+ <note visibility="dev">Rien de bien important (des logs, principalement) sur le FullXlsExporter</note>
+ </release>
+ <release v="5.0.1.10">
+ <note visibility="public">Correction de la FA 270</note>
+ <note visibility="dev">Re-travail sur les API de XemeliosUserAgent dans le cas de son utilisation dans Xemelios Viewer</note>
+ </release>
+ <release v="5.0.1.9">
+ <note visibility="dev">Suppression des accès à DematTransform</note>
+ </release>
+ <release v="5.0.1.8">
+ <note visibility="public">Correction des exports (FA-259)</note>
+ <note visibility="dev">Correction sur le CustomUriResolver : FAP-0037</note>
+ <note visibility="dev">Correction bug sur le passage de paramètres aux XSL en recherche (FAP-0033)</note>
+ <note visibility="dev">Passage du docId aux documents affichés en recherche</note>
+ </release>
+ <release v="5.0.1.6">
+ <note visibility="dev">Logs supplémentaires sur les exports</note>
+ </release>
+ <release v="5.0.1.5">
+ <note visibility="public">Ajout d'une entrée de menu pour accéder aux notes de version</note>
+ <note visibility="dev">Prise en compte de la nouvelle API de control-core</note>
+ <note visibility="editeur">Fenêtre de recherche : correction du URIResolver sur la visualisation de documents</note>
+ </release>
+ <release v="5.0.1.4">
+ <note visibility="public">Correction fiche anomalie 252 : bug sur impossibilité de modifier le mode d'authentification</note>
+ <note visibility="public">Le numéro de version du composant installé est maintenant dans le fichier installed-compoennts.xml</note>
+ </release>
+ <release v="5.0.1.3">
+ <note visibility="public">Correction FA 245 : possibilité de visionner les release-notes et progression sur la recherche de mise à jour</note>
+ <note visibility="public">Correction de la faute d'orthographe sur l'onglet "Mises à jour" de la fenêtre de configuration</note>
+ </release>
+ <release v="5.0.1.2">
+ <note>Tous les exports avancés sont désormais des Exports Full</note>
+ <note>Correction de la faute d'orthographe dans le message d'erreur d'accès aux profils</note>
+ </release>
+ <release v="5.0.1.1">
+ <note>Application des modifications du PatchProgress</note>
+ <note>Accès à la liste des composants référencés</note>
+ <note>Ajout des composants installés dans le rapport de configuration</note>
+ </release>
+ <release v="5.0.1.0">
+ <note>Correction du nombre de lignes dans les exports Full</note>
+ <note>Modification des exports : tous les exports se font depuis la fenêtre d'export</note>
+ <note>Fenêtre de recherche : <ENTER> fonctionne de nouveau</note>
+ </release>
+ <release v="5.0.0.8">
+ <note>Sauvegarde du type d'export (CSV/XLS) quand on quitte Xemelios</note>
+ <note>Usage d'un format par défaut de date pour l'exporteur FullXlsExporter</note>
+ </release>
+ <release v="5.0.0.7">
+ <note>Nouvel exporteur Excel</note>
+ </release>
+ <release v="5.0.0.6">
+ <note>Standardisation des Factory XML</note>
+ </release>
+ <release v="5.0.0.5">
+ <note>Correction du bug sur l'enregistrement du proxy au premier démarrage en mode trésor</note>
+ <note>Ajout d'un indicateur de téléchargement des mises à jour</note>
+ <note>Téléchargement des mises à jour : prise en compte des Delete qui étaient ignorés</note>
+ </release>
+ <release v="5.0.0.4">
+ <note>Prise en compte du nouveau format d'update</note>
+ <note>Si la cible de mise à jour n'est pas définie, utilise PRODUCTION par défaut</note>
+ </release>
+ <release v="5.0.0.3">
+ <note>Premier démarrage: modification du panneau de proxy pour avoir la configuration trésor en premier, et rechargement des profils quand on revient sur l'étape Abonnements</note>
+ </release>
+ <release v="5.0.0.0">
+ <note>Version initiale</note>
+ </release>
+ </release-notes>
+</component>
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 L.Meckert - lmeckert@club-internet.fr
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.utils;
+
+//import edu.stanford.ejalbert.BrowserLauncher;
+//import edu.stanford.ejalbert.exception.BrowserLaunchingInitializingException;
+//import edu.stanford.ejalbert.exception.UnsupportedOperatingSystemException;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import java.lang.reflect.Method;
+import javax.swing.JOptionPane;
+import org.apache.log4j.Logger;
+
+import fr.gouv.finances.dgfip.xemelios.common.ToolException;
+
+// Recuperer le path du navigateuir dans le registre
+// et visualiser une URL
+//
+// Exemple java StartUrl http://wwww.google.fr
+
+public class StartUrl {
+ public static Logger logger = Logger.getLogger(StartUrl.class);
+
+ public static void startUrl(String url) throws ToolException {
+ launchURL(url);
+ }
+ /**
+ * Lance le navigateur systeme sur l'URL choisie
+ *
+ * Usage : try { StartUrl.startUrl(url) } catch(ToolException te){ traiter}
+ */
+ protected static void launchURL(String url){
+
+ String osName = System.getProperty("os.name");
+ try {
+ if (osName.startsWith("Mac OS")) {
+ // Mac OS X can handle file types itself (thank goodness!)
+ Class fileMgr = Class.forName("com.apple.eio.FileManager");
+ Method openURL = fileMgr.getDeclaredMethod("openURL",new Class[] {String.class});
+ openURL.invoke(null, new Object[] {url});
+ } else if (osName.startsWith("Windows")) { // who knows what Windows does ...
+ // il y a un bug avec Windows 2000, il faut que le fichier commence par file:// au lieu de file:/
+ if("Windows 2000".equals(System.getProperty("os.name")) || "Windows 98".equals(System.getProperty("os.name"))) {
+ if(url.startsWith("file:/") && !url.startsWith("file://"))
+ url = "file://"+url.substring(6);
+ }
+ if(url.indexOf(' ')>=0) {
+ url = "\"".concat(url).concat("\"");
+ }
+ if(url.toLowerCase().endsWith(".html") && System.getProperty(Constants.SYS_PROP_NAVIGATOR_CMD_LINE)!=null) {
+ Runtime.getRuntime().exec(System.getProperty(Constants.SYS_PROP_NAVIGATOR_CMD_LINE)+" \""+url+"\"");
+ } else
+ logger.info("rundll32 url.dll,FileProtocolHandler " + url);
+ Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
+ } else if (osName.equalsIgnoreCase("Linux") || osName.equalsIgnoreCase("sunos") || osName.equalsIgnoreCase("solaris")) { // Linux, etc.
+ // launch pdf files on Linux
+ if(url.endsWith(".pdf") || url.endsWith(".PDF")){
+ String[] pdfViewers = {"evince", "kpdf", "xpdf", "Xpdf", "gv", "acroread", "acrobat", "kghostview" };
+ String viewer = null;
+ // pick the PDF Viewer
+ for (int count = 0; count < pdfViewers.length && viewer == null; count++)
+ if (Runtime.getRuntime().exec(new String[] {"which", pdfViewers [count]}).waitFor() == 0)
+ viewer = pdfViewers[count];
+ if (viewer == null) // got no pdf viewer
+ throw new Exception("Could not find PDF Viewer");
+ else { // got a pdf viewer, so launch it
+ int ind = url.indexOf(":");
+ if(ind >= 0){
+ url.substring(ind);
+ }
+ Runtime.getRuntime().exec(new String[] {viewer, url});
+ }
+ // launch html urls in a browser
+ } else if (url.startsWith("http") || url.endsWith("html") || url.endsWith("htm") || url.endsWith("HTML") || url.endsWith("HTM")){
+ String[] browsers = { // list of html browsers
+ "firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape" };
+ String browser = null;
+ for (int count = 0; count < browsers.length && browser == null; count++)
+ if (Runtime.getRuntime().exec(
+ new String[] {"which", browsers [count]}).waitFor() == 0)
+ browser = browsers[count];
+ if (browser == null) // got no browser, bummer
+ throw new Exception("Could not find web browser");
+ else // got a browser, run it
+ Runtime.getRuntime().exec(new String[] {browser, url});
+ } else {
+ // try with browser
+ String[] browsers = { "firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape" };
+ String browser = null;
+ for (int count = 0; count < browsers.length && browser == null; count++)
+ if (Runtime.getRuntime().exec(
+ new String[] {"which", browsers [count]}).waitFor() == 0)
+ browser = browsers[count];
+ if (browser == null) // got no browser, bummer
+ throw new Exception("Could not find web browser");
+ else // got a browser, run it
+ Runtime.getRuntime().exec(new String[] {browser, url});
+ }
+ }
+ } catch (Exception e) { // bollux!
+ JOptionPane.showMessageDialog(null, e.getMessage());
+ }
+ }
+
+ public static void main(String[] argv) throws ToolException {
+ // Attend une URL en parametre; je teste juste s'il y a un prametre
+ if (argv.length < 1) {
+ System.exit(1);
+ }
+
+
+ startUrl(argv[0]);
+
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 Christophe Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.utils.ui;
+
+import java.awt.BorderLayout;
+import java.awt.Dialog;
+import java.awt.FlowLayout;
+import java.awt.GraphicsEnvironment;
+import java.awt.HeadlessException;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.StringTokenizer;
+
+import javax.swing.JButton;
+import javax.swing.JComponent;
+import javax.swing.JDialog;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JTextArea;
+import javax.swing.SwingUtilities;
+
+import fr.gouv.finances.dgfip.utils.WordWrap;
+import java.awt.Window;
+import org.apache.log4j.Logger;
+
+/**
+ * A dialog to display exceptions. You can use helper-methods
+ * {@link #displayException(Dialog,Throwable)} and {@link #displayException(Frame,Throwable)}
+ */
+public class DisplayExceptionDlg extends JDialog implements ActionListener {
+
+ private static final Logger logger = Logger.getLogger(DisplayExceptionDlg.class);
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 3979274659365664560L;
+ private JButton pbClose = null;
+ private JButton pbHideShow = null;
+ private JPanel center = null;
+
+ /**
+ * Creates a non-modal dialog without a title with the
+ * specified <code>Dialog</code> as its owner.
+ * <p>
+ * This constructor sets the component's locale property to the value
+ * returned by <code>JComponent.getDefaultLocale</code>.
+ *
+ * @param owner the non-null <code>Dialog</code> from which the dialog is displayed
+ * @exception HeadlessException if GraphicsEnvironment.isHeadless()
+ * returns true.
+ * @see GraphicsEnvironment#isHeadless
+ * @see JComponent#getDefaultLocale
+ */
+ public DisplayExceptionDlg(Window owner, Throwable toDisplay) throws HeadlessException {
+ super(owner, "Erreur", Dialog.ModalityType.APPLICATION_MODAL);
+ initialize(toDisplay);
+ }
+
+ public DisplayExceptionDlg(Throwable toDisplay) throws HeadlessException {
+ super();
+ setModal(true);
+ initialize(toDisplay);
+ }
+
+ protected void initialize(Throwable toDisplay) {
+ logger.error("", toDisplay);
+ while (toDisplay.getCause() != null) {
+ toDisplay = toDisplay.getCause();
+ }
+ JPanel pane = new JPanel(new BorderLayout());
+ String[] msg = beautify(toDisplay.getMessage());
+ JPanel msgPane = new JPanel(new VerticalFlowLayout());
+ for (int i = 0; i < msg.length; i++) {
+ msgPane.add(new JLabel(msg[i]));
+ }
+ pane.add(msgPane, BorderLayout.NORTH);
+ StringWriter sw = new StringWriter();
+ PrintWriter pw = new PrintWriter(sw);
+ while (toDisplay != null) {
+ toDisplay.printStackTrace(pw);
+ pw.println("caused by...");
+ toDisplay = toDisplay.getCause();
+ }
+ pw.flush();
+ String ex = sw.toString();
+ pw.close();
+ JTextArea ml = new JTextArea(ex);
+ ml.setColumns(60);
+ ml.setRows(20);
+ center = new JPanel();
+ center.add(new JScrollPane(ml));
+ pane.add(center, BorderLayout.CENTER);
+ center.setVisible(false);
+ JPanel buttonPane = new JPanel(new FlowLayout(FlowLayout.CENTER));
+ buttonPane.add(pbClose = new JButton("Fermer"));
+ buttonPane.add(pbHideShow = new JButton("Afficher"));
+ pane.add(buttonPane, BorderLayout.SOUTH);
+ setContentPane(pane);
+ pbClose.addActionListener(this);
+ pack();
+ setLocationRelativeTo(getOwner());
+ pbHideShow.addActionListener(new java.awt.event.ActionListener() {
+
+ @Override
+ public void actionPerformed(java.awt.event.ActionEvent e) {
+ boolean visible = center.isVisible();
+ if (visible) {
+ center.setVisible(false);
+ pbHideShow.setText("Afficher");
+ } else {
+ center.setVisible(true);
+ pbHideShow.setText("Cacher");
+ }
+ pack();
+ }
+ });
+ setVisible(true);
+ }
+
+ /**
+ * Invoked when an action occurs.
+ */
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ dispose();
+ }
+
+ /**
+ * Displays <tt>toDisplay</tt> exception in a EDT-thread-safe way
+ * @param owner
+ * @param toDisplay
+ */
+ public static void displayException(Window owner, Throwable toDisplay) {
+ Runnable code = new Displayer(owner, toDisplay);
+ if (SwingUtilities.isEventDispatchThread()) {
+ code.run();
+ } else {
+ SwingUtilities.invokeLater(code);
+ }
+ }
+
+ /**
+ * Displays <tt>toDisplay</tt> exception in a EDT-thread-safe way
+ * @param owner
+ * @param toDisplay
+ */
+ public static void displayException(Dialog owner, Throwable toDisplay) {
+ Runnable code = new Displayer(owner, toDisplay);
+ if (SwingUtilities.isEventDispatchThread()) {
+ code.run();
+ } else {
+ SwingUtilities.invokeLater(code);
+ }
+ }
+
+ /**
+ * Cuts msg at 80chars max per line
+ * @param msg
+ * @return
+ */
+ protected static String[] beautify(String msg) {
+ if (msg == null) {
+ return new String[0];
+ }
+ String s = WordWrap.wrap(msg, 80);
+ StringTokenizer st = new StringTokenizer(s, "\n\r\f");
+ String[] ret = new String[st.countTokens()];
+ for (int i = 0; i < st.countTokens(); i++) {
+ ret[i] = st.nextToken();
+ }
+ return ret;
+ }
+
+ private static class Displayer implements Runnable {
+
+ private Window fOwner;
+ private Dialog dOwner;
+ private Throwable t;
+
+ public Displayer(Window owner, Throwable t) {
+ super();
+ this.fOwner = owner;
+ this.t = t;
+ }
+
+ public Displayer(Dialog owner, Throwable t) {
+ super();
+ this.dOwner = owner;
+ this.t = t;
+ }
+
+ @Override
+ public void run() {
+ if (fOwner != null) {
+ new DisplayExceptionDlg(fOwner, t);
+ } else {
+ new DisplayExceptionDlg(dOwner, t);
+ }
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.utils.ui;
+
+import java.awt.FlowLayout;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.FocusEvent;
+import java.awt.event.FocusListener;
+import java.awt.event.ItemEvent;
+import java.awt.event.ItemListener;
+import java.awt.event.KeyEvent;
+import java.awt.event.KeyListener;
+import java.util.Iterator;
+import java.util.TreeSet;
+import java.util.Vector;
+
+import javax.swing.AbstractAction;
+import javax.swing.Action;
+import javax.swing.JButton;
+import javax.swing.JComboBox;
+import javax.swing.JComponent;
+import javax.swing.JDialog;
+import javax.swing.JFrame;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JRootPane;
+import javax.swing.JTextArea;
+import javax.swing.JTextField;
+import javax.swing.KeyStroke;
+import javax.swing.Timer;
+
+import com.jgoodies.forms.builder.PanelBuilder;
+import com.jgoodies.forms.layout.CellConstraints;
+import com.jgoodies.forms.layout.FormLayout;
+
+import fr.gouv.finances.dgfip.utils.Pair;
+
+/**
+ * @author chm
+ */
+public class DlgGetPair extends JDialog {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 5506053470241303864L;
+// private static Logger logger = Logger.getLogger(DlgGetPair.class);
+ private static final String TITLE = "Informations";
+ static {
+ if(System.getProperty("os.name").toLowerCase().indexOf("win")>=0)
+ setDefaultLookAndFeelDecorated(true);
+ }
+ private JButton pbOk, pbCancel;
+ private boolean ret;
+ private Action escapeAction;
+ private String question;
+ private JTextField dfCode, dfLibelle;
+ private JComboBox cbxData;
+ private TreeSet<Pair> defaultValues;
+ private Timer timer = null;
+
+ public DlgGetPair(JFrame owner, String question) {
+ this(owner,question,TITLE);
+ }
+ public DlgGetPair(JFrame owner, String question,String title) {
+ super(owner,title,true);
+ this.question = question;
+ initialize();
+ }
+ public DlgGetPair(JFrame owner, String question,TreeSet<Pair> values) {
+ this(owner,question,values,TITLE);
+ }
+ public DlgGetPair(JFrame owner, String question,TreeSet<Pair> values,String title) {
+ super(owner,title,true);
+ this.question = question;
+ this.defaultValues=values;
+ initialize();
+ }
+ public DlgGetPair(JFrame owner, String question,TreeSet<Pair> values,String title,Pair initialValue) {
+ this(owner,question,values,title);
+ if(initialValue!=null) {
+ if(initialValue.key!=null && initialValue.key.trim().length()>0) {
+ dfCode.setText(initialValue.key);
+ if(cbxData!=null) cbxData.setEnabled(false);
+ dfCode.setEnabled(false);
+ dfLibelle.grabFocus();
+ dfLibelle.setText(initialValue.libelle);
+ // try to find an existing lib to this code
+ if(values!=null) {
+ Pair p = null;
+ for(Iterator<Pair> it=values.iterator();it.hasNext();) {
+ Pair p1 = it.next();
+ if(p1.equals(initialValue)) p = p1;
+ }
+ if(p!=null) dfLibelle.setText(p.libelle);
+ }
+ } else {
+ dfLibelle.setText(initialValue.libelle);
+ }
+ }
+ }
+ public void initialize() {
+ int sepInfo = 2;
+ int lineInfo = sepInfo + 2;
+ int sepData = lineInfo + 2;
+ int existingData = sepData + (defaultValues!=null ? 2 : 0);
+ int codeLine = existingData + 2;
+
+ int libelleLine = codeLine + 2;
+ int buttonLine = libelleLine + 2;
+
+ JTextArea area = null;
+ cbxData = null;
+
+ setDefaultCloseOperation(DISPOSE_ON_CLOSE);
+
+ FormLayout fl = new FormLayout(
+ // 1 2 3 4 5 6
+ /* "1dlu,20dlu,pref,1dlu,pref,1dlu", */
+ "3dlu,20dlu,pref,3dlu,pref,3dlu",
+ "7dlu,"+ // 1
+ "pref,"+ // 2 separateur INFO
+ "3dlu,"+ // 3
+ "pref,"+ // 4 message (question)
+ "7dlu,"+ // 5
+ "pref,"+ // 6 separateur DATA
+ (defaultValues!=null?"3dlu,pref,":"")+ // les deux lignes pour les valeurs existantes
+ "3dlu,"+ // 7
+ "pref,"+ // 8 codeLine
+ "1dlu,"+ // 9
+ "pref,"+ // 10 libelleLine
+ "10dlu,"+ // 11
+ "pref,"+ // 12 buttonLine
+ "3dlu"); // 13
+ CellConstraints cc = new CellConstraints();
+ PanelBuilder pb = new PanelBuilder(fl);
+ IhmFactory iF=IhmFactory.newInstance();
+
+ pb.addSeparator("Informations", cc.xyw(2,sepInfo,4));
+ pb.add(area = new JTextArea(), cc.xyw(3,lineInfo,3));
+
+ pb.addSeparator("Données", cc.xyw(2,sepData,4));
+ if(defaultValues!=null) {
+ pb.add(iF.newLabel("Valeurs possibles","normal"), cc.xy(3,existingData));
+ Vector<Pair> data = new Vector<Pair>();
+ data.add(new Pair("",""));
+ data.addAll(defaultValues);
+ pb.add(cbxData = new JComboBox(data), cc.xy(5,existingData));
+ cbxData.addItemListener(new ItemListener() {
+ public void itemStateChanged(ItemEvent e) {
+ if(e.getStateChange()==ItemEvent.SELECTED) {
+ JComboBox cbxData = (JComboBox)e.getSource();
+ Pair p = (Pair)cbxData.getSelectedItem();
+ dfCode.setText(p.key);
+ dfLibelle.setText(p.libelle);
+ }
+ resetTimer();
+ }
+ });
+ }
+ pb.add(iF.newLabel("Code","normal"), cc.xy(3,codeLine));
+ pb.add(dfCode = new JTextField(), cc.xy(5,codeLine));
+ pb.add(iF.newLabel("Libellé","normal"), cc.xy(3,libelleLine));
+ pb.add(dfLibelle = new JTextField(), cc.xy(5,libelleLine));
+
+ JPanel bPane = new JPanel(new FlowLayout(FlowLayout.CENTER));
+ pbCancel = new JButton(escapeAction);
+ pbOk = new JButton("Ok");
+ bPane.add(pbOk); bPane.add(pbCancel);
+
+ pb.add(bPane, cc.xyw(2,buttonLine,4));
+
+ dfCode.setColumns(15);
+ add(pb.getPanel());
+
+ area.setEditable(false);
+ area.setLineWrap(true);
+ area.setRows(3);
+ area.setBackground(getBackground());
+ area.setText(question);
+
+ if(defaultValues!=null && defaultValues.size()>0) {
+ cbxData.setSelectedIndex(1);
+ }
+
+ // timer stop !
+ dfCode.addKeyListener(new KeyListener() {
+ public void keyTyped(KeyEvent e) { resetTimer(); }
+ public void keyPressed(KeyEvent e) { resetTimer(); }
+ public void keyReleased(KeyEvent e) { resetTimer(); }
+ });
+ dfLibelle.addKeyListener(new KeyListener() {
+ public void keyTyped(KeyEvent e) { resetTimer(); }
+ public void keyPressed(KeyEvent e) { resetTimer(); }
+ public void keyReleased(KeyEvent e) { resetTimer(); resetTimer();
+ }
+ });
+ dfCode.addFocusListener(new FocusListener() {
+ public void focusGained(FocusEvent e) { /*resetTimer();*/ }
+ public void focusLost(FocusEvent e) { resetTimer(); }
+ });
+ dfLibelle.addFocusListener(new FocusListener() {
+ public void focusGained(FocusEvent e) { resetTimer(); }
+ public void focusLost(FocusEvent e) { resetTimer(); }
+ });
+ pbOk.addActionListener(new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ checkReponse();
+ }
+ });
+ getRootPane().setDefaultButton(pbOk);
+ pack();
+ setLocationRelativeTo(getParent());
+ }
+ @Override
+ protected JRootPane createRootPane() {
+ KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0);
+ JRootPane rp = new JRootPane();
+ escapeAction = new AbstractAction("Annuler") {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+
+ public void actionPerformed(ActionEvent evt) {
+ ret = false;
+ setVisible(false);
+ }
+ };
+ rp.registerKeyboardAction(escapeAction,"TOTOTOTO",ks,JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
+ }
+ protected void checkReponse() {
+ if(dfCode.getText()!=null && dfCode.getText().length()>0 && dfLibelle.getText()!=null && dfLibelle.getText().length()>0) {
+ setVisible(false);
+ ret = true;
+ } else {
+ JOptionPane.showMessageDialog(this,"Le code ainsi que le libelle sont obligatoires","Erreur de saisie",JOptionPane.WARNING_MESSAGE);
+ ret = false;
+ }
+ }
+ public String getCode() {
+ return dfCode.getText();
+ }
+ public String getLibelle() {
+ return dfLibelle.getText();
+ }
+ public boolean run() {
+ if(dfCode.getText()!=null && dfCode.getText().length()>0) {
+ // mise en place d'un compteur pour auto-cliquer
+ int delay=1000;
+ ActionListener taskPerformer = new ActionListener() {
+ private int sec = 30;
+ public void actionPerformed(ActionEvent evt) {
+ if(sec==0) {
+ if(evt.getSource() instanceof Timer) {
+ //Timer timer = (Timer)evt.getSource();
+ timer.stop();
+ timer=null;
+ }
+ pbOk.doClick();
+ } else {
+ String msg = "Ok ("+(sec--)+" sec.)";
+ pbOk.setText(msg);
+ }
+ }
+ };
+ timer = new Timer(delay,taskPerformer);
+ timer.start();
+ }
+ setVisible(true);
+ toFront();
+ return ret;
+ }
+
+ @Override
+ public void setVisible(boolean b) {
+ dfCode.grabFocus();
+ super.setVisible(b);
+ }
+ private void resetTimer() {
+ if(timer!=null) {
+ timer.stop();
+ timer=null;
+ }
+ pbOk.setText("Ok");
+ }
+// public JTextField getDfCode() {
+// return dfCode;
+// }
+// public void setDfCode(String dfCode) {
+// this.dfCode.setText(dfCode);
+// }
+// public JTextField getDfLibelle() {
+// return dfLibelle;
+// }
+// public void setDfLibelle(
+// String dfLibelle) {
+// this.dfLibelle.setText(dfLibelle);
+// }
+// public void setComboEnable(boolean b){
+// this.cbxData.setEnabled(b);
+// }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.utils.ui;
+
+import java.awt.Dialog;
+import java.awt.FlowLayout;
+import java.awt.Frame;
+import java.awt.HeadlessException;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.KeyEvent;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.util.Set;
+import java.util.Vector;
+
+import javax.swing.AbstractAction;
+import javax.swing.Action;
+import javax.swing.JButton;
+import javax.swing.JComponent;
+import javax.swing.JDialog;
+import javax.swing.JList;
+import javax.swing.JPanel;
+import javax.swing.JRootPane;
+import javax.swing.JScrollPane;
+import javax.swing.JTextArea;
+import javax.swing.KeyStroke;
+
+import com.jgoodies.forms.builder.PanelBuilder;
+import com.jgoodies.forms.layout.CellConstraints;
+import com.jgoodies.forms.layout.FormLayout;
+
+/**
+ * Permet a l'utilisateur de selectionner une valeur dans une liste
+ * @author chm
+ */
+public class DlgSelectFromList extends JDialog {
+
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 3690757289103865651L;
+ private Set<String> data;
+ private Action escapeAction;
+ private JButton pbOk, pbCancel;
+ private JList list;
+ private boolean ret;
+ private String selectedValue;
+
+ /**
+ * @throws java.awt.HeadlessException
+ */
+ public DlgSelectFromList(Set<String> data) throws HeadlessException {
+ super();
+ this.data = data;
+ initComponents();
+ }
+
+ /**
+ * @param owner
+ * @throws java.awt.HeadlessException
+ */
+ public DlgSelectFromList(Frame owner, Set<String> data) throws HeadlessException {
+ super(owner, true);
+ this.data = data;
+ initComponents();
+ }
+
+ /**
+ * @param owner
+ * @param title
+ * @throws java.awt.HeadlessException
+ */
+ public DlgSelectFromList(Frame owner, String title, Set<String> data) throws HeadlessException {
+ super(owner, title, true);
+ this.data = data;
+ initComponents();
+ }
+
+ /**
+ * @param owner
+ * @throws java.awt.HeadlessException
+ */
+ public DlgSelectFromList(Dialog owner, Set<String> data) throws HeadlessException {
+ super(owner, "Valeurs", true);
+ this.data = data;
+ initComponents();
+ }
+
+ /**
+ * @param owner
+ * @param title
+ * @throws java.awt.HeadlessException
+ */
+ public DlgSelectFromList(Dialog owner, String title, Set<String> data) throws HeadlessException {
+ super(owner, title,true);
+ this.data = data;
+ initComponents();
+ }
+
+ public void initComponents() {
+ int sepInfo = 2;
+ int lineInfo = sepInfo + 2;
+ int sepData = lineInfo + 2;
+ int dataLine = sepData + 2;
+ int buttonLine = dataLine + 2;
+
+ Vector<String> dataFL = new Vector<String>();
+ dataFL.addAll(data);
+
+ JTextArea area;
+
+ FormLayout fl = new FormLayout(
+ // 0 1 2 3 4 5
+/* "1dlu,20dlu,pref,1dlu,pref,1dlu", */
+ "3dlu,20dlu,140dlu,3dlu",
+ "7dlu,"+ // 0
+ "pref,"+ // 1
+ "3dlu,"+ // 2
+ "pref,"+ // 3
+ "7dlu,"+ // 4
+ "pref,"+ // 5
+ "3dlu,"+ // 6
+ "140dlu,"+ // 7
+ "7dlu,"+ // 10
+ "pref,"+ // 11
+ "3dlu"); // 12
+ CellConstraints cc = new CellConstraints();
+ PanelBuilder pb = new PanelBuilder(fl);
+
+// JScrollPane scroller;
+ list = new JList(dataFL);
+
+ pb.addSeparator("Informations", cc.xyw(2,sepInfo,2));
+ pb.add(area = new JTextArea(), cc.xy(3,lineInfo));
+
+ pb.addSeparator("Données", cc.xyw(2,sepData,2));
+ pb.add(new JScrollPane(list), cc.xy(3,dataLine,"fill, fill"));
+
+ JPanel bPane = new JPanel(new FlowLayout(FlowLayout.CENTER));
+ pbCancel = new JButton(escapeAction);
+ pbOk = new JButton("Ok");
+ bPane.add(pbOk); bPane.add(pbCancel);
+ pb.add(bPane, cc.xyw(2,buttonLine,2));
+
+ area.setEditable(false);
+ area.setLineWrap(true);
+ area.setRows(3);
+ area.setBackground(getBackground());
+// area.setColumns(70);
+ area.setText("Sélectionnez dans la liste ci-dessous\nl'élément de votre choix");
+
+ pbOk.setDefaultCapable(true);
+ pbOk.addActionListener(new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ selectedValue = (String)list.getSelectedValue();
+ ret = true;
+ setVisible(false);
+ }
+ });
+ list.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(MouseEvent e) {
+ if (e.getClickCount() == 2) {
+// int index = list.locationToIndex(e.getPoint());
+ selectedValue = (String)list.getSelectedValue();
+ ret = true;
+ setVisible(false);
+ }
+ }
+ });
+
+ setContentPane(pb.getPanel());
+
+ getRootPane().setDefaultButton(pbOk);
+ pack();
+ setLocationRelativeTo(getParent());
+
+ }
+ public boolean run() {
+ setVisible(true);
+ return ret;
+ }
+ public String getSelectedValue() { return selectedValue; }
+ @Override
+ protected JRootPane createRootPane() {
+ KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0);
+ JRootPane rp = new JRootPane();
+ escapeAction = new AbstractAction("Annuler") {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+
+ public void actionPerformed(ActionEvent evt) {
+ ret = false;
+ setVisible(false);
+ }
+ };
+ rp.registerKeyboardAction(escapeAction,"TOTOTOTO",ks,JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.utils.ui;
+
+/**
+ * A class to print html content
+ * @author chm
+ */
+import java.awt.Color;
+import java.awt.Graphics;
+import java.awt.GraphicsConfiguration;
+import java.awt.Rectangle;
+import java.awt.image.BufferedImage;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.Vector;
+
+import javax.imageio.ImageIO;
+import javax.imageio.ImageWriter;
+import javax.imageio.stream.ImageOutputStream;
+import javax.print.Doc;
+import javax.print.DocFlavor;
+import javax.print.DocPrintJob;
+import javax.print.PrintException;
+import javax.print.PrintService;
+import javax.print.PrintServiceLookup;
+import javax.print.ServiceUI;
+import javax.print.SimpleDoc;
+import javax.print.attribute.HashPrintRequestAttributeSet;
+import javax.print.attribute.PrintJobAttributeSet;
+import javax.print.attribute.PrintRequestAttributeSet;
+import javax.print.attribute.standard.Chromaticity;
+import javax.print.attribute.standard.ColorSupported;
+import javax.print.attribute.standard.MediaPrintableArea;
+import javax.print.attribute.standard.PrinterResolution;
+import javax.print.event.PrintJobListener;
+import javax.print.event.PrintServiceAttributeListener;
+import javax.swing.JEditorPane;
+import javax.swing.text.View;
+
+/**
+ * Sets up to easily print HTML documents. It is not necessary to call any of
+ * the setter methods as they all have default values, they are provided should
+ * you wish to change any of the default values.
+ */
+public class HtmlPrinter {
+ public static int DEFAULT_DPI = 72;
+
+ public static float DEFAULT_PAGE_WIDTH_INCH = 8.5f;
+
+ public static float DEFAULT_PAGE_HEIGHT_INCH = 11f;
+
+ int x = 100;
+
+ int y = 80;
+
+ GraphicsConfiguration gc;
+
+ PrintService[] services;
+
+ PrintService defaultService;
+
+ DocFlavor flavor;
+
+ PrintRequestAttributeSet attributes;
+
+ Vector<PrintJobListener> pjlListeners = new Vector<PrintJobListener>();
+
+ Vector<PrintServiceAttributeListener> pjalListeners = new Vector<PrintServiceAttributeListener>();
+
+ Vector<PrintServiceAttributeListener> psalListeners = new Vector<PrintServiceAttributeListener>();
+
+ public HtmlPrinter() {
+ gc = null;
+ attributes = new HashPrintRequestAttributeSet();
+ flavor = null;
+ defaultService = PrintServiceLookup.lookupDefaultPrintService();
+ services = PrintServiceLookup.lookupPrintServices(flavor, attributes);
+
+ // do something with the supported docflavors
+ DocFlavor[] df = defaultService.getSupportedDocFlavors();
+ for (int i = 0; i < df.length; i++)
+
+ // if there is a default service, but no other services
+ if (defaultService != null && (services == null || services.length == 0)) {
+ services = new PrintService[1];
+ services[0] = defaultService;
+ }
+ }
+
+ /**
+ * Set the GraphicsConfiguration to display the print dialog on.
+ *
+ * @param gc
+ * a GraphicsConfiguration object
+ */
+ public void setGraphicsConfiguration(GraphicsConfiguration gc) {
+ this.gc = gc;
+ }
+
+ public void setServices(PrintService[] services) {
+ this.services = services;
+ }
+
+ public void setDefaultService(PrintService service) {
+ this.defaultService = service;
+ }
+
+ public void setDocFlavor(DocFlavor flavor) {
+ this.flavor = flavor;
+ }
+
+ public void setPrintRequestAttributes(PrintRequestAttributeSet attributes) {
+ this.attributes = attributes;
+ }
+
+ public void setPrintDialogLocation(int x, int y) {
+ this.x = x;
+ this.y = y;
+ }
+
+ public void addPrintJobListener(PrintJobListener pjl) {
+ pjlListeners.addElement(pjl);
+ }
+
+ public void removePrintJobListener(PrintJobListener pjl) {
+ pjlListeners.removeElement(pjl);
+ }
+
+ public void addPrintServiceAttributeListener(PrintServiceAttributeListener psal) {
+ psalListeners.addElement(psal);
+ }
+
+ public void removePrintServiceAttributeListener(PrintServiceAttributeListener psal) {
+ psalListeners.removeElement(psal);
+ }
+
+ public boolean printJEditorPane(JEditorPane jep, PrintService ps) {
+ if (ps == null || jep == null) {
+ return false;
+ }
+
+ // get the root view of the preview pane
+ View rv = jep.getUI().getRootView(jep);
+
+ // get the size of the view (hopefully the total size of the page to be
+ // printed
+// int x = (int)rv.getPreferredSpan(View.X_AXIS);
+ int y = (int)rv.getPreferredSpan(View.Y_AXIS);
+
+ // find out if the print has been set to colour mode
+ DocPrintJob dpj = ps.createPrintJob();
+ PrintJobAttributeSet pjas = dpj.getAttributes();
+
+ // get the DPI and printable area of the page. use default values if not
+ // available
+ // use this to get the maximum number of pixels on the vertical axis
+
+ PrinterResolution pr = (PrinterResolution)pjas.get(PrinterResolution.class);
+
+ int dpi;
+ float pageX, pageY;
+ if (pr != null)
+ dpi = pr.getFeedResolution(PrinterResolution.DPI);
+ else dpi = DEFAULT_DPI;
+ MediaPrintableArea mpa = (MediaPrintableArea)pjas.get(MediaPrintableArea.class);
+ if (mpa != null) {
+ pageX = mpa.getX(MediaPrintableArea.INCH);
+ pageY = mpa.getX(MediaPrintableArea.INCH);
+ } else {
+ pageX = DEFAULT_PAGE_WIDTH_INCH;
+ pageY = DEFAULT_PAGE_HEIGHT_INCH;
+ }
+ int pixelsPerPageY = (int)(dpi * pageY);
+
+ // mod: Add 'pixelsPerPageX' and 'minY'; used in place of 'x' and 'y',
+ // respectively, in the remainder of the method
+ int pixelsPerPageX = (int)(dpi * pageX); // mod: needed to correctly
+ // scale images with lines
+ // pre-wrapped longer than
+ // page width
+ int minY = Math.max(pixelsPerPageY, y); // mod: needed to print one page
+ // documents
+
+ // make colour true if the user has selected colour, and the
+ // PrintService can support colour
+ boolean colour = pjas.containsValue(Chromaticity.COLOR);
+ colour = colour & (ps.getAttribute(ColorSupported.class) == ColorSupported.SUPPORTED);
+
+ // create a BufferedImage to draw on
+ int imgMode;
+ if (colour)
+ imgMode = BufferedImage.TYPE_3BYTE_BGR;
+ else imgMode = BufferedImage.TYPE_BYTE_GRAY;
+ BufferedImage img = new BufferedImage(pixelsPerPageX, minY, imgMode);
+ Graphics myGraphics = img.getGraphics();
+ myGraphics.setClip(0, 0, pixelsPerPageX, minY);
+ myGraphics.setColor(Color.WHITE);
+ myGraphics.fillRect(0, 0, pixelsPerPageX, minY);
+
+ // call rootView.paint( myGraphics, rect ) to paint the whole image on
+ // myGraphics
+ rv.paint(myGraphics, new Rectangle(0, 0, pixelsPerPageX, minY));
+
+ try {
+ // write the image as a JPEG to the ByteArray so it can be printed
+ Iterator writers = ImageIO.getImageWritersByFormatName("jpeg");
+ ImageWriter writer = (ImageWriter)writers.next();
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ImageOutputStream ios = ImageIO.createImageOutputStream(out);
+ writer.setOutput(ios);
+
+ // get the number of pages we need to print this image
+// int imageHeight = img.getHeight();
+
+ // mod: corrected to calculate true number of pages
+ int numberOfPages = (int)Math.ceil(minY / (double)pixelsPerPageY);
+
+ // print each page
+ for (int i = 0; i < numberOfPages; i++) {
+ int startY = i * pixelsPerPageY;
+
+ // get a subimage which is exactly the size of one page
+ BufferedImage subImg = img.getSubimage(0, startY, pixelsPerPageX, Math.min(y - startY, pixelsPerPageY)); // mod:
+ // changed
+ // to
+ // correctly
+ // calculate
+ // the
+ // 'subImg'
+ // crop
+ writer.write(subImg);
+
+ SimpleDoc sd = new SimpleDoc(out.toByteArray(), DocFlavor.BYTE_ARRAY.JPEG, null);
+ printDocument(sd, ps);
+
+ // reset the ByteArray so we can start the next page
+ out.reset();
+ }
+ }
+ catch (PrintException e) {
+ e.printStackTrace();
+ return false;
+ }
+ catch (IOException e) {
+ e.printStackTrace();
+ return false;
+ }
+
+ // uncomment this code and comment out the 'try-catch' block above
+ // to print to a JFrame instead of to the printer
+ /*
+ * JFrame jf = new JFrame(); PaintableJPanel jp = new PaintableJPanel();
+ * jp.setImage( img ); JScrollPane jsp = new JScrollPane( jp );
+ * jf.getContentPane().add( jsp ); Insets i = jf.getInsets();
+ * jf.setBounds( 0, 0, newX, y ); jf.setDefaultCloseOperation(
+ * JFrame.DISPOSE_ON_CLOSE ); jf.setVisible( true );
+ */
+
+ return true;
+ }
+
+ /**
+ * Print the document to the specified PrintService. This method cannot tell
+ * if the printing was successful. You must register a PrintJobListener
+ *
+ * @return false if no PrintService is selected in the dialog, true
+ * otherwise
+ */
+ public boolean printDocument(Doc doc, PrintService ps) throws PrintException {
+ if (ps == null)
+ return false;
+
+ addAllPrintServiceAttributeListeners(ps);
+
+ DocPrintJob dpj = ps.createPrintJob();
+ addAllPrintJobListeners(dpj);
+
+ dpj.print(doc, attributes);
+ return true;
+ }
+
+ public PrintService showPrintDialog() {
+ return ServiceUI.printDialog(gc, x, y, services, defaultService, flavor, attributes);
+ }
+
+ private void addAllPrintServiceAttributeListeners(PrintService ps) {
+ // add all listeners that are currently added to this object
+ for (int i = 0; i < psalListeners.size(); i++) {
+ PrintServiceAttributeListener p = psalListeners.get(i);
+ ps.addPrintServiceAttributeListener(p);
+ }
+ }
+
+ private void addAllPrintJobListeners(DocPrintJob dpj) {
+ // add all listeners that are currently added to this object
+ for (int i = 0; i < pjlListeners.size(); i++) {
+ PrintJobListener p = pjlListeners.get(i);
+ dpj.addPrintJobListener(p);
+ }
+ }
+
+ // uncomment this also to print to a JFrame instead of a printer
+ /*
+ * protected class PaintableJPanel extends JPanel { Image img;
+ *
+ * protected PaintableJPanel() { super(); }
+ *
+ * public void setImage( Image i ) { img = i; }
+ *
+ * public void paint( Graphics g ) { g.drawImage( img, 0, 0, this ); } }
+ */
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.utils.ui;
+
+import java.awt.Color;
+import java.awt.Font;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.awt.image.BufferedImage;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.StringTokenizer;
+
+import javax.imageio.ImageIO;
+import javax.imageio.ImageReader;
+import javax.imageio.stream.MemoryCacheImageInputStream;
+import javax.swing.Action;
+import javax.swing.Icon;
+import javax.swing.ImageIcon;
+import javax.swing.JButton;
+import javax.swing.JLabel;
+
+import fr.gouv.finances.dgfip.utils.StringUtilities;
+
+/**
+ * @author chm
+ */
+public class IhmFactory {
+ private Hashtable<String,Font> fonts=null;
+ private Hashtable<String,Color> colors=null;
+
+ /**
+ * Constructor for UIFactory.
+ */
+ private IhmFactory() {
+ super();
+ fonts = new Hashtable<String,Font>();
+ colors = new Hashtable<String,Color>();
+ }
+
+ public static IhmFactory newInstance() {
+ return new IhmFactory();
+ }
+
+ /**
+ * Construit un nouveau label.
+ * @param text Le texte du label
+ * @param txtClass Une chaine representant le format du texte.
+ * <p>Le format du texte est le suivant : <tt>[<font-info>[:<text-color>[:<back-color>]]]</tt>
+ * ou <ul><li><tt><font-info></tt> est de la forme <tt>[normal[-{italic|bold}[-{italic|bold}]]]</tt></li>
+ * <li><tt><text-color></tt> est de la forme <tt>[black|blue|cyan|darkgray|gray|green|lightgray|magenta|orange|pink|red|white|yellow|#xxxxxx]</tt></li>
+ * <li><tt><back-color></tt> est de la forme <tt>[black|blue|cyan|darkgray|gray|green|lightgray|magenta|orange|pink|red|white|yellow|#xxxxxx]</tt></li></ul>
+ * @return Le label construit
+ */
+ public JLabel newLabel(String text, String txtClass) {
+ String fontSpec = null;
+ String fontColor = null;
+ String backColor = null;
+ if(txtClass!=null) {
+ StringTokenizer st = new StringTokenizer(txtClass,":");
+ fontSpec = st.nextToken();
+ if(st.hasMoreTokens()) fontColor=st.nextToken();
+ if(st.hasMoreTokens()) backColor=st.nextToken();
+ }
+ String fontName = "dialog-"+(fontSpec!=null?fontSpec.toLowerCase():"");
+ JLabel ret = new JLabel(text);
+ if(txtClass==null) return ret;
+ Font font = getFont(ret.getFont(),fontName);
+ ret.setFont(font);
+ if(fontColor!=null) {
+ Color col = decodeColor(fontColor);
+ if(col!=null) ret.setForeground(col);
+ }
+ if(backColor!=null) {
+ Color col = decodeColor(backColor);
+ if(col!=null) ret.setBackground(col);
+ }
+ return ret;
+ }
+ public JLabel newLabel(String text) { return newLabel(text,null); }
+
+
+ // private implementations
+
+ /**
+ * Renvoie la police demandee
+ * @param font Une police basique
+ * @param c la chaine indiquant le type de police demandee.
+ * La forme est <tt>{dialog|<font-familly>}-[normal[-{italic|bold}[-{italic|bold}]]]</tt>
+ * @return La font demandee
+ */
+ protected Font getFont(Font font, String c) {
+ Font ret = fonts.get(c);
+ if(ret==null) {
+ ret = font;
+ if(c.indexOf("normal")>=0) ret=ret.deriveFont(Font.PLAIN);
+ if(c.indexOf("italic")>=0) ret=ret.deriveFont(Font.ITALIC);
+ if(c.indexOf("bold")>=0) ret = ret.deriveFont(Font.BOLD);
+ fonts.put(c,ret);
+ }
+ return ret;
+ }
+ public Color decodeColor(String col) {
+ String c = col.toLowerCase();
+ Color ret = colors.get(c);
+ if(ret==null) {
+ if("black".equals(col)) ret = Color.BLACK;
+ else if("blue".equals(col)) ret = Color.BLUE;
+ else if("cyan".equals(col)) ret = Color.CYAN;
+ else if("darkgray".equals(col)) ret = Color.DARK_GRAY;
+ else if("gray".equals(col)) ret = Color.GRAY;
+ else if("green".equals(col)) ret = Color.GREEN;
+ else if("lightgray".equals(col)) ret = Color.LIGHT_GRAY;
+ else if("magenta".equals(col)) ret = Color.MAGENTA;
+ else if("orange".equals(col)) ret = Color.ORANGE;
+ else if("pink".equals(col)) ret = Color.PINK;
+ else if("red".equals(col)) ret = Color.RED;
+ else if("white".equals(col)) ret = Color.WHITE;
+ else if("yellow".equals(col)) ret = Color.YELLOW;
+ else if(col.startsWith("#")) {
+ if(col.length()==7) {
+ String s = col.toUpperCase();
+ int r=Integer.parseInt(s.substring(1,2));
+ int g=Integer.parseInt(s.substring(3,4));
+ int b=Integer.parseInt(s.substring(5,6));
+ ret = new Color(r,g,b);
+ }
+ }
+ if(ret!=null) colors.put(col,ret);
+ }
+ return ret;
+ }
+ public JButton newButton(String text) {
+ JButton ret = new JButton(text);
+ addInfoMgr(ret);
+ return ret;
+ }
+ public JButton newButton(Icon icon) {
+ JButton ret = new JButton(icon);
+ addInfoMgr(ret);
+ return ret;
+ }
+ public JButton newButton(String text, Icon icon) {
+ JButton ret = new JButton(text,icon);
+ addInfoMgr(ret);
+ return ret;
+ }
+ public JButton newButton(Action action) {
+ JButton ret = new JButton(action);
+ addInfoMgr(ret);
+ return ret;
+ }
+ protected void addInfoMgr(JButton button) {
+ button.setBorderPainted(false);
+ button.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseEntered(MouseEvent e) {
+ ((JButton)e.getSource()).setBorderPainted(true);
+ ((JButton)e.getSource()).setOpaque(true);
+ }
+ @Override
+ public void mouseExited(MouseEvent e) {
+ ((JButton)e.getSource()).setBorderPainted(false);
+ ((JButton)e.getSource()).setOpaque(false);
+ }
+ });
+ }
+ public static ImageIcon getIconFromResource(String resName) {
+ Iterator it = ImageIO.getImageReadersBySuffix(StringUtilities.getFileNameSuffix(resName));
+ if(it.hasNext()) {
+ ImageReader ir = (ImageReader)it.next();
+ InputStream is = IhmFactory.class.getClassLoader().getResourceAsStream(resName);
+ try {
+ MemoryCacheImageInputStream fiis = new MemoryCacheImageInputStream(is);
+ ir.setInput(fiis);
+ BufferedImage bi = ir.read(0);
+ fiis.close();
+ ImageIcon icon = new ImageIcon(bi);
+ return icon;
+ } catch(IOException ioEx) {
+ return null;
+ }
+ }
+ return null;
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.utils.ui;
+
+import java.awt.Dimension;
+import java.util.Timer;
+import java.util.TimerTask;
+import javax.swing.Icon;
+import javax.swing.ImageIcon;
+import javax.swing.JLabel;
+import javax.swing.SwingUtilities;
+
+//import org.apache.log4j.Logger;
+
+/**
+ * This class is designed to drive users patient when a long process is running.
+ * It is really awfull, by its implementation and by its drawing. Artists contributors
+ * are welcome to re-implment it ;-))
+ * @author chm
+ */
+public class JWaiter extends JLabel {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 3256444694262394930L;
+// public static final Color EXT_COLOR = Color.WHITE;
+// public static final Color IN_COLOR = new Color(163,184,204);
+// public static final int PAINT_MODE_NORMAL = 1; // an empty rect
+// public static final int PAINT_MODE_PROGRESS = 2;
+// public static final int LEFT_TO_RIGHT = 1;
+// public static final int RIGHT_TO_LEFT = 2;
+//
+// private int inPosition = 0; // may change from 0 to 10
+// private int inDirection = LEFT_TO_RIGHT;
+//
+// private int paintMode = PAINT_MODE_NORMAL;
+// private Waiter waiter = null;
+ private Icon[] waiters = new Icon[12];
+ private Timer timer;
+ private ProgressPainter currentPainter;
+ private Icon transparent;
+
+ public JWaiter() {
+ super();
+ initIcons();
+ setPreferredSize(new Dimension(20,20));
+ setIcon(transparent);
+ }
+// @Override
+// public void setVisible(boolean aFlag) {
+// super.setVisible(aFlag);
+// if(aFlag) {
+// startProgress();
+// } else {
+// stopProgress();
+// }
+// }
+
+ public void startProgress() {
+ if(timer==null) {
+ timer = new Timer();
+ }
+ if(currentPainter!=null) return;
+ currentPainter = new ProgressPainter();
+ timer.schedule(currentPainter, 0, 50);
+ }
+ public void stopProgress() {
+ if(currentPainter==null) return;
+ currentPainter.cancel();
+ currentPainter = null;
+ setIcon(transparent);
+ }
+ private void initIcons() {
+ String[] names = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"};
+ for(int i=0;i<12;i++) {
+ String name = names[i];
+ String resName = "fr/gouv/finances/cp/xemelios/updater/ui/res/wait-"+name+".png";
+ ImageIcon ii = IhmFactory.getIconFromResource(resName);
+ waiters[i] = ii;
+ }
+ transparent = IhmFactory.getIconFromResource("fr/gouv/finances/cp/xemelios/ui/resources/blank.png");
+ }
+
+// public void startProgress() {
+// inPosition = 0;
+// inDirection = LEFT_TO_RIGHT;
+// paintMode = PAINT_MODE_PROGRESS;
+// waiter = new Waiter();
+// waiter.start();
+// }
+//
+// private void pushProgress() {
+// if(inDirection==LEFT_TO_RIGHT) {
+// inPosition++;
+// if(inPosition==10) inDirection = RIGHT_TO_LEFT;
+// } else {
+// inPosition--;
+// if(inPosition==0) inDirection = LEFT_TO_RIGHT;
+// }
+// //paintImmediately(getBounds());
+// Graphics g = getGraphics();
+// g.setClip(0,0,getWidth(),getHeight());
+// paintComponent(g);
+// }
+//
+// public void stopProgress() {
+// if(waiter!=null) {
+// waiter.stop = true;
+// }
+// paintMode = PAINT_MODE_NORMAL;
+// Graphics g = getGraphics();
+// g.setClip(0,0,getWidth(),getHeight());
+// paintComponent(g);
+// waiter = null;
+// }
+//
+// @Override
+// protected void paintComponent(Graphics g) {
+// //super.paintComponent(g);
+// Rectangle rect = getBounds();
+// if(paintMode==PAINT_MODE_NORMAL) {
+// g.setColor(getBackground());
+// g.fillRect(1,1,rect.width-2,rect.height-2);
+// } else {
+// int w = rect.width;
+// int left = (inPosition*w/30);
+// int right = (left + w/3);
+// g.setColor(EXT_COLOR);
+// g.fillRect(0,0,left,rect.height-1);
+// g.fillRect(right,0,w-1,rect.height-1);
+// g.setColor(IN_COLOR);
+// g.fillRect(left+1,0,right-1,rect.height-1);
+// }
+// g.setColor(Color.DARK_GRAY);
+// g.drawRect(0,0,rect.width-1,rect.height-1);
+// }
+// private class Waiter extends Thread {
+// public boolean stop = false;
+// public Waiter() {
+// super("Waiter");
+// }
+// @Override
+// public void run() {
+// setPriority(MAX_PRIORITY);
+// while(!stop) {
+// pushProgress();
+// try {
+// sleep(100);
+// } catch(InterruptedException iEx) {
+// stopProgress();
+// }
+// }
+// }
+// }
+ private class ProgressPainter extends TimerTask {
+ private long startTime;
+ private int lastIndex;
+
+ public ProgressPainter() {
+ super();
+ startTime = System.currentTimeMillis();
+ }
+
+ @Override
+ public void run() {
+ long delay = (System.currentTimeMillis() - startTime) / 100;
+ final int pos = (int) (delay % 12);
+ if(pos!=lastIndex) {
+ try {
+ SwingUtilities.invokeAndWait(new Runnable() {
+ @Override
+ public void run() {
+ setIcon(waiters[pos]);
+ }
+ });
+ } catch(Exception ex) {}
+ lastIndex = pos;
+ }
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.utils.ui;
+
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.FontMetrics;
+import java.awt.Graphics;
+import java.text.DecimalFormat;
+
+import javax.swing.JComponent;
+
+
+/**
+ * This class is only for tests. It draw a gauge-like of RAM
+ * @author chm
+ *
+ */
+public class RamViewer extends JComponent {
+
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+ //public static void main(String[] args) {}
+ private Runner currentRunner = null;
+
+ public RamViewer() {
+ super();
+ initComponents();
+ }
+
+ protected void initComponents() {
+ setPreferredSize(new Dimension(100,20));
+ currentRunner = new Runner(this);
+ currentRunner.start();
+ }
+
+
+ public void paint(Graphics g) {
+ if(!isVisible()) return;
+ int width = getSize().width;
+ int height = getSize().height;
+// Image offscreenImg = createImage(width,height);
+ Graphics offG = g;
+ if(g==null) return;
+ long freeRam = Runtime.getRuntime().freeMemory();
+ long totalRam = Runtime.getRuntime().totalMemory();
+ //long maxRam = Runtime.getRuntime().maxMemory();
+
+ int freeWidth = (int)(width * freeRam / totalRam );
+ int totalWidth = /*(int)(width * totalRam / maxRam );*/width-freeWidth;
+ offG.setColor(getParent().getBackground());
+ offG.fillRect(0,0,width,height);
+ offG.setColor(new Color(0xCC0000));
+ offG.fillRect(0,0,totalWidth,height);
+ offG.setColor(new Color(0x00CC00));
+ offG.fillRect(totalWidth,0,freeWidth,height);
+ Font f = new Font("Arial",Font.BOLD,12);
+ FontMetrics fm = getFontMetrics(f);
+ offG.setFont(f);
+ DecimalFormat df = new DecimalFormat("0.0' MB'");
+ String s = df.format((totalRam-freeRam)/1024.0/1024.0)+" / "+df.format(totalRam/1024.0/1024.0);
+ offG.setColor(Color.WHITE);
+ offG.drawString(s,(width-fm.stringWidth(s))/2,(int)(height*0.8));
+ offG.setColor(Color.BLACK);
+ offG.drawRect(0,0,width-1,height-1);
+// g.drawImage(offscreenImg, 0, 0, this);
+ }
+ protected class Runner extends Thread {
+ private RamViewer viewer=null;
+ private boolean stop=false;
+ public Runner(RamViewer viewer) {
+ super();
+ this.viewer=viewer;
+ }
+ @Override
+ public void run() {
+ setPriority(Thread.MAX_PRIORITY);
+ while(!stop) {
+ viewer.paint(viewer.getGraphics());
+ try { sleep(1000) ; } catch(Throwable t) { }
+ }
+ }
+ public void stopIt() { stop=true; }
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.utils.ui;
+
+import java.awt.Component;
+import java.awt.Container;
+import java.awt.Dimension;
+import java.awt.Insets;
+import java.awt.LayoutManager;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+
+/**
+ * Similar to {@link VerticalFlowLayout}, but resize all components to make them the same size.
+ * License LGPL
+ * @author christophe.marchand@labodev.com
+ * @since Nov 23, 2003
+ */
+public class SameSizeVerticalFlowLayout implements LayoutManager, java.io.Serializable {
+ /**
+ * This value indicates that each column of components
+ * should be top-justified.
+ */
+ public static final int TOP = 0;
+
+ /**
+ * This value indicates that each column of components
+ * should be centered.
+ */
+ public static final int CENTER = 1;
+
+ /**
+ * This value indicates that each column of components
+ * should be bottom-justified.
+ */
+ public static final int BOTTOM = 2;
+
+ /**
+ * This value indicates that each column of components
+ * should be justified to the leading edge of the container's
+ * orientation, for example, to the top in top-to-bottom orientations.
+ *
+ * @see java.awt.Component#getComponentOrientation
+ * @see java.awt.ComponentOrientation
+ * @since 1.2
+ * Package-private pending API change approval
+ */
+ public static final int LEADING = 3;
+
+ /**
+ * This value indicates that each column of components
+ * should be justified to the trailing edge of the container's
+ * orientation, for example, to the bottom in top-to-bottom orientations.
+ *
+ * @see java.awt.Component#getComponentOrientation
+ * @see java.awt.ComponentOrientation
+ * @since 1.2
+ * Package-private pending API change approval
+ */
+ public static final int TRAILING = 4;
+
+ /**
+ * <code>align</code> is the property that determines
+ * how each row distributes empty space.
+ * It can be one of the following values:
+ * <ul>
+ * <code>TOP</code>
+ * <code>BOTTOM</code>
+ * <code>CENTER</code>
+ * <code>LEADING</code>
+ * <code>TRAILING</code>
+ * </ul>
+ *
+ * @serial
+ * @see #getAlignment
+ * @see #setAlignment
+ */
+ int align; // This is for 1.1 serialization compatibility
+
+ /**
+ * <code>newAlign</code> is the property that determines
+ * how each row distributes empty space for the Java 2 platform,
+ * v1.2 and greater.
+ * It can be one of the following three values:
+ * <ul>
+ * <code>TOP</code>
+ * <code>BOTTOM</code>
+ * <code>CENTER</code>
+ * <code>LEADING</code>
+ * <code>TRAILING</code>
+ * </ul>
+ *
+ * @serial
+ * @since 1.2
+ * @see #getAlignment
+ * @see #setAlignment
+ */
+ int newAlign; // This is the one we actually use
+
+ /**
+ * The flow layout manager allows a seperation of
+ * components with gaps. The horizontal gap will
+ * specify the space between components.
+ *
+ * @serial
+ * @see #getHgap
+ * @see #setHgap
+ */
+ int hgap;
+
+ /**
+ * The flow layout manager allows a seperation of
+ * components with gaps. The vertical gap will
+ * specify the space between rows.
+ *
+ * @serial
+ * @see #getVgap
+ * @see #setVgap
+ */
+ int vgap;
+
+ /*
+ * JDK 1.1 serialVersionUID
+ */
+ private static final long serialVersionUID = -7262534874583282631L;
+ private Dimension maxDimension;
+
+ /**
+ * Constructs a new <code>FlowLayout</code> with a centered alignment and a
+ * default 5-unit horizontal and vertical gap.
+ */
+ public SameSizeVerticalFlowLayout() {
+ this(CENTER, 5, 5);
+ }
+
+ /**
+ * Constructs a new <code>FlowLayout</code> with the specified
+ * alignment and a default 5-unit horizontal and vertical gap.
+ * The value of the alignment argument must be one of
+ * <code>FlowLayout.TOP</code>, <code>FlowLayout.BOTTOM</code>,
+ * or <code>FlowLayout.CENTER</code>.
+ * @param align the alignment value
+ */
+ public SameSizeVerticalFlowLayout(int align) {
+ this(align, 5, 5);
+ }
+
+ /**
+ * Creates a new flow layout manager with the indicated alignment
+ * and the indicated horizontal and vertical gaps.
+ * <p>
+ * The value of the alignment argument must be one of
+ * <code>FlowLayout.TOP</code>, <code>FlowLayout.BOTTOM</code>,
+ * or <code>FlowLayout.CENTER</code>.
+ * @param align the alignment value
+ * @param hgap the horizontal gap between components
+ * @param vgap the vertical gap between components
+ */
+ public SameSizeVerticalFlowLayout(int align, int hgap, int vgap) {
+ this.hgap = hgap;
+ this.vgap = vgap;
+ setAlignment(align);
+ }
+
+ /**
+ * Gets the alignment for this layout.
+ * Possible values are <code>FlowLayout.TOP</code>,
+ * <code>FlowLayout.BOTTOM</code>, <code>FlowLayout.CENTER</code>,
+ * <code>FlowLayout.LEADING</code>,
+ * or <code>FlowLayout.TRAILING</code>.
+ * @return the alignment value for this layout
+ * @see java.awt.FlowLayout#setAlignment
+ * @since JDK1.1
+ */
+ public int getAlignment() {
+ return newAlign;
+ }
+
+ /**
+ * Sets the alignment for this layout.
+ * Possible values are
+ * <ul>
+ * <li><code>FlowLayout.TOP</code>
+ * <li><code>FlowLayout.BOTTOM</code>
+ * <li><code>FlowLayout.CENTER</code>
+ * <li><code>FlowLayout.LEADING</code>
+ * <li><code>FlowLayout.TRAILING</code>
+ * </ul>
+ * @param align one of the alignment values shown above
+ * @see #getAlignment()
+ * @since JDK1.1
+ */
+ public void setAlignment(int align) {
+ this.newAlign = align;
+
+ // this.align is used only for serialization compatibility,
+ // so set it to a value compatible with the 1.1 version
+ // of the class
+
+ switch (align) {
+ case LEADING:
+ this.align = TOP;
+ break;
+ case TRAILING:
+ this.align = BOTTOM;
+ break;
+ default:
+ this.align = align;
+ break;
+ }
+ }
+
+ /**
+ * Gets the horizontal gap between components.
+ * @return the horizontal gap between components
+ * @see java.awt.FlowLayout#setHgap
+ * @since JDK1.1
+ */
+ public int getHgap() {
+ return hgap;
+ }
+
+ /**
+ * Sets the horizontal gap between components.
+ * @param hgap the horizontal gap between components
+ * @see java.awt.FlowLayout#getHgap
+ * @since JDK1.1
+ */
+ public void setHgap(int hgap) {
+ this.hgap = hgap;
+ }
+
+ /**
+ * Gets the vertical gap between components.
+ * @return the vertical gap between components
+ * @see java.awt.FlowLayout#setVgap
+ * @since JDK1.1
+ */
+ public int getVgap() {
+ return vgap;
+ }
+
+ /**
+ * Sets the vertical gap between components.
+ * @param vgap the vertical gap between components
+ * @see java.awt.FlowLayout#getVgap
+ * @since JDK1.1
+ */
+ public void setVgap(int vgap) {
+ this.vgap = vgap;
+ }
+
+ /**
+ * Adds the specified component to the layout. Not used by this class.
+ * @param name the name of the component
+ * @param comp the component to be added
+ */
+ public void addLayoutComponent(String name, Component comp) {
+ }
+
+ /**
+ * Removes the specified component from the layout. Not used by
+ * this class.
+ * @param comp the component to remove
+ * @see java.awt.Container#removeAll
+ */
+ public void removeLayoutComponent(Component comp) {
+ }
+
+ /**
+ * Returns the preferred dimensions for this layout given the
+ * <i>visible</i> components in the specified target container.
+ * @param target the component which needs to be laid out
+ * @return the preferred dimensions to lay out the
+ * subcomponents of the specified container
+ * @see java.awt.Container
+ * @see #minimumLayoutSize
+ * @see java.awt.Container#getPreferredSize
+ */
+ public Dimension preferredLayoutSize(Container target) {
+ synchronized (target.getTreeLock()) {
+ Dimension dim = new Dimension(0, 0);
+ int nmembers = target.getComponentCount();
+ boolean firstVisibleComponent = true;
+
+ for (int i = 0; i < nmembers; i++) {
+ Component m = target.getComponent(i);
+ if (m.isVisible()) {
+ Dimension d = m.getPreferredSize();
+ dim.width = Math.max(dim.width, d.width);
+ if (firstVisibleComponent) {
+ firstVisibleComponent = false;
+ } else {
+ dim.height += vgap;
+ }
+ dim.height += d.height;
+ }
+ }
+ Insets insets = target.getInsets();
+ dim.width += insets.left + insets.right + hgap * 2;
+ dim.height += insets.top + insets.bottom + vgap * 2;
+ return dim;
+ }
+ }
+
+ /**
+ * Returns the minimum dimensions needed to layout the <i>visible</i>
+ * components contained in the specified target container.
+ * @param target the component which needs to be laid out
+ * @return the minimum dimensions to lay out the
+ * subcomponents of the specified container
+ * @see #preferredLayoutSize
+ * @see java.awt.Container
+ * @see java.awt.Container#doLayout
+ */
+ public Dimension minimumLayoutSize(Container target) {
+ synchronized (target.getTreeLock()) {
+ Dimension dim = new Dimension(0, 0);
+ int nmembers = target.getComponentCount();
+
+ for (int i = 0; i < nmembers; i++) {
+ Component m = target.getComponent(i);
+ if (m.isVisible()) {
+ Dimension d = m.getMinimumSize();
+ dim.width = Math.max(dim.width, d.width);
+ if (i > 0) {
+ dim.height += vgap;
+ }
+ dim.height += d.height;
+ }
+ }
+ Insets insets = target.getInsets();
+ dim.width += insets.left + insets.right + hgap * 2;
+ dim.height += insets.top + insets.bottom + vgap * 2;
+ return dim;
+ }
+ }
+
+ /**
+ * Centers the elements in the specified row, if there is any slack.
+ * @param target the component which needs to be moved
+ * @param x the x coordinate
+ * @param y the y coordinate
+ * @param width the width dimensions
+ * @param height the height dimensions
+ * @param columnStart the beginning of the row
+ * @param columnEnd the the ending of the row
+ */
+ private void moveComponents(Container target, int x, int y, int width, int height,
+ int columnStart, int columnEnd, boolean ltr) {
+ synchronized (target.getTreeLock()) {
+ switch (newAlign) {
+ case TOP:
+ y += ltr ? 0 : height;
+ break;
+ case CENTER:
+ y += height / 2;
+ break;
+ case BOTTOM:
+ y += ltr ? height : 0;
+ break;
+ case LEADING:
+ break;
+ case TRAILING:
+ y += height;
+ break;
+ }
+ for (int i = columnStart; i < columnEnd; i++) {
+ Component m = target.getComponent(i);
+ if (m.isVisible()) {
+ if (ltr) {
+ m.setLocation(x + (width - m.getWidth()) / 2,y);
+ } else {
+ m.setLocation(x + (width - m.getWidth()) / 2, target.getHeight() - y - m.getHeight());
+ }
+ y += m.getHeight() + vgap;
+ }
+ }
+ }
+ }
+
+ /**
+ * Lays out the container. This method lets each component take
+ * its preferred size by reshaping the components in the
+ * target container in order to satisfy the constraints of
+ * this <code>FlowLayout</code> object.
+ * @param target the specified component being laid out
+ * @see java.awt.Container
+ * @see java.awt.Container#doLayout
+ */
+ public void layoutContainer(Container target) {
+ synchronized (target.getTreeLock()) {
+ computeDimensions(target);
+ Insets insets = target.getInsets();
+ int maxheight = target.getHeight() - (insets.top + insets.bottom + vgap * 2);
+ int nmembers = target.getComponentCount();
+ int x = insets.left + hgap, y = 0;
+ int columnw = 0, start = 0;
+
+ boolean ltr = target.getComponentOrientation().isLeftToRight();
+
+ for (int i = 0; i < nmembers; i++) {
+ Component m = target.getComponent(i);
+ if (m.isVisible()) {
+ //Dimension d = m.getPreferredSize();
+ m.setSize(maxDimension);
+
+ if ((y == 0) || ((y + maxDimension.height) <= maxheight )) {
+ if (y > 0) {
+ y += vgap;
+ }
+ y += maxDimension.height;
+ columnw = Math.max(columnw, maxDimension.width);
+ } else {
+ moveComponents(target, x, insets.top + vgap, columnw, maxheight - y, start, i, ltr);
+ y = maxDimension.height;
+ x += hgap + columnw;
+ columnw = maxDimension.width;
+ start = i;
+ }
+ }
+ }
+ moveComponents(target, x, insets.top + vgap, columnw, maxheight - y, start, nmembers, ltr);
+ }
+ }
+
+ private void computeDimensions(Container target) {
+ maxDimension = new Dimension(0, 0);
+ for(int i = 0; i< target.getComponentCount(); i++) {
+ Component m = target.getComponent(i);
+ if(m.isVisible()) {
+ Dimension d = m.getPreferredSize();
+ maxDimension.setSize(Math.max(maxDimension.getWidth(),d.getWidth()),Math.max(maxDimension.getHeight(),d.getHeight()));
+ }
+ }
+ }
+
+ //
+ // the internal serial version which says which version was written
+ // - 0 (default) for versions before the Java 2 platform, v1.2
+ // - 1 for version >= Java 2 platform v1.2, which includes "newAlign" field
+ //
+ private static final int currentSerialVersion = 1;
+ /**
+ * This represent the <code>currentSerialVersion</code>
+ * which is bein used. It will be one of two values :
+ * <code>0</code> versions before Java 2 platform v1.2..
+ * <code>1</code> versions after Java 2 platform v1.2..
+ *
+ * @serial
+ * @since 1.2
+ */
+ private int serialVersionOnStream = currentSerialVersion;
+
+ /**
+ * Reads this object out of a serialization stream, handling
+ * objects written by older versions of the class that didn't contain all
+ * of the fields we use now..
+ */
+ private void readObject(ObjectInputStream stream)
+ throws IOException, ClassNotFoundException {
+ stream.defaultReadObject();
+
+ if (serialVersionOnStream < 1) {
+ // "newAlign" field wasn't present, so use the old "align" field.
+ setAlignment(this.align);
+ }
+ serialVersionOnStream = currentSerialVersion;
+ }
+
+ /**
+ * Returns a string representation of this <code>FlowLayout</code>
+ * object and its values.
+ * @return a string representation of this layout
+ */
+ @Override
+ public String toString() {
+ String str = "";
+ switch (align) {
+ case TOP:
+ str = ",align=top";
+ break;
+ case CENTER:
+ str = ",align=center";
+ break;
+ case BOTTOM:
+ str = ",align=bottom";
+ break;
+ case LEADING:
+ str = ",align=leading";
+ break;
+ case TRAILING:
+ str = ",align=trailing";
+ break;
+ }
+ return getClass().getName() + "[hgap=" + hgap + ",vgap=" + vgap + str + "]";
+ }
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.utils.ui;
+
+import javax.swing.SwingUtilities;
+
+public class UiUtils {
+
+ public static void invokeInEDT(final Thread runner, final boolean waitForComplete) {
+ if(SwingUtilities.isEventDispatchThread()) {
+ runner.run();
+ if(waitForComplete) {
+ try {
+ runner.join();
+ } catch(Throwable t) {}
+ }
+ }
+ else {
+ if(waitForComplete) {
+ try {
+ SwingUtilities.invokeAndWait(runner);
+ } catch(Throwable t) {}
+ } else {
+ SwingUtilities.invokeLater(runner);
+ }
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.utils.ui;
+
+import java.awt.Component;
+import java.awt.Container;
+import java.awt.Dimension;
+import java.awt.Insets;
+import java.awt.LayoutManager;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+
+/**
+ * Similar to <tt>FlowLayout</tt>, but arranges items vertically
+ * License : LGPL
+ * @author christophe.marchand@labodev.com
+ * @since Nov 23, 2003
+ */
+public class VerticalFlowLayout implements LayoutManager, java.io.Serializable {
+ /**
+ * This value indicates that each column of components
+ * should be top-justified.
+ */
+ public static final int TOP = 0;
+
+ /**
+ * This value indicates that each column of components
+ * should be centered.
+ */
+ public static final int CENTER = 1;
+
+ /**
+ * This value indicates that each column of components
+ * should be bottom-justified.
+ */
+ public static final int BOTTOM = 2;
+
+ /**
+ * This value indicates that each column of components
+ * should be justified to the leading edge of the container's
+ * orientation, for example, to the top in top-to-bottom orientations.
+ *
+ * @see java.awt.Component#getComponentOrientation
+ * @see java.awt.ComponentOrientation
+ * @since 1.2
+ * Package-private pending API change approval
+ */
+ public static final int LEADING = 3;
+
+ /**
+ * This value indicates that each column of components
+ * should be justified to the trailing edge of the container's
+ * orientation, for example, to the bottom in top-to-bottom orientations.
+ *
+ * @see java.awt.Component#getComponentOrientation
+ * @see java.awt.ComponentOrientation
+ * @since 1.2
+ * Package-private pending API change approval
+ */
+ public static final int TRAILING = 4;
+
+ /**
+ * <code>align</code> is the property that determines
+ * how each row distributes empty space.
+ * It can be one of the following values:
+ * <ul>
+ * <code>TOP</code>
+ * <code>BOTTOM</code>
+ * <code>CENTER</code>
+ * <code>LEADING</code>
+ * <code>TRAILING</code>
+ * </ul>
+ *
+ * @serial
+ * @see #getAlignment
+ * @see #setAlignment
+ */
+ int align; // This is for 1.1 serialization compatibility
+
+ /**
+ * <code>newAlign</code> is the property that determines
+ * how each row distributes empty space for the Java 2 platform,
+ * v1.2 and greater.
+ * It can be one of the following three values:
+ * <ul>
+ * <code>TOP</code>
+ * <code>BOTTOM</code>
+ * <code>CENTER</code>
+ * <code>LEADING</code>
+ * <code>TRAILING</code>
+ * </ul>
+ *
+ * @serial
+ * @since 1.2
+ * @see #getAlignment
+ * @see #setAlignment
+ */
+ int newAlign; // This is the one we actually use
+
+ /**
+ * The flow layout manager allows a seperation of
+ * components with gaps. The horizontal gap will
+ * specify the space between components.
+ *
+ * @serial
+ * @see #getHgap
+ * @see #setHgap
+ */
+ int hgap;
+
+ /**
+ * The flow layout manager allows a seperation of
+ * components with gaps. The vertical gap will
+ * specify the space between rows.
+ *
+ * @serial
+ * @see #getVgap
+ * @see #setVgap
+ */
+ int vgap;
+
+ /*
+ * JDK 1.1 serialVersionUID
+ */
+ private static final long serialVersionUID = -7262534874583282631L;
+
+ /**
+ * Constructs a new <code>FlowLayout</code> with a centered alignment and a
+ * default 5-unit horizontal and vertical gap.
+ */
+ public VerticalFlowLayout() {
+ this(CENTER, 5, 5);
+ }
+
+ /**
+ * Constructs a new <code>FlowLayout</code> with the specified
+ * alignment and a default 5-unit horizontal and vertical gap.
+ * The value of the alignment argument must be one of
+ * <code>FlowLayout.TOP</code>, <code>FlowLayout.BOTTOM</code>,
+ * or <code>FlowLayout.CENTER</code>.
+ * @param align the alignment value
+ */
+ public VerticalFlowLayout(int align) {
+ this(align, 5, 5);
+ }
+
+ /**
+ * Creates a new flow layout manager with the indicated alignment
+ * and the indicated horizontal and vertical gaps.
+ * <p>
+ * The value of the alignment argument must be one of
+ * <code>FlowLayout.TOP</code>, <code>FlowLayout.BOTTOM</code>,
+ * or <code>FlowLayout.CENTER</code>.
+ * @param align the alignment value
+ * @param hgap the horizontal gap between components
+ * @param vgap the vertical gap between components
+ */
+ public VerticalFlowLayout(int align, int hgap, int vgap) {
+ this.hgap = hgap;
+ this.vgap = vgap;
+ setAlignment(align);
+ }
+
+ /**
+ * Gets the alignment for this layout.
+ * Possible values are <code>FlowLayout.TOP</code>,
+ * <code>FlowLayout.BOTTOM</code>, <code>FlowLayout.CENTER</code>,
+ * <code>FlowLayout.LEADING</code>,
+ * or <code>FlowLayout.TRAILING</code>.
+ * @return the alignment value for this layout
+ * @see java.awt.FlowLayout#setAlignment
+ * @since JDK1.1
+ */
+ public int getAlignment() {
+ return newAlign;
+ }
+
+ /**
+ * Sets the alignment for this layout.
+ * Possible values are
+ * <ul>
+ * <li><code>FlowLayout.TOP</code>
+ * <li><code>FlowLayout.BOTTOM</code>
+ * <li><code>FlowLayout.CENTER</code>
+ * <li><code>FlowLayout.LEADING</code>
+ * <li><code>FlowLayout.TRAILING</code>
+ * </ul>
+ * @param align one of the alignment values shown above
+ * @see #getAlignment()
+ * @since JDK1.1
+ */
+ public void setAlignment(int align) {
+ this.newAlign = align;
+
+ // this.align is used only for serialization compatibility,
+ // so set it to a value compatible with the 1.1 version
+ // of the class
+
+ switch (align) {
+ case LEADING:
+ this.align = TOP;
+ break;
+ case TRAILING:
+ this.align = BOTTOM;
+ break;
+ default:
+ this.align = align;
+ break;
+ }
+ }
+
+ /**
+ * Gets the horizontal gap between components.
+ * @return the horizontal gap between components
+ * @see java.awt.FlowLayout#setHgap
+ * @since JDK1.1
+ */
+ public int getHgap() {
+ return hgap;
+ }
+
+ /**
+ * Sets the horizontal gap between components.
+ * @param hgap the horizontal gap between components
+ * @see java.awt.FlowLayout#getHgap
+ * @since JDK1.1
+ */
+ public void setHgap(int hgap) {
+ this.hgap = hgap;
+ }
+
+ /**
+ * Gets the vertical gap between components.
+ * @return the vertical gap between components
+ * @see java.awt.FlowLayout#setVgap
+ * @since JDK1.1
+ */
+ public int getVgap() {
+ return vgap;
+ }
+
+ /**
+ * Sets the vertical gap between components.
+ * @param vgap the vertical gap between components
+ * @see java.awt.FlowLayout#getVgap
+ * @since JDK1.1
+ */
+ public void setVgap(int vgap) {
+ this.vgap = vgap;
+ }
+
+ /**
+ * Adds the specified component to the layout. Not used by this class.
+ * @param name the name of the component
+ * @param comp the component to be added
+ */
+ public void addLayoutComponent(String name, Component comp) {
+ }
+
+ /**
+ * Removes the specified component from the layout. Not used by
+ * this class.
+ * @param comp the component to remove
+ * @see java.awt.Container#removeAll
+ */
+ public void removeLayoutComponent(Component comp) {
+ }
+
+ /**
+ * Returns the preferred dimensions for this layout given the
+ * <i>visible</i> components in the specified target container.
+ * @param target the component which needs to be laid out
+ * @return the preferred dimensions to lay out the
+ * subcomponents of the specified container
+ * @see java.awt.Container
+ * @see #minimumLayoutSize
+ * @see java.awt.Container#getPreferredSize
+ */
+ public Dimension preferredLayoutSize(Container target) {
+ synchronized (target.getTreeLock()) {
+ Dimension dim = new Dimension(0, 0);
+ int nmembers = target.getComponentCount();
+ boolean firstVisibleComponent = true;
+
+ for (int i = 0; i < nmembers; i++) {
+ Component m = target.getComponent(i);
+ if (m.isVisible()) {
+ Dimension d = m.getPreferredSize();
+ dim.width = Math.max(dim.width, d.width);
+ if (firstVisibleComponent) {
+ firstVisibleComponent = false;
+ } else {
+ dim.height += vgap;
+ }
+ dim.height += d.height;
+ }
+ }
+ Insets insets = target.getInsets();
+ dim.width += insets.left + insets.right + hgap * 2;
+ dim.height += insets.top + insets.bottom + vgap * 2;
+ return dim;
+ }
+ }
+
+ /**
+ * Returns the minimum dimensions needed to layout the <i>visible</i>
+ * components contained in the specified target container.
+ * @param target the component which needs to be laid out
+ * @return the minimum dimensions to lay out the
+ * subcomponents of the specified container
+ * @see #preferredLayoutSize
+ * @see java.awt.Container
+ * @see java.awt.Container#doLayout
+ */
+ public Dimension minimumLayoutSize(Container target) {
+ synchronized (target.getTreeLock()) {
+ Dimension dim = new Dimension(0, 0);
+ int nmembers = target.getComponentCount();
+
+ for (int i = 0; i < nmembers; i++) {
+ Component m = target.getComponent(i);
+ if (m.isVisible()) {
+ Dimension d = m.getMinimumSize();
+ dim.width = Math.max(dim.width, d.width);
+ if (i > 0) {
+ dim.height += vgap;
+ }
+ dim.height += d.height;
+ }
+ }
+ Insets insets = target.getInsets();
+ dim.width += insets.left + insets.right + hgap * 2;
+ dim.height += insets.top + insets.bottom + vgap * 2;
+ return dim;
+ }
+ }
+
+ /**
+ * Centers the elements in the specified row, if there is any slack.
+ * @param target the component which needs to be moved
+ * @param x the x coordinate
+ * @param y the y coordinate
+ * @param width the width dimensions
+ * @param height the height dimensions
+ * @param columnStart the beginning of the row
+ * @param columnEnd the the ending of the row
+ */
+ private void moveComponents(Container target, int x, int y, int width, int height,
+ int columnStart, int columnEnd, boolean ltr) {
+ synchronized (target.getTreeLock()) {
+ switch (newAlign) {
+ case TOP:
+ y += ltr ? 0 : height;
+ break;
+ case CENTER:
+ y += height / 2;
+ break;
+ case BOTTOM:
+ y += ltr ? height : 0;
+ break;
+ case LEADING:
+ break;
+ case TRAILING:
+ y += height;
+ break;
+ }
+ for (int i = columnStart; i < columnEnd; i++) {
+ Component m = target.getComponent(i);
+ if (m.isVisible()) {
+ if (ltr) {
+ //m.setLocation(x, y + (height - m.getHeight()) / 2);
+ m.setLocation(x,y);
+ } else {
+ //m.setLocation(target.getWidth() - x - m.getWidth(), y + (height - m.getHeight()) / 2);
+ m.setLocation(x, target.getHeight() - y - m.getHeight());
+ }
+ //x += m.getWidth() + hgap;
+ y += m.getHeight() + vgap;
+ }
+ }
+ }
+ }
+
+ /**
+ * Lays out the container. This method lets each component take
+ * its preferred size by reshaping the components in the
+ * target container in order to satisfy the constraints of
+ * this <code>FlowLayout</code> object.
+ * @param target the specified component being laid out
+ * @see java.awt.Container
+ * @see java.awt.Container#doLayout
+ */
+ public void layoutContainer(Container target) {
+ synchronized (target.getTreeLock()) {
+ Insets insets = target.getInsets();
+ int maxheight = target.getHeight() - (insets.top + insets.bottom + vgap * 2);
+ int nmembers = target.getComponentCount();
+ int x = insets.left + hgap, y = 0;
+ int columnw = 0, start = 0;
+
+ boolean ltr = target.getComponentOrientation().isLeftToRight();
+
+ for (int i = 0; i < nmembers; i++) {
+ Component m = target.getComponent(i);
+ if (m.isVisible()) {
+ Dimension d = m.getPreferredSize();
+ m.setSize(d.width, d.height);
+
+ if ((y == 0) || ((y + d.height) <= maxheight )) {
+ if (y > 0) {
+ y += vgap;
+ }
+ y += d.height;
+ columnw = Math.max(columnw, d.width);
+ } else {
+ moveComponents(target, x, insets.top + vgap, columnw, maxheight - y, start, i, ltr);
+ y = d.height;
+ x += hgap + columnw;
+ columnw = d.width;
+ start = i;
+ }
+ }
+ }
+ moveComponents(target, x, insets.top + vgap, columnw, maxheight - y, start, nmembers, ltr);
+ }
+ }
+
+ //
+ // the internal serial version which says which version was written
+ // - 0 (default) for versions before the Java 2 platform, v1.2
+ // - 1 for version >= Java 2 platform v1.2, which includes "newAlign" field
+ //
+ private static final int currentSerialVersion = 1;
+ /**
+ * This represent the <code>currentSerialVersion</code>
+ * which is bein used. It will be one of two values :
+ * <code>0</code> versions before Java 2 platform v1.2..
+ * <code>1</code> versions after Java 2 platform v1.2..
+ *
+ * @serial
+ * @since 1.2
+ */
+ private int serialVersionOnStream = currentSerialVersion;
+
+ /**
+ * Reads this object out of a serialization stream, handling
+ * objects written by older versions of the class that didn't contain all
+ * of the fields we use now..
+ */
+ private void readObject(ObjectInputStream stream)
+ throws IOException, ClassNotFoundException {
+ stream.defaultReadObject();
+
+ if (serialVersionOnStream < 1) {
+ // "newAlign" field wasn't present, so use the old "align" field.
+ setAlignment(this.align);
+ }
+ serialVersionOnStream = currentSerialVersion;
+ }
+
+ /**
+ * Returns a string representation of this <code>FlowLayout</code>
+ * object and its values.
+ * @return a string representation of this layout
+ */
+ @Override
+ public String toString() {
+ String str = "";
+ switch (align) {
+ case TOP:
+ str = ",align=top";
+ break;
+ case CENTER:
+ str = ",align=center";
+ break;
+ case BOTTOM:
+ str = ",align=bottom";
+ break;
+ case LEADING:
+ str = ",align=leading";
+ break;
+ case TRAILING:
+ str = ",align=trailing";
+ break;
+ }
+ return getClass().getName() + "[hgap=" + hgap + ",vgap=" + vgap + str + "]";
+ }
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios;
+
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import java.awt.BorderLayout;
+import java.awt.Dimension;
+import java.awt.Toolkit;
+
+import javax.swing.ImageIcon;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JProgressBar;
+import javax.swing.JWindow;
+
+import fr.gouv.finances.cp.utils.ui.IhmFactory;
+import fr.gouv.finances.cp.utils.ui.UiUtils;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import fr.gouv.finances.dgfip.xemelios.common.listeners.StartListener;
+import fr.gouv.finances.cp.xemelios.debug.CheckThreadViolationRepaintManager;
+import fr.gouv.finances.dgfip.xemelios.ui.ImageResources;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import javax.swing.RepaintManager;
+
+/**
+ * Fenêtre splash de Xemelios. C'est elle qui lance la MainWindow
+ * @author chm
+ */
+public class Splash extends JWindow implements StartListener {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 3257570598480654904L;
+ private static final int MAX_PROGRESS=8;
+ public static Splash instance = null;
+ private JProgressBar progress;
+ private int requiredProgress=0;
+
+ private PropertiesExpansion applicationProperties;
+
+ static {
+ if("true".equals(System.getProperty(Constants.SYS_PROP_DEBUG_UI))) {
+ RepaintManager.setCurrentManager(new CheckThreadViolationRepaintManager());
+ }
+ }
+
+ public Splash(PropertiesExpansion applicationProperties, String[] args) {
+ super();
+ this.applicationProperties = applicationProperties;
+ instance = this;
+ final Displayer displayer = new Displayer(this);
+ UiUtils.invokeInEDT(displayer,true);
+ Starter starter = new Starter(applicationProperties,args,this);
+ starter.run();
+
+ }
+
+ protected void initialize() {
+ JFrame.setDefaultLookAndFeelDecorated(true);
+ //IhmFactory iF = IhmFactory.newInstance();
+ ImageIcon ii = IhmFactory.getIconFromResource(ImageResources.SPLASH);
+ JPanel pane = new JPanel(new BorderLayout());
+ pane.add(new JLabel(ii),BorderLayout.CENTER);
+ pane.add(progress=new JProgressBar(JProgressBar.HORIZONTAL,0,MAX_PROGRESS),BorderLayout.SOUTH);
+ getContentPane().add(pane);
+ pack();
+ Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
+ setLocation((int)(screen.getWidth()-getWidth())/2, (int)(screen.getHeight()-getHeight())/2);
+ addFocusListener(new java.awt.event.FocusListener() {
+ @Override
+ public void focusGained(java.awt.event.FocusEvent e) {
+ toFront();
+ }
+ @Override
+ public void focusLost(java.awt.event.FocusEvent e) {
+ toFront();
+ }
+ });
+ }
+ @Override
+ public void pushProgress() {
+ final Thread runner = new Thread() {
+ @Override
+ public void run() {
+ int p = requiredProgress;
+ p++;
+ if(p<MAX_PROGRESS) {
+ progress.setValue(p);
+
+ } else if(p==MAX_PROGRESS) {
+ progress.setValue(MAX_PROGRESS);
+ }
+ requiredProgress = p;
+ }
+ };
+ UiUtils.invokeInEDT(runner,true);
+ }
+ @Override
+ public void completeProgress() {
+ final Thread runner = new Thread() {
+ @Override
+ public void run() {
+ progress.setValue(MAX_PROGRESS);
+ }
+ };
+ UiUtils.invokeInEDT(runner,true);
+ }
+ /**
+ * @see fr.gouv.finances.cp.xemelios.common.listeners.StartListener#notifyMessage(java.lang.String)
+ */
+ @Override
+ public void notifyMessage(String msg) {
+ // les messages ne sont pas gérés pour le moment
+ }
+ /**
+ * @see fr.gouv.finances.cp.xemelios.common.listeners.StartListener#notifyProgress(int)
+ */
+ @Override
+ public void notifyProgress(int progress) {
+ if(progress>=0 && progress<=100) this.progress.setValue(progress);
+
+ }
+ /**
+ * Point d'entrée en mode développement
+ * @param args
+ */
+ public static void main(final String[] args) {
+ PropertiesExpansion pe = new PropertiesExpansion();
+ for(String key:System.getProperties().stringPropertyNames())
+ pe.setProperty(key, System.getProperty(key));
+ Splash splash = new Splash(pe, args);
+ }
+ private static final class Displayer extends Thread {
+ private Splash splash = null;
+ public Displayer(Splash splash) {
+ this.splash=splash;
+ }
+ @Override
+ public void run() {
+ splash.initialize();
+ splash.setVisible(true);
+ }
+ public Splash getSplash() { return splash; }
+ }
+ private final class Starter implements Runnable {
+ Splash sl;
+ String[] args = null;
+ public Starter(PropertiesExpansion applicationProperties, String[] args,Splash sl) {
+ super();
+ this.args = args;
+ this.sl=sl;
+ }
+
+ @Override
+ public void run() {
+ try {
+ Thread.sleep(100);
+ } catch(Throwable t) {}
+ if(sl!=null) sl.pushProgress();
+ final Thread runner = new Thread() {
+ @Override
+ public void run() {
+ try {
+ new MainWindow(Splash.this.applicationProperties, Constants.NOM_APP, sl, args);
+ } catch(Throwable t) {
+ t.printStackTrace();
+ }
+ }
+ };
+ UiUtils.invokeInEDT(runner,true);
+ try {
+ Thread.sleep(1000);
+ } catch(Throwable t) {}
+ if(sl!=null) {
+ sl.setVisible(false);
+ sl.dispose();
+ }
+ }
+ }
+}
--- /dev/null
+//XXX moche, mais copié sur le AskPassword.java d'origine...
+// je suis d'accord, mais il est autorise de la reecrire...
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.auth;
+
+import java.awt.FlowLayout;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.KeyEvent;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.Properties;
+
+import javax.swing.AbstractAction;
+import javax.swing.Action;
+import javax.swing.JButton;
+import javax.swing.JComponent;
+import javax.swing.JDialog;
+import javax.swing.JFrame;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JPasswordField;
+import javax.swing.JRootPane;
+import javax.swing.JTextArea;
+import javax.swing.JTextField;
+import javax.swing.KeyStroke;
+
+import com.jgoodies.forms.builder.PanelBuilder;
+import com.jgoodies.forms.layout.CellConstraints;
+import com.jgoodies.forms.layout.FormLayout;
+
+import fr.gouv.finances.cp.utils.ui.IhmFactory;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+
+/**
+ * Permet de demander les informations de connexion à l'utilisateur
+ * @author chm
+ */
+public class LoginDialog extends JDialog {
+
+ private static final long serialVersionUID = 3546362837975971889L;
+
+ static {
+ if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
+ setDefaultLookAndFeelDecorated(true);
+ }
+ }
+ public static final transient String DLG_TITLE = "Authentification...";
+ private JTextField loginTextField;
+ private JPasswordField passwordField;
+ private JButton pbOk, pbCancel;
+ private boolean ret;
+ private String userName;
+ private String password;
+ private Action escapeAction;
+ private Properties props;
+ private boolean showLogin;
+ private boolean showPassword;
+
+ public LoginDialog(JFrame owner, boolean showLogin, boolean showPassword) {
+ super(owner, DLG_TITLE, true);
+ this.showLogin = showLogin;
+ this.showPassword = showPassword;
+ File f = new File(System.getProperty("user.home"), "xemelios.properties");
+ props = new Properties();
+ if (f.exists()) {
+ try {
+ props.load(new FileInputStream(f));
+ } catch (IOException ioEx) {
+ }
+ }
+ initComposants();
+ }
+
+ protected void initComposants() {
+ int sepInfo = 2;
+ int lineInfo = sepInfo + 2;
+ int sepData = lineInfo + 2;
+ int userLine = sepData + 2;
+ int pwdLine = userLine + 2;
+ int buttonLine = pwdLine + 2;
+
+ JTextArea area = null;
+
+ FormLayout fl = new FormLayout(
+ // 0 1 2 3 4 5
+ /* "1dlu,20dlu,pref,1dlu,pref,1dlu", */
+ "3dlu,20dlu,pref,3dlu,pref,3dlu",
+ "7dlu," + // 0
+ "pref," + // 1
+ "3dlu," + // 2
+ "pref," + // 3
+ "7dlu," + // 4
+ "pref," + // 5
+ "3dlu," + // 6
+ "pref," + // 7
+ "3dlu," + // 8
+ "pref," + // 9
+ "10dlu," + // 10
+ "pref," + // 11
+ "3dlu"); // 12
+ CellConstraints cc = new CellConstraints();
+ PanelBuilder pb = new PanelBuilder(fl);
+ IhmFactory iF = IhmFactory.newInstance();
+
+ pb.addSeparator("Informations", cc.xyw(2, sepInfo, 4));
+ pb.add(area = new JTextArea(), cc.xyw(3, lineInfo, 3));
+
+ pb.addSeparator("Données", cc.xyw(2, sepData, 4));
+ loginTextField = new JTextField();
+ if (showLogin) {
+ pb.add(iF.newLabel("Utilisateur", "normal"), cc.xy(3, userLine));
+ pb.add(loginTextField, cc.xy(5, userLine));
+ }
+ if (showPassword) {
+ pb.add(iF.newLabel("Mot de passe", "normal"), cc.xy(3, pwdLine));
+ pb.add(passwordField = new JPasswordField(), cc.xy(5, pwdLine));
+ }
+
+ JPanel bPane = new JPanel(new FlowLayout(FlowLayout.CENTER));
+ pbCancel = new JButton(escapeAction);
+ pbOk = new JButton("Ok");
+ bPane.add(pbOk);
+ bPane.add(pbCancel);
+
+ pb.add(bPane, cc.xyw(2, buttonLine, 4));
+
+ passwordField.setColumns(15);
+ add(pb.getPanel());
+
+ area.setEditable(false);
+ area.setLineWrap(true);
+ area.setRows(3);
+ area.setBackground(getBackground());
+
+ area.setText("Veuillez vos informations de connexions\r\npour accéder à " + Constants.NOM_APP);
+
+ pbOk.setDefaultCapable(true);
+ pbOk.addActionListener(new ActionListener() {
+
+ public void actionPerformed(ActionEvent e) {
+ if (showLogin && (loginTextField.getText() == null || loginTextField.getText().length() == 0)) {
+ JOptionPane.showMessageDialog(LoginDialog.this, "L'identifiant est obligatoire", "Erreur", JOptionPane.ERROR_MESSAGE);
+ loginTextField.grabFocus();
+ return;
+ }
+ if (showPassword && passwordField.getPassword().length == 0) {
+ JOptionPane.showMessageDialog(LoginDialog.this, "Le mot de passe est obligatoire", "Erreur", JOptionPane.ERROR_MESSAGE);
+ passwordField.grabFocus();
+ return;
+ }
+ userName = loginTextField.getText();
+ password = new String(passwordField.getPassword());
+ ret = true;
+ props.setProperty("last.login", userName);
+ try {
+ props.store(new FileOutputStream(new File(System.getProperty("user.home"), "xemelios.properties")), "");
+ } catch (IOException ioEx) {
+ }
+ setVisible(false);
+ }
+ });
+ getRootPane().setDefaultButton(pbOk);
+ pack();
+ setLocationRelativeTo(getParent());
+ }
+
+ public boolean run() {
+ String lastLogin = props.getProperty("last.login");
+ loginTextField.setText(lastLogin);
+ passwordField.setText("");
+ if (lastLogin != null && lastLogin.length() > 0) {
+ passwordField.grabFocus();
+ } else {
+ loginTextField.grabFocus();
+ }
+ setVisible(true);
+ return ret;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public String getUserName() {
+ return userName;
+ }
+
+ @Override
+ protected JRootPane createRootPane() {
+ KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
+ JRootPane rp = new JRootPane();
+ escapeAction = new AbstractAction("Annuler") {
+
+ private static final long serialVersionUID = 1L;
+
+ public void actionPerformed(ActionEvent evt) {
+ ret = false;
+ setVisible(false);
+ }
+ };
+ rp.registerKeyboardAction(escapeAction, "TOTOTOTO", ks, JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
+ }
+
+}
--- /dev/null
+/*
+ *
+ * Copyright
+ * 2009 axYus - www.axyus.com
+ * 2009 Christophe Marchand <christophe.marchand@axyus.com>
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+package fr.gouv.finances.cp.xemelios.controls;
+
+import fr.gouv.finances.cp.utils.ui.DlgGetPair;
+import fr.gouv.finances.dgfip.xemelios.controls.core.AbstractControlContentHandler;
+import fr.gouv.finances.dgfip.xemelios.controls.core.ControlProgressListener;
+import fr.gouv.finances.dgfip.xemelios.controls.core.models.DocumentControlModel;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.dgfip.xemelios.auth.UnauthorizedException;
+import fr.gouv.finances.dgfip.xemelios.common.ToolException;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.data.DataAccessException;
+import fr.gouv.finances.dgfip.xemelios.data.DataConfigurationException;
+import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.TreeSet;
+import java.util.Vector;
+import javax.swing.SwingUtilities;
+import javax.xml.namespace.NamespaceContext;
+import org.apache.log4j.Logger;
+
+/**
+ *
+ * @author Christophe Marchand <christophe.marchand@axyus.com>
+ */
+public class DefaultControlContentHandler extends AbstractControlContentHandler {
+
+ private static final Logger logger = Logger.getLogger(DefaultControlContentHandler.class);
+ private DocumentModel dm;
+ private MainWindow frame;
+
+ public DefaultControlContentHandler(
+ DocumentModel dm,
+ NamespaceContext nsCtx,
+ DocumentControlModel docCtrlMod,
+ Hashtable<String, Object> parameters,
+ MainWindow frame,
+ String file,
+ ControlProgressListener cpl) {
+ super(dm.getId(), nsCtx, docCtrlMod, parameters, file, cpl);
+ this.frame = frame;
+ this.dm = dm;
+ }
+
+ public Pair getCollectivite(String documentModelId, String fileName) throws ToolException {
+ Pair ret = null;
+ if (ret == null) {
+ QueryCollectivite qc = new QueryCollectivite(fileName);
+ qc.setDefaultCollectivite(collectivite);
+ if (SwingUtilities.isEventDispatchThread()) {
+ qc.run();
+ } else {
+ try {
+ SwingUtilities.invokeAndWait(qc);
+ } catch (Throwable t) {
+ }
+ }
+ ret = qc.getRet();
+ if (ret == null) {
+ throw new ToolException("Action interrompue", ToolException.ERROR_INTERRUPTED);
+
+ }
+ }
+ return ret;
+ }
+
+ public Pair getBudget(String documentModelId, Pair collectivite, String fileName) throws ToolException, UnauthorizedException {
+ Pair ret = null;
+ if (ret == null) {
+ TreeSet<Pair> existing = new TreeSet<Pair>();
+ try {
+ existing.addAll(DataLayerManager.getImplementation().getBudgets(dm, collectivite, frame.getConnectedUser()));
+ } catch (DataConfigurationException e) {
+ logger.error("in getBudget", e);
+ } catch (DataAccessException e) {
+ logger.error("in getBudget", e);
+ }
+ Vector<Pair> budgetsDm = dm.getDefaultBudgets();
+ existing.addAll(budgetsDm);
+ if (budget != null && (budget.libelle == null || budget.libelle.length() == 0)) {
+ if (existing.contains(budget)) {
+ for (Iterator<Pair> it = existing.iterator(); it.hasNext();) {
+ Pair p = it.next();
+ if (p.key.equals(budget.key)) {
+ return p;
+ }
+ }
+ }
+ }
+ QueryBudget qb = new QueryBudget(fileName, existing, collectivite.libelle);
+ if (SwingUtilities.isEventDispatchThread()) {
+ qb.run();
+ } else {
+ try {
+ SwingUtilities.invokeAndWait(qb);
+ } catch (Throwable t) {
+ }
+ }
+ ret = qb.getRet();
+ if (ret == null) {
+ throw new ToolException("Action interrompue", ToolException.ERROR_INTERRUPTED);
+ }
+ }
+ return ret;
+ }
+
+ protected class QueryCollectivite implements Runnable {
+
+ private Pair ret;
+ private String fileName;
+ private Pair defaultCollectivite = null;
+
+ public Pair getDefaultCollectivite() {
+ return defaultCollectivite;
+ }
+
+ public void setDefaultCollectivite(Pair defaultCollectivite) {
+ this.defaultCollectivite = defaultCollectivite;
+ }
+
+ public QueryCollectivite(String fileName) {
+ super();
+ this.fileName = fileName;
+ }
+
+ public void run() {
+ DlgGetPair dlg = new DlgGetPair(frame, "Sur quelle collectivité porte ce document : " + fileName + " ?", null, null, collectivite);
+ if (dlg.run()) {
+ ret = new Pair(dlg.getCode(), dlg.getLibelle());
+ } else {
+ importInterupted = true;
+// dlgControl.notifyImportInterupted();
+// dlgControl.setVisible(false);
+ getControlProgressListener().notifyImportInterrupted(true);
+ }
+ }
+
+ public Pair getRet() {
+ return ret;
+ }
+ }
+
+ protected class QueryBudget implements Runnable {
+
+ private String fileName;
+ private TreeSet<Pair> existing;
+ private Pair ret;
+ private String collectivite = null;
+
+ public QueryBudget(String fileName, TreeSet<Pair> existing, String collectivite) {
+ super();
+ this.fileName = fileName;
+ this.existing = existing;
+ this.collectivite = collectivite;
+ }
+
+ public void run() {
+ DlgGetPair dlg = null;
+ dlg = new DlgGetPair(frame, "Sur quel budget porte ce document : " + fileName + " ?", existing, collectivite, budget);
+
+ if (dlg.run()) {
+ ret = new Pair(dlg.getCode(), dlg.getLibelle());
+ } else {
+ if (!importInterupted) {
+// dlgControl.notifyImportInterupted();
+ importInterupted = true;
+ getControlProgressListener().notifyImportInterrupted(false);
+ }
+ }
+ logger.debug("fin de QueryBudget.run()");
+ }
+
+ public Pair getRet() {
+ logger.debug("QueryBudget.getRet()");
+ return ret;
+ }
+ }
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.3" maxVersion="1.3" type="org.netbeans.modules.form.forminfo.JDialogFormInfo">
+ <Properties>
+ <Property name="title" type="java.lang.String" value="Contrôler un flux"/>
+ </Properties>
+ <SyntheticProperties>
+ <SyntheticProperty name="formSizePolicy" type="int" value="1"/>
+ </SyntheticProperties>
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="2"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" attributes="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" attributes="0">
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="jScrollPane1" alignment="1" pref="482" max="32767" attributes="0"/>
+ <Group type="102" alignment="1" attributes="0">
+ <Component id="pbCancel" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="pbOk" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <Group type="102" alignment="1" attributes="0">
+ <Component id="dfFileToImport" pref="458" max="32767" attributes="0"/>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Component id="pbBrowse" min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </Group>
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace min="12" pref="12" max="12" attributes="0"/>
+ <Component id="lblFileToImport" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace min="12" pref="12" max="12" attributes="0"/>
+ <Component id="lblParams" min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="lblFileToImport" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="dfFileToImport" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="pbBrowse" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="lblParams" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="jScrollPane1" pref="257" max="32767" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="pbOk" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="pbCancel" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Component class="javax.swing.JLabel" name="lblFileToImport">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Fichier à importer"/>
+ </Properties>
+ <AuxValues>
+ <AuxValue name="JavaCodeGenerator_VariableLocal" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="JavaCodeGenerator_VariableModifier" type="java.lang.Integer" value="0"/>
+ </AuxValues>
+ </Component>
+ <Component class="javax.swing.JButton" name="pbBrowse">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="..."/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="browse"/>
+ </Events>
+ <AuxValues>
+ <AuxValue name="JavaCodeGenerator_VariableLocal" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="JavaCodeGenerator_VariableModifier" type="java.lang.Integer" value="0"/>
+ </AuxValues>
+ </Component>
+ <Component class="javax.swing.JTextField" name="dfFileToImport">
+ </Component>
+ <Component class="javax.swing.JLabel" name="lblParams">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Paramètres"/>
+ </Properties>
+ <AuxValues>
+ <AuxValue name="JavaCodeGenerator_VariableLocal" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="JavaCodeGenerator_VariableModifier" type="java.lang.Integer" value="0"/>
+ </AuxValues>
+ </Component>
+ <Container class="javax.swing.JScrollPane" name="jScrollPane1">
+ <AuxValues>
+ <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
+ </AuxValues>
+
+ <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
+ <SubComponents>
+ <Component class="org.jdesktop.swingx.JXTable" name="table">
+ <Properties>
+ <Property name="model" type="javax.swing.table.TableModel" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
+ <Connection code="createModel()" type="code"/>
+ </Property>
+ <Property name="sortable" type="boolean" value="false"/>
+ </Properties>
+ <AuxValues>
+ <AuxValue name="JavaCodeGenerator_CreateCodeCustom" type="java.lang.String" value="new JParamTable(createModel());"/>
+ </AuxValues>
+ </Component>
+ </SubComponents>
+ </Container>
+ <Component class="javax.swing.JButton" name="pbOk">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Ok"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="doControl"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="pbCancel">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Annuler"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="cancel"/>
+ </Events>
+ </Component>
+ </SubComponents>
+</Form>
--- /dev/null
+/*
+ *
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 Christophe Marchand <christophe.marchand@axyus.com>
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+package fr.gouv.finances.cp.xemelios.controls;
+
+import fr.gouv.finances.dgfip.xemelios.controls.core.MainControl;
+import fr.gouv.finances.dgfip.xemelios.controls.core.ControlProgressListener;
+import java.awt.Component;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.FocusEvent;
+import java.awt.event.FocusListener;
+import java.awt.event.KeyEvent;
+import java.io.File;
+import java.io.IOException;
+import java.util.Hashtable;
+import java.util.StringTokenizer;
+import java.util.Vector;
+
+import javax.swing.AbstractAction;
+import javax.swing.ActionMap;
+import javax.swing.DefaultCellEditor;
+import javax.swing.InputMap;
+import javax.swing.JButton;
+import javax.swing.JCheckBox;
+import javax.swing.JComboBox;
+import javax.swing.JComponent;
+import javax.swing.JFileChooser;
+import javax.swing.JLabel;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JRootPane;
+import javax.swing.JTable;
+import javax.swing.JTextField;
+import javax.swing.KeyStroke;
+import javax.swing.SwingConstants;
+import javax.swing.SwingUtilities;
+import javax.swing.event.PopupMenuEvent;
+import javax.swing.event.PopupMenuListener;
+import javax.swing.event.TableModelListener;
+import javax.swing.filechooser.FileFilter;
+import javax.swing.table.DefaultTableCellRenderer;
+import javax.swing.table.TableCellEditor;
+import javax.swing.table.TableCellRenderer;
+import javax.swing.table.TableModel;
+import javax.swing.text.Keymap;
+
+import org.apache.log4j.Logger;
+import org.jdesktop.swingx.JXTable;
+
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.controls.core.models.OptionModel;
+import fr.gouv.finances.dgfip.xemelios.controls.core.models.ParamModel;
+import fr.gouv.finances.cp.xemelios.ui.HtmlViewer;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import fr.gouv.finances.dgfip.xemelios.swing.InfiniteGlassPane;
+
+/**
+ *
+ * @author chm
+ */
+public class DlgControl extends javax.swing.JDialog implements ControlProgressListener {
+ private static final Logger logger = Logger.getLogger(DlgControl.class);
+ private static final long serialVersionUID = -4196631171841258162L;
+ private DocumentModel documentModel;
+ private MainControlWrapper mc;
+ private static String lastInputDirectory;
+ private AbstractAction escapeAction;
+ private MainControl.Triplet triplet;
+
+ /** Creates new form DlgControl
+ * @param parent
+ * @param documentModel
+ * @param mc
+ */
+ public DlgControl(java.awt.Frame parent, DocumentModel documentModel, MainControlWrapper mc) {
+ super(parent, false);
+ this.documentModel = documentModel;
+ this.mc = mc;
+ initComponents();
+ InfiniteGlassPane glassPane = new InfiniteGlassPane();
+ this.setGlassPane(glassPane);
+
+ mc.setDlgControl(this);
+ table.packAll();
+ setLocationRelativeTo(getParent());
+ pbOk.setDefaultCapable(true);
+ getRootPane().setDefaultButton(pbOk);
+ }
+
+ @Override
+ protected JRootPane createRootPane() {
+ KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0);
+ JRootPane rp = new JRootPane();
+ escapeAction = new AbstractAction("Annuler") {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ cancel(evt);
+ }
+ };
+ rp.registerKeyboardAction(escapeAction,"TOTOTOTO",ks,JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
+ private void initComponents() {
+ javax.swing.JLabel lblFileToImport;
+ javax.swing.JLabel lblParams;
+ javax.swing.JButton pbBrowse;
+
+ lblFileToImport = new javax.swing.JLabel();
+ pbBrowse = new javax.swing.JButton();
+ dfFileToImport = new javax.swing.JTextField();
+ lblParams = new javax.swing.JLabel();
+ jScrollPane1 = new javax.swing.JScrollPane();
+ table = new JParamTable(createModel());
+ pbOk = new javax.swing.JButton();
+ pbCancel = new javax.swing.JButton();
+
+ setTitle("Analyser un flux");
+ lblFileToImport.setText("Fichier \u00e0 analyser");
+
+ pbBrowse.setText("...");
+ pbBrowse.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ browse(evt);
+ }
+ });
+
+ lblParams.setText("Param\u00e8tres");
+
+ table.setModel(createModel());
+ table.setSortable(false);
+ jScrollPane1.setViewportView(table);
+
+ pbOk.setText("Ok");
+ pbOk.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ doControl(evt);
+ }
+ });
+
+ pbCancel.setText("Annuler");
+ pbCancel.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ cancel(evt);
+ }
+ });
+
+ org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 482, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
+ .add(pbCancel)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(pbOk))
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
+ .add(dfFileToImport, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 433, Short.MAX_VALUE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(pbBrowse))))
+ .add(layout.createSequentialGroup()
+ .add(12, 12, 12)
+ .add(lblFileToImport))
+ .add(layout.createSequentialGroup()
+ .add(12, 12, 12)
+ .add(lblParams)))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(lblFileToImport)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(dfFileToImport, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .add(pbBrowse))
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(lblParams)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(pbOk)
+ .add(pbCancel))
+ .addContainerGap())
+ );
+ pack();
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void cancel(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancel
+ setVisible(false);
+ }//GEN-LAST:event_cancel
+
+ private void doControl(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_doControl
+ // TODO: implement
+ if(doChecks()) {
+ try {
+ mc.writeControlConfigFile();
+ } catch(IOException ioEx) {
+ logger.error("while writting control config file",ioEx);
+ }
+ runControl();
+ }
+ }//GEN-LAST:event_doControl
+
+ private void displayRapport(MainControl.Triplet infoRapport) {
+ StringBuffer uri = new StringBuffer();
+ uri.append("xemelios:/query?collectivite=").append(infoRapport.codeCollectivite).append("&budget=").append(infoRapport.codeBudget);
+ uri.append("&docId=rapport&etatId=DonneesRapport&path=[n:Id/@n:V='").append(infoRapport.iDrapport.replaceAll("'","''")).append("']");
+ MainWindow mw = (MainWindow)getParent();
+ HtmlViewer viewer = new HtmlViewer(uri.toString(),"Rapport de contrôle",mw);
+ mw.getDesk().add(viewer);
+ mw.getDesk().getDesktopManager().maximizeFrame(viewer);
+ viewer.show();
+ }
+ private void browse(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browse
+ JFileChooser fc = new JFileChooser();
+ fc.addChoosableFileFilter(new FileFilter() {
+ @Override
+ public boolean accept(File f) {
+ return f.isDirectory() || f.getName().toUpperCase().endsWith("XML");
+ }
+ @Override
+ public String getDescription() {
+ return "Fichiers XML";
+ }
+ });
+
+ if(documentModel.getExtension()!=null) {
+ fc.addChoosableFileFilter( new FileFilter() {
+ @Override
+ public boolean accept(File f) {
+ return f.isDirectory() || f.getName().toUpperCase().endsWith(documentModel.getExtension().toUpperCase());
+ }
+ @Override
+ public String getDescription() {
+ return documentModel.getLibelleExtension();
+ }
+ });
+ }
+
+ if(lastInputDirectory!=null) {
+ try {
+ fc.setCurrentDirectory(new File(lastInputDirectory));
+ } catch(Throwable t) {
+ // on s'affranchit de la suppression du repertoire
+ }
+ }
+ if(fc.showOpenDialog(this)==JFileChooser.APPROVE_OPTION) {
+ dfFileToImport.setText(fc.getSelectedFile().getAbsolutePath());
+ lastInputDirectory = fc.getSelectedFile().getParent();
+ }
+
+ }//GEN-LAST:event_browse
+
+ private boolean doChecks() {
+ if(dfFileToImport.getText()==null || dfFileToImport.getText().length()==0) {
+ JOptionPane.showMessageDialog(this,"Le fichier à importer est obligatoire","Erreur",JOptionPane.ERROR_MESSAGE);
+ dfFileToImport.grabFocus();
+ return false;
+ }
+ for(ParamModel pm:mc.getDocumentControl().getParams()) {
+ if(!pm.isOptional() && pm.getValue()==null) {
+ JOptionPane.showMessageDialog(this,"Le paramètre "+pm.getName()+" est obligatoire.","Erreur",JOptionPane.ERROR_MESSAGE);
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private void runControl() {
+ File fToCtrl = new File(dfFileToImport.getText());
+ if(!fToCtrl.exists()) {
+ JOptionPane.showMessageDialog(this,"Le fichier indiqué n'existe pas :\n"+dfFileToImport.getText(),"Erreur",JOptionPane.ERROR_MESSAGE);
+ return;
+ }
+ mc.setFileToControl(fToCtrl);
+ Hashtable<String,Object> params = new Hashtable<String,Object>();
+ for(ParamModel pm:mc.getDocumentControl().getParams()) {
+ Object value = null;
+ if(pm.getValue()==null) {
+ logger.debug(pm.getName()+" has no value");
+ continue;
+ } else {
+ if(pm.getSelect()!=null && pm.getSelect().isMultiValued()) {
+ StringTokenizer tokenizer = new StringTokenizer((String)pm.getValue(),DlgEditParam.SEPARATOR);
+ int count = tokenizer.countTokens();
+ String[] values = new String[count];
+ for(int i=0;i<count;i++) {
+ values[i]=tokenizer.nextToken();
+ }
+ value = values;
+ } else {
+ value = pm.getValue();
+ }
+ }
+ params.put(pm.getId(),value);
+ logger.debug("param -> "+pm.getId()+" : "+value.toString());
+ }
+ mc.setParameters(params);
+ getGlassPane().setVisible(true);
+ try {
+ if(SwingUtilities.isEventDispatchThread()) {
+ logger.debug("invoke later");
+ SwingUtilities.invokeLater(mc);
+ } else {
+ logger.debug("invoke now");
+ mc.run();
+ }
+ } catch(Throwable t) {
+ t.printStackTrace();
+ }
+ }
+ public void stopVentilateur() {
+ getGlassPane().setVisible(false);
+ }
+ public void startVentilateur() {
+ getGlassPane().setVisible(true);
+ }
+ public void notifyImportFailed() {
+ JOptionPane.showMessageDialog(this,"L'import du rapport a échoué.","",JOptionPane.ERROR);
+ setVisible(false);
+ }
+ @Override
+ public void notifyImportInterrupted(boolean hide) {
+ JOptionPane.showMessageDialog(this,"L'import du rapport a été imterrompu.","",JOptionPane.CANCEL_OPTION);
+ stopVentilateur();
+ if(hide) setVisible(false);
+ }
+ @Override
+ public void notifyTechniqueValidationFailed() {
+ setVisible(false);
+ }
+ @Override
+ public void notifyImportFinished(MainControl.Triplet triplet) {
+ if(triplet!=null) displayRapport(triplet);
+ setVisible(false);
+ }
+
+ private TableModel createModel() {
+ return new ParamTableModel(null);
+ }
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JTextField dfFileToImport;
+ private javax.swing.JScrollPane jScrollPane1;
+ private javax.swing.JButton pbCancel;
+ private javax.swing.JButton pbOk;
+ private org.jdesktop.swingx.JXTable table;
+ // End of variables declaration//GEN-END:variables
+
+ private class ParamTableModel implements TableModel {
+ private Vector<ParamModel> params;
+ public ParamTableModel(Hashtable<String,Object> existingParams) {
+ super();
+ this.params = mc.getDocumentControl().getParams();
+
+ }
+ @Override
+ public void removeTableModelListener(TableModelListener l) {
+ }
+
+ @Override
+ public void addTableModelListener(TableModelListener l) {
+ }
+
+ @Override
+ public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
+ ParamModel pm = getParam(rowIndex);
+ if(columnIndex==1) pm.setValue(aValue, MainWindow.getInstance().getEnvProperties().getProperty(Constants.SYS_PROP_DATE_FORMAT));
+ }
+
+ @Override
+ public String getColumnName(int columnIndex) {
+ if(columnIndex==0) return "Paramètre";
+ return "Valeur";
+ }
+
+ @Override
+ public Class<?> getColumnClass(int columnIndex) {
+ return String.class;
+ }
+
+ @Override
+ public boolean isCellEditable(int rowIndex, int columnIndex) {
+ return columnIndex==1;
+ }
+
+ @Override
+ public Object getValueAt(int rowIndex, int columnIndex) {
+ ParamModel pm = params.get(rowIndex);
+ if(columnIndex==0) return pm.getName();
+ else if(columnIndex==1) return pm.getValue();
+ return "";
+ }
+
+ @Override
+ public int getRowCount() {
+ return params.size();
+ }
+
+ @Override
+ public int getColumnCount() {
+ return 2;
+ }
+ public ParamModel getParam(int rowIndex) {
+ return params.get(rowIndex);
+ }
+ }
+
+ private class JParamTable extends JXTable {
+ private static final long serialVersionUID = -7291976269965161967L;
+ private MyCellRenderer cellRenderer;
+ private MyCellEditor cellEditor2;
+ public JParamTable(TableModel model) {
+ super(model);
+ if(model instanceof ParamTableModel) {
+ cellRenderer = new MyCellRenderer((ParamTableModel)model);
+ cellEditor2 = new MyCellEditor((ParamTableModel)model);
+ }
+ }
+ public JParamTable() {
+ super();
+ cellRenderer = new MyCellRenderer(null);
+ }
+ @Override
+ public TableCellEditor getCellEditor(int row, int column) {
+ return cellEditor2;
+ }
+ @Override
+ public TableCellRenderer getCellRenderer(int row, int column) {
+ return cellRenderer;
+ }
+
+ @Override
+ public void setModel(TableModel tableModel) {
+ super.setModel(tableModel);
+ if(tableModel!=null && tableModel instanceof ParamTableModel && cellRenderer!=null) {
+ cellRenderer.setModel((ParamTableModel)tableModel);
+ cellEditor2.setModel((ParamTableModel)tableModel);
+ }
+ }
+ }
+ private class MyCellRenderer extends DefaultTableCellRenderer {
+ private static final long serialVersionUID = 6185107566838768220L;
+ private ParamTableModel ptm;
+ public MyCellRenderer(ParamTableModel ptm) {
+ super();
+ this.ptm=ptm;
+ }
+ @Override
+ public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column) {
+ Component ret;
+ if(column==0) {
+ ret = super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
+ JLabel lbl=(JLabel)ret;
+ lbl.setHorizontalAlignment(SwingConstants.LEFT);
+ } else {
+ ParamModel pm = ptm.getParam(row);
+ JLabel lbl;
+ Component c = super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
+ if("string".equals(pm.getDatatype()) || "integer".equals(pm.getDatatype()) || "decimal".equals(pm.getDatatype()) || "date".equals(pm.getDatatype()) ) {
+ lbl = (JLabel)c;
+ if(pm.getValue()==null) lbl.setText("");
+ else {
+ lbl.setText(pm.getValue().toString());
+ }
+ if("integer".equals(pm.getDatatype()) || "decimal".equals(pm.getDatatype())) lbl.setHorizontalAlignment(SwingConstants.RIGHT);
+ else lbl.setHorizontalAlignment(SwingConstants.LEFT);
+ ret = lbl;
+ } else if("boolean".equals(pm.getDatatype())) {
+ JCheckBox chk = new JCheckBox();
+ chk.setBackground(c.getBackground());
+ chk.setHorizontalAlignment(SwingConstants.CENTER);
+ if(pm.getValue()!=null && pm.getValue() instanceof Boolean) {
+ Boolean b = (Boolean)pm.getValue();
+ chk.setSelected(b.booleanValue());
+ }
+ ret = chk;
+ } else {
+ ret = super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
+ }
+ if(pm.getSelect()!=null&& (pm.getSelect().isMultiValued()||pm.getSelect().isEditable())) {
+ final JButton pbEdit = new ButtonEditParam(pm);
+ double height = table.getRowHeight();
+ pbEdit.setSize((int)height,(int)height);
+ JPanel pane = new JPanel();
+ org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(pane);
+ pane.setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
+ .add(ret, (int)height, 100, Short.MAX_VALUE)
+ .add(pbEdit, (int)height, (int)height, (int)height))
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(pbEdit, (int)height, (int)height, Short.MAX_VALUE)
+ .add(ret, (int)height, (int)height, (int)height))
+ );
+ InputMap iMap = pane.getInputMap();
+ Object actionKey = "helpButton";
+ iMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F3,0),actionKey);
+ ActionMap am = pane.getActionMap();
+ am.put(actionKey,new AbstractAction() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ pbEdit.doClick();
+ }
+ });
+ ret = pane;
+ }
+ }
+ return ret;
+ }
+ public void setModel(ParamTableModel tpm) { this.ptm=tpm; }
+ }
+ private class MyCellEditor extends DefaultCellEditor {
+ private static final long serialVersionUID = 4213567233833281102L;
+ private DefaultCellEditor chkEditor, cbxEditor, dfEditor, currentEditor;
+ private JComponent editorComponent2;
+ private ParamTableModel ptm;
+ private PopupMenuListener cbxPopupListener;
+ private FocusListener chkFocusListener;
+ public MyCellEditor(ParamTableModel ptm) {
+ super(new JTextField());
+ chkEditor = new DefaultCellEditor(new JCheckBox());
+ cbxEditor = new DefaultCellEditor(new JComboBox());
+ dfEditor = new DefaultCellEditor(new JTextField());
+ setClickCountToStart(1);
+ this.ptm=ptm;
+ }
+ @Override
+ public Component getTableCellEditorComponent(JTable table,Object value,boolean isSelected,int row,int column) {
+ ParamModel pm = ptm.getParam(row);
+ Component ret;
+ if(pm.getSelect()!=null && !pm.getSelect().isMultiValued()) {
+ JComboBox cbx = (JComboBox)cbxEditor.getTableCellEditorComponent(table,value,isSelected,row,column);
+ editorComponent2 = cbx;
+ if(cbxPopupListener==null) {
+ cbxPopupListener = new PopupMenuListener() {
+ @Override
+ public void popupMenuWillBecomeVisible(PopupMenuEvent e) { }
+ @Override
+ public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
+ stopCellEditing();
+ }
+ @Override
+ public void popupMenuCanceled(PopupMenuEvent e) { }
+ };
+ cbx.addPopupMenuListener(cbxPopupListener);
+ }
+ cbx.removeAllItems();
+ int selectedItem = -1;
+ for(OptionModel om:pm.getSelect().getOptions()) {
+ cbx.addItem(new Pair(om.getValue(),om.getLibelle()));
+ if(value!=null && om.getValue().equals(value)) selectedItem = cbx.getItemCount()-1;
+ }
+ if(selectedItem!=-1) cbx.setSelectedIndex(selectedItem);
+ ret = cbx;
+ currentEditor = cbxEditor;
+ } else if("boolean".equals(pm.getDatatype())) {
+ JCheckBox chk = (JCheckBox)chkEditor.getTableCellEditorComponent(table,value,isSelected,row,column);
+ chk.setHorizontalAlignment(SwingConstants.CENTER);
+ chk.setBackground(table.getCellRenderer(row,column).getTableCellRendererComponent(table,value,isSelected,hasFocus(),row,column).getBackground());
+ if(chkFocusListener==null) {
+ chkFocusListener = new FocusListener() {
+ @Override
+ public void focusGained(FocusEvent e) {
+ }
+ @Override
+ public void focusLost(FocusEvent e) {
+ stopCellEditing();
+ }
+ };
+ chk.addFocusListener(chkFocusListener);
+ }
+ ret = chk;
+ currentEditor = chkEditor;
+ editorComponent2 = chk;
+ } else {
+ JTextField df = (JTextField)dfEditor.getTableCellEditorComponent(table,value,isSelected,row,column);
+ Keymap km = df.getKeymap();
+ if(km.getAction(KeyStroke.getKeyStroke('\n'))==null) {
+ km.addActionForKeyStroke(KeyStroke.getKeyStroke('\n'),new AbstractAction() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ stopCellEditing();
+ }
+ });
+ }
+ ret = df;
+ currentEditor = dfEditor;
+ editorComponent2 = df;
+ }
+ if(pm.getSelect()!=null&& (pm.getSelect().isMultiValued()||pm.getSelect().isEditable())) {
+ final JButton pbEdit;
+ if(ret instanceof JComboBox) pbEdit = new ButtonEditParam(pm,(JComboBox)ret);
+ else pbEdit = new ButtonEditParam(pm,(JTextField)ret);
+ double height = table.getRowHeight();
+ pbEdit.setSize((int)height,(int)height);
+ JPanel pane = new JPanel();
+ org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(pane);
+ pane.setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
+ .add(ret, (int)height, 100, Short.MAX_VALUE)
+ .add(pbEdit, (int)height, (int)height, (int)height))
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(pbEdit, (int)height, (int)height, Short.MAX_VALUE)
+ .add(ret, (int)height, (int)height, (int)height))
+ );
+ ret.addFocusListener(new FocusListener() {
+ @Override
+ public void focusGained(FocusEvent e) {
+ }
+ @Override
+ public void focusLost(FocusEvent e) {
+ stopCellEditing();
+ }
+ });
+ pane.addFocusListener(new FocusListener() {
+ @Override
+ public void focusGained(FocusEvent e) {
+ editorComponent2.grabFocus();
+ }
+ @Override
+ public void focusLost(FocusEvent e) {
+ }
+ });
+ InputMap iMap = pane.getInputMap();
+ Object actionKey = "helpButton";
+ iMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F3,0),actionKey);
+ ActionMap am = pane.getActionMap();
+ am.put(actionKey,new AbstractAction() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ pbEdit.doClick();
+ }
+ });
+ ret = pane;
+ }
+ return ret;
+ }
+ public void setModel(ParamTableModel ptm) { this.ptm=ptm; }
+ @Override
+ public Object getCellEditorValue() { return currentEditor.getCellEditorValue(); }
+ }
+ private class ButtonEditParam extends JButton {
+ private static final long serialVersionUID = -5930317858850211706L;
+ private final ParamModel pm;
+ private JComboBox cbx;
+ private JTextField df;
+ private ButtonEditParam(ParamModel pm) {
+ super("...");
+ this.pm = pm;
+ addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ doEdit();
+ }
+ });
+ }
+ public ButtonEditParam(ParamModel pm, JComboBox cbx) {
+ this(pm);
+ this.cbx=cbx;
+ }
+ public ButtonEditParam(ParamModel pm, JTextField df) {
+ this(pm);
+ this.df=df;
+ }
+ private void doEdit() {
+ DlgEditParam dep = new DlgEditParam(DlgControl.this,pm);
+ dep.setVisible(true);
+ if(cbx!=null) {
+ Object value = cbx.getSelectedItem();
+ cbx.removeAllItems();
+ int selectedItem = -1;
+ for(OptionModel om:pm.getSelect().getOptions()) {
+ cbx.addItem(new Pair(om.getValue(),om.getLibelle()));
+ if(value!=null && om.getValue().equals(value)) selectedItem = cbx.getItemCount()-1;
+ }
+ if(selectedItem!=-1) cbx.setSelectedIndex(selectedItem);
+ } else if(df!=null) {
+ df.setText(pm.getValue().toString());
+ }
+ }
+ }
+
+ @Override
+ public void stopWaiting() { stopVentilateur(); }
+
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.3" maxVersion="1.3" type="org.netbeans.modules.form.forminfo.JDialogFormInfo">
+ <Properties>
+ <Property name="defaultCloseOperation" type="int" value="2"/>
+ <Property name="title" type="java.lang.String" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
+ <Connection code="pm.getName()" type="code"/>
+ </Property>
+ </Properties>
+ <SyntheticProperties>
+ <SyntheticProperty name="formSizePolicy" type="int" value="1"/>
+ </SyntheticProperties>
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="2"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" max="-2" attributes="0">
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Component id="jScrollPane1" pref="221" max="32767" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" max="-2" attributes="0">
+ <Component id="pbAdd" linkSize="1" alignment="0" pref="98" max="32767" attributes="1"/>
+ <Component id="pbClose" linkSize="1" alignment="0" pref="98" max="32767" attributes="1"/>
+ <Component id="pbRemove" linkSize="1" alignment="0" max="32767" attributes="1"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <Component id="pbAdd" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="pbRemove" min="-2" max="-2" attributes="0"/>
+ <EmptySpace pref="201" max="32767" attributes="0"/>
+ <Component id="pbClose" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <Component id="jScrollPane1" alignment="0" pref="276" max="32767" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Container class="javax.swing.JScrollPane" name="jScrollPane1">
+ <AuxValues>
+ <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
+ </AuxValues>
+
+ <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
+ <SubComponents>
+ <Component class="javax.swing.JList" name="lst">
+ <Properties>
+ <Property name="model" type="javax.swing.ListModel" editor="org.netbeans.modules.form.editors2.ListModelEditor">
+ <StringArray count="5">
+ <StringItem index="0" value="Item 1"/>
+ <StringItem index="1" value="Item 2"/>
+ <StringItem index="2" value="Item 3"/>
+ <StringItem index="3" value="Item 4"/>
+ <StringItem index="4" value="Item 5"/>
+ </StringArray>
+ </Property>
+ <Property name="selectionMode" type="int" value="0"/>
+ </Properties>
+ </Component>
+ </SubComponents>
+ </Container>
+ <Component class="javax.swing.JButton" name="pbClose">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Fermer"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbCloseActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="pbAdd">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Ajouter"/>
+ <Property name="enabled" type="boolean" value="false"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbAddActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="pbRemove">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Supprimer"/>
+ <Property name="enabled" type="boolean" value="false"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbRemoveActionPerformed"/>
+ </Events>
+ </Component>
+ </SubComponents>
+</Form>
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.controls;
+
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import java.awt.Color;
+import java.awt.Component;
+import java.util.HashSet;
+import java.util.StringTokenizer;
+import java.util.Vector;
+
+import javax.swing.JCheckBox;
+import javax.swing.JList;
+import javax.swing.JOptionPane;
+import javax.swing.ListCellRenderer;
+import javax.swing.ListSelectionModel;
+import javax.swing.border.LineBorder;
+import javax.swing.event.ListSelectionEvent;
+import javax.swing.event.ListSelectionListener;
+
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import fr.gouv.finances.dgfip.xemelios.controls.core.models.OptionModel;
+import fr.gouv.finances.dgfip.xemelios.controls.core.models.ParamModel;
+
+/**
+ *
+ * @author chm
+ */
+public class DlgEditParam extends javax.swing.JDialog {
+ public static final String SEPARATOR=" ";
+ private ParamModel pm;
+
+ /** Creates new form DlgEditParam */
+ public DlgEditParam(java.awt.Frame parent, ParamModel pm) {
+ super(parent, true);
+ this.pm = pm;
+ initAll();
+ }
+ public DlgEditParam(java.awt.Dialog parent, ParamModel pm) {
+ super(parent, true);
+ this.pm = pm;
+ initAll();
+ }
+ private void initAll() {
+ initComponents();
+ setLocationRelativeTo(getParent());
+ if(!pm.getSelect().isMultiValued()) {
+ Vector<Pair> v = new Vector<Pair>();
+ for(OptionModel om:pm.getSelect().getOptions()) {
+ Pair p = new Pair(om.getValue(),om.getLibelle());
+ v.add(p);
+ }
+ lst.setListData(v);
+ pbAdd.setEnabled(true);
+ lst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
+ lst.addListSelectionListener(new ListSelectionListener() {
+ public void valueChanged(ListSelectionEvent e) {
+ pbRemove.setEnabled(lst.getSelectedIndex()>=0);
+ }
+ });
+ } else {
+ Object oValue = pm.getValue();
+ HashSet<String> values = new HashSet<String>();
+ if(oValue!=null && oValue instanceof String) {
+ String s = (String)oValue;
+ StringTokenizer tokenizer = new StringTokenizer(s,SEPARATOR);
+ while(tokenizer.hasMoreTokens()) values.add(tokenizer.nextToken());
+ }
+ lst.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
+ lst.setCellRenderer(new MyCellRenderer());
+ Vector<String> data = new Vector<String>();
+ Vector<Integer> selectedIndices = new Vector<Integer>();
+ for(OptionModel om:pm.getSelect().getOptions()) {
+ String key = om.getValue();
+ if(values.contains(key)) selectedIndices.add(new Integer(data.size()));
+ data.add(key);
+ }
+ lst.setListData(data);
+ int[] indices = new int[selectedIndices.size()];
+ for(int i=0;i<indices.length;i++) indices[i]=selectedIndices.get(i).intValue();
+ lst.setSelectedIndices(indices);
+ if(pm.getSelect().isEditable()) {
+ pbAdd.setEnabled(true);
+ lst.addListSelectionListener(new ListSelectionListener() {
+ public void valueChanged(ListSelectionEvent e) {
+ pbRemove.setEnabled(lst.getSelectedIndex()>=0);
+ }
+ });
+ }
+ }
+ }
+
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ jScrollPane1 = new javax.swing.JScrollPane();
+ lst = new javax.swing.JList();
+ pbClose = new javax.swing.JButton();
+ pbAdd = new javax.swing.JButton();
+ pbRemove = new javax.swing.JButton();
+
+ setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+ setTitle(pm.getName());
+
+ lst.setModel(new javax.swing.AbstractListModel() {
+ String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
+ public int getSize() { return strings.length; }
+ public Object getElementAt(int i) { return strings[i]; }
+ });
+ lst.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
+ jScrollPane1.setViewportView(lst);
+
+ pbClose.setText("Fermer");
+ pbClose.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbCloseActionPerformed(evt);
+ }
+ });
+
+ pbAdd.setText("Ajouter");
+ pbAdd.setEnabled(false);
+ pbAdd.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbAddActionPerformed(evt);
+ }
+ });
+
+ pbRemove.setText("Supprimer");
+ pbRemove.setEnabled(false);
+ pbRemove.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbRemoveActionPerformed(evt);
+ }
+ });
+
+ org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
+ .add(pbAdd, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE)
+ .add(pbClose, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE)
+ .add(pbRemove, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ .addContainerGap())
+ );
+
+ layout.linkSize(new java.awt.Component[] {pbAdd, pbClose, pbRemove}, org.jdesktop.layout.GroupLayout.HORIZONTAL);
+
+ layout.setVerticalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .add(pbAdd)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(pbRemove)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 201, Short.MAX_VALUE)
+ .add(pbClose))
+ .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 276, Short.MAX_VALUE))
+ .addContainerGap())
+ );
+
+ pack();
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void pbAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbAddActionPerformed
+ String s = JOptionPane.showInputDialog(this,"Valeur à ajouter :");
+ OptionModel om = new OptionModel(s,s);
+ try { pm.getSelect().addChild(om,OptionModel.QN); } catch(Throwable t) {}
+ if(!pm.getSelect().isMultiValued()) {
+ Vector<Pair> v = new Vector<Pair>();
+ for(OptionModel om2:pm.getSelect().getOptions()) {
+ Pair p = new Pair(om2.getValue(),om2.getLibelle());
+ v.add(p);
+ }
+ lst.setListData(v);
+ } else {
+ Vector<String> data = new Vector<String>();
+ for(OptionModel om2:pm.getSelect().getOptions()) {
+ String key = om2.getValue();
+ data.add(key);
+ }
+ lst.setListData(data);
+ }
+ }//GEN-LAST:event_pbAddActionPerformed
+
+ private void pbRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbRemoveActionPerformed
+ if(pm.getSelect().isEditable()) {
+ if(!pm.getSelect().isMultiValued()) {
+ Pair p = (Pair)lst.getSelectedValue();
+ if(p!=null) {
+ int index = lst.getSelectedIndex();
+ lst.remove(index);
+ pm.getSelect().getOptions().remove(index);
+ }
+ } else {
+ Object[] values = lst.getSelectedValues();
+ Vector<String> v = new Vector<String>();
+ for(Object value:values) v.add((String)value);
+ Vector<OptionModel> toDrop = new Vector<OptionModel>();
+ for(OptionModel om:pm.getSelect().getOptions()) {
+ if(v.contains(om.getValue())) toDrop.add(om);
+ }
+ pm.getSelect().getOptions().removeAll(toDrop);
+ pm.setValue("", MainWindow.getInstance().getEnvProperties().getProperty(Constants.SYS_PROP_DATE_FORMAT));
+ Vector<String> data = new Vector<String>();
+ for(OptionModel om:pm.getSelect().getOptions()) {
+ String key = om.getValue();
+ data.add(key);
+ }
+ lst.setListData(data);
+ }
+ }
+ }//GEN-LAST:event_pbRemoveActionPerformed
+
+ private void pbCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbCloseActionPerformed
+ if(pm.getSelect().isMultiValued()) {
+ StringBuffer sb = new StringBuffer();
+ int[] indices = lst.getSelectedIndices();
+ for(int i:indices) {
+ String s = lst.getModel().getElementAt(i).toString();
+ sb.append(s).append(SEPARATOR);
+ }
+ if(sb.length()>1) sb.deleteCharAt(sb.length()-1);
+ pm.setValue(sb.toString(), MainWindow.getInstance().getEnvProperties().getProperty(Constants.SYS_PROP_DATE_FORMAT));
+ }
+ setVisible(false);
+ }//GEN-LAST:event_pbCloseActionPerformed
+
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JScrollPane jScrollPane1;
+ private javax.swing.JList lst;
+ private javax.swing.JButton pbAdd;
+ private javax.swing.JButton pbClose;
+ private javax.swing.JButton pbRemove;
+ // End of variables declaration//GEN-END:variables
+
+ private class MyCellRenderer extends JCheckBox implements ListCellRenderer {
+ public MyCellRenderer() {
+ super();
+ setBorder(new LineBorder(Color.GRAY,1));
+ }
+ public Component getListCellRendererComponent(JList list,Object value,int index,boolean isSelected,boolean cellHasFocus) {
+ if(value!=null) {
+ setText(value.toString());
+ } else {
+ setText("");
+ }
+ setSelected(isSelected);
+ setBorderPainted(cellHasFocus);
+ if(cellHasFocus) {
+ setBackground(list.getSelectionBackground());
+ setForeground(list.getSelectionForeground());
+ } else {
+ setBackground(list.getBackground());
+ setForeground(list.getForeground());
+ }
+ return this;
+ }
+ }
+}
--- /dev/null
+/*
+ *
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 Christophe Marchand <christophe.marchand@axyus.com>
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+package fr.gouv.finances.cp.xemelios.controls;
+
+import fr.gouv.finances.dgfip.xemelios.controls.core.AbstractControlContentHandler;
+import fr.gouv.finances.dgfip.xemelios.controls.core.ControlProgressListener;
+import fr.gouv.finances.dgfip.xemelios.controls.core.ControlParser;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentsModel;
+import fr.gouv.finances.dgfip.xemelios.controls.core.MainControl.Triplet;
+import fr.gouv.finances.dgfip.xemelios.controls.core.models.ControlsModel;
+import fr.gouv.finances.dgfip.xemelios.controls.core.models.DocumentControlModel;
+import fr.gouv.finances.dgfip.xemelios.importers.EtatImporteur;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow.ImportContent;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+import fr.gouv.finances.dgfip.xemelios.controls.core.MainControl;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.lang.reflect.Constructor;
+import java.util.ArrayList;
+import java.util.Hashtable;
+import javax.swing.JOptionPane;
+import org.apache.log4j.Logger;
+
+/**
+ *
+ * @author chm
+ */
+public class MainControlWrapper implements Runnable {
+ private static Logger logger = Logger.getLogger(MainControlWrapper.class);
+ private DlgControl dlgControl = null;
+ private MainControl mc = null;
+ private DocumentModel dmRapport = null;
+ private XemeliosUser user;
+ private DocumentModel dm;
+
+ /** Creates a new instance of MainControlWrapper */
+ public MainControlWrapper(DocumentModel dm,DocumentsModel docsMod,XemeliosUser user) {
+ super();
+ this.user=user;
+ this.dm=dm;
+ final DocumentModel dm2 = dm;
+ final ControlsModel cm = getControlsModel();
+ final DocumentControlModel dcm = cm.getDocumentById(dm.getId());
+ File schemaLocation = null;
+ if(dcm.getControlTechById("TECH03")!=null) {
+ schemaLocation = new File(dm.getBaseDirectory(), dcm.getControlTechById("TECH03").getParamTechById("schemaLocation").getValue());
+ }
+ this.mc=new MainControl(dm, dm.getNamespaces(), dcm, /*dm.getTitre(), */schemaLocation) {
+ @Override
+ public void writeControlConfigFile() throws IOException {
+ File output = new File(dm2.getBaseDirectory(), dm2.getControlConfigFile());
+ OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(output), "ISO-8859-1");
+ XmlOutputter outputter = new XmlOutputter(os, "ISO-8859-1");
+ cm.marshall(outputter);
+ os.flush();
+ os.close();
+ }
+
+ @Override
+ public AbstractControlContentHandler getControlContentHandler(String documentModelId, DocumentControlModel docCtrlMod, Hashtable<String, Object> parameters, String file, ControlProgressListener cpl) {
+ return new DefaultControlContentHandler(dm2, dm2.getNamespaces(), dcm, parameters, MainWindow.getInstance(), file, getControlProgressListener());
+ }
+
+ };
+ if(dm.getTextToXmlTransformer()!=null)
+ mc.setTextToXmlTransformer(dm.getTextToXmlTransformer());
+ this.dmRapport = docsMod.getDocumentById("rapport");
+ }
+
+ private void importer(DocumentModel dm,Pair coll,Pair budg,File f,boolean isRapport,MainControl.Triplet triplet) {
+ try {
+ Class clazz = Class.forName(dm.getImportClass());
+ Constructor cc = clazz.getConstructor(XemeliosUser.class);
+ Object obj = cc.newInstance(user);
+ if(!(obj instanceof EtatImporteur)) {
+ JOptionPane.showMessageDialog(MainWindow.instance,"Cette classe n'est pas un importeur.\nLe fichier de configuration qui vous a été livré est certainement invalide.\nVeuillez contacter votre fournisseur.\n","Erreur",JOptionPane.ERROR_MESSAGE);
+ return;
+ }
+ EtatImporteur ei = (EtatImporteur)obj;
+ ei.setDocument(dm,coll,budg);
+ ei.setApplicationConfiguration(MainWindow.getInstance().getEnvProperties());
+ ArrayList<File> array = new ArrayList<File>();
+ array.add(f);
+ ImportContent fToImport = new ImportContent();
+ fToImport.setFilesToImport(array);
+
+ if(isRapport) {
+ MainWindow.instance.doImport(ei,fToImport,dm,dlgControl,triplet,true);
+ } else {
+ MainWindow.instance.doImport(ei,fToImport,dm,true);
+ }
+ } catch(Exception ex) {
+ ex.printStackTrace();
+ } finally {
+
+ }
+ }
+ public void setDlgControl(DlgControl dlgControl) {
+ this.dlgControl=dlgControl;
+ mc.setControlProgressListener(dlgControl);
+ }
+ public void writeControlConfigFile() throws IOException {
+ mc.writeControlConfigFile();
+ }
+ public DocumentControlModel getDocumentControl() { return mc.getDocumentControl(); }
+ public void setFileToControl(File fToCtrl) { mc.setFileToControl(fToCtrl); }
+ public void setParameters(Hashtable<String,Object> params) { mc.setParameters(params); }
+ @Override
+ public void run() {
+ mc.run();
+ switch (mc.getControlStatus()) {
+ case MainControl.STATUS_CONTROL_NO_ERROR: {
+ int reponse = JOptionPane.showConfirmDialog(MainWindow.instance,
+ "Le fichier "+mc.getFileToControl().getName()+" ne comporte pas d'anomalies.\nSouhaitez-vous quand même l'importer?",
+ "Question",
+ JOptionPane.YES_NO_OPTION);
+ // Confirmation de l'import du flux malgré l'absence d'anos
+ if(JOptionPane.YES_OPTION == reponse){
+ // Import du doc
+ importer(dm,mc.getCollectivite(),mc.getBudget(),mc.getFichierEnrichi(),false,null);
+ // Import du rapport si des anos sont présentes
+ importer(dmRapport,mc.getCollectivite(),mc.getBudget(),mc.getRapport(),true,new Triplet(mc.getIdRapport(),mc.getCollectivite().key,mc.getBudget().key));
+ } else {
+ dlgControl.notifyImportFinished(null);
+ }
+ break;
+ }
+ case MainControl.STATUS_HAS_UNIT_CONTROL_ERRORS: {
+ importer(dm,mc.getCollectivite(),mc.getBudget(),mc.getFichierEnrichi(),false,null);
+ importer(dmRapport,mc.getCollectivite(),mc.getBudget(),mc.getRapport(),true,new Triplet(mc.getIdRapport(),mc.getCollectivite().key,mc.getBudget().key));
+ break;
+ }
+ case MainControl.STATUS_NOT_SCHEMA_VALID:
+ case MainControl.STATUS_INVALID_ENCODING:
+ case MainControl.STATUS_NOT_XML: {
+ importer(dmRapport,new Pair("00000000000000","Collectivite de Contrôle"),new Pair("00","Budget de Contrôle"),mc.getRapport(),true,new Triplet(mc.getIdRapport(),"00000000000000","00"));
+ break;
+ }
+ }
+ }
+ private ControlsModel getControlsModel() {
+ ControlsModel ret = null;
+ try {
+ ControlParser cp = new ControlParser();
+ cp.parse(new File(dm.getBaseDirectory(), dm.getControlConfigFile()));
+ ControlsModel c = (ControlsModel) cp.getMarshallable();
+ c.validate();
+ ret = c;
+ } catch (Exception ex) {
+ logger.debug("Error in getControlsModel()!!!", ex);
+ }
+ return ret;
+ }
+
+}
--- /dev/null
+/*
+ *
+ * Copyright
+ * 2009 axYus - www.axyus.com
+ * 2009 Laurent Meckert <laurent.meckert@axyus.com>
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+package fr.gouv.finances.cp.xemelios.controls.editors;
+
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
+import java.util.Hashtable;
+import java.math.BigDecimal;
+import java.io.FileOutputStream;
+import java.util.Properties;
+import java.io.FileInputStream;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+
+import org.w3c.dom.Document;
+
+
+
+import java.io.File;
+
+/**
+ *
+ * @author laurent.meckert
+ */
+public class CommandLineController {
+
+ static Controller controller;
+
+ protected static Object controlParameterFromString(String paramId, String paramValue) {
+ // in control config file, param types are
+ // string -> java.lang.String
+ // boolean -> java.lang.Boolean
+ // decimal -> java.math.BigDecimal
+ // integer -> java.lang.Integer
+ //
+ // multi-valued params are String arrays (java.lang.String[]) values
+
+
+ String dataType = controller.getParameterDataType(paramId);
+ if (dataType == null) {
+ System.err.println("Unknown parameter :" + paramId);
+ return null;
+ }
+ if ("string".equals(dataType)) {
+ if (paramValue.matches("\\{.*\\}")) {
+
+ int i1 = paramValue.indexOf("{");
+ int i2 = paramValue.lastIndexOf("}");
+ paramValue = paramValue.substring(i1 + 1, i2);
+ System.err.println("Splitting :" + paramValue);
+ return paramValue.split(" *, *");
+ } else {
+ return paramValue;
+ }
+ } else if ("boolean".equals(dataType)) {
+ return new Boolean(paramValue);
+ } else if ("decimal".equals(dataType)) {
+ return new BigDecimal(Long.parseLong(paramValue));
+ } else if ("integer".equals(dataType)) {
+ return new Integer(Integer.parseInt(paramValue));
+ } else {
+ System.err.println("Unknown data type :" + dataType);
+ return null;
+ }
+ }
+
+ protected static Hashtable<String, Object> getControlParameters(String propertiesFile) throws Exception {
+ // Read properties file.
+ Properties properties = new Properties();
+
+ properties.load(new FileInputStream(propertiesFile));
+ Hashtable<String, Object> ret = new Hashtable<String, Object>();
+ for (Object obk : properties.keySet()) {
+ String sk = obk.toString();
+
+ ret.put(sk, controlParameterFromString(sk, properties.getProperty(sk)));
+ }
+ return ret;
+ }
+
+ /**
+ * Appel en ligne de commande
+ * @param args = type de document, fichier à analyser, répertoire de génération, fichier de properties
+ */
+ public static void main(String[] args) {
+ try {
+
+ // si pas assez d'arguments = on donne le modele d'appel et on sort
+ if (args.length < 4) {
+
+ System.err.println("Usage : CommandLineController DocType FileToParse GenerationDirectory PropertiesFile");
+ System.exit(1);
+ }
+
+
+ String typeDoc = args[0];
+ String fileToReadPath = args[1];
+ String dirToGeneratePath = args[2];
+ String propertiesFilePath = args[3];
+
+ File fileToRead = new File(fileToReadPath);
+
+
+ PropertiesExpansion applicationConfiguration = new PropertiesExpansion(System.getProperties());
+ controller = new Controller(typeDoc, applicationConfiguration);
+ Hashtable<String, Document> result = controller.controle(fileToRead, getControlParameters(propertiesFilePath));
+
+ // si on est ici = on peut au moins generer le rapport
+ // donc on tente de creer le repertoire de sortie
+ File dirToGenerate = new File(dirToGeneratePath);
+ if (dirToGenerate.exists()) {
+ if (!dirToGenerate.isDirectory()) {
+ throw new Exception(dirToGeneratePath + " exists and is not a directory");
+ }
+ } else {
+ dirToGenerate.mkdirs();
+ }
+
+ for (String k : result.keySet()) {
+ Document doc = result.get(k);
+
+ try {
+ File fn = new File(dirToGenerate,
+ k + ".xml");
+ FileOutputStream f = new FileOutputStream(fn);
+
+ TransformerFactory tf = FactoryProvider.getTransformerFactory();
+ Transformer t = tf.newTransformer();
+ t.setOutputProperty("encoding", "ISO-8859-1");
+ t.setOutputProperty("method", "xml");
+ t.setOutputProperty("indent", "yes");
+ t.transform(new DOMSource(doc), new StreamResult(f));
+
+ f.flush();
+ f.close();
+ System.out.println("Generated " + fn.getAbsolutePath() + ".");
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ //
+
+ } catch (Error e) {
+ e.printStackTrace();
+
+
+ }
+ }
+
+ } catch (Throwable t) {
+ t.printStackTrace();
+ }
+ }
+}
--- /dev/null
+/*
+ *
+ * Copyright
+ * 2009 axYus - www.axyus.com
+ * 2009 Laurent Meckert <laurent.meckert@axyus.com>
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+package fr.gouv.finances.cp.xemelios.controls.editors;
+
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentsModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.Loader;
+import fr.gouv.finances.dgfip.xemelios.controls.core.AbstractControlContentHandler;
+import fr.gouv.finances.dgfip.xemelios.controls.core.ControlParser;
+import fr.gouv.finances.dgfip.xemelios.controls.core.models.DocumentControlModel;
+import fr.gouv.finances.dgfip.xemelios.controls.core.models.ParamModel;
+
+import fr.gouv.finances.dgfip.xemelios.controls.core.ControlProgressListener;
+import fr.gouv.finances.dgfip.xemelios.controls.core.MainControl;
+import fr.gouv.finances.dgfip.xemelios.controls.core.models.ControlsModel;
+import fr.gouv.finances.dgfip.xemelios.auth.UnauthorizedException;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+import fr.gouv.finances.dgfip.xemelios.common.ToolException;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.util.Hashtable;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.stream.StreamSource;
+
+import org.w3c.dom.Document;
+import javax.xml.transform.dom.DOMResult;
+
+import javax.xml.parsers.DocumentBuilderFactory;
+import org.apache.log4j.Logger;
+
+/**
+ *
+ * @author chm
+ */
+public class Controller implements ControlProgressListener {
+
+ private static final Logger logger = Logger.getLogger(Controller.class);
+ MainControl mc;
+ DocumentsModel config;
+ DocumentModel pesConfig;
+ DocumentModel rapportConfig;
+ private PropertiesExpansion applicationConfiguration;
+
+ /**
+ *
+ * @param typeDoc identifiant du type de document
+ * @throws Exception
+ */
+ public Controller(String typeDoc, PropertiesExpansion applicationConfiguration) throws Exception {
+ this.applicationConfiguration = applicationConfiguration;
+ config = Loader.getDocumentsInfos(applicationConfiguration.getProperty(Constants.SYS_PROP_DOC_DEF_DIR));
+
+ pesConfig = config.getDocumentById(typeDoc); //("PES_Aller");
+ rapportConfig = config.getDocumentById("DocumentRapport");
+ final DocumentModel dm2 = pesConfig;
+ final ControlsModel cm = getControlsModel();
+ final DocumentControlModel dcm = cm.getDocumentById(pesConfig.getId());
+ mc = new MainControl(
+ pesConfig,
+ pesConfig.getNamespaces(),
+ dcm,
+// pesConfig.getTitre(),
+ new File(pesConfig.getBaseDirectory(), dcm.getControlTechById("TECH03").getParamTechById("schemaLocation").getValue())) {
+
+ @Override
+ public void writeControlConfigFile() throws IOException {
+ File output = new File(dm2.getBaseDirectory(), dm2.getControlConfigFile());
+ OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(output), "ISO-8859-1");
+ XmlOutputter outputter = new XmlOutputter(os, "ISO-8859-1");
+ cm.marshall(outputter);
+ os.flush();
+ os.close();
+ }
+
+ @Override
+ public AbstractControlContentHandler getControlContentHandler(String documentModelId, DocumentControlModel docCtrlMod, Hashtable<String, Object> parameters, String file, ControlProgressListener cpl) {
+ AbstractControlContentHandler cch = new AbstractControlContentHandler(
+ getDocumentModelId(),
+ dm2.getNamespaces(),
+ dcm,
+ parameters,
+ file,
+ cpl) {
+
+ @Override
+ public Pair getCollectivite(String documentModelId, String fileName) throws ToolException {
+ return new Pair("xxxxxxxxxxx", "Collectivité d'analyse");
+ }
+
+ @Override
+ public Pair getBudget(String documentModelId, Pair collectivite, String fileName) throws ToolException, UnauthorizedException {
+ return new Pair("00", "Budget principal");
+ }
+ };
+ return cch;
+ }
+ };
+ if (pesConfig.getTextToXmlTransformer() != null) {
+ mc.setTextToXmlTransformer(pesConfig.getTextToXmlTransformer());
+ }
+ }
+
+ /**
+ * Verifie que tous les parametres necessaires sont renseignes
+ * @param hashParams cle = id du parametres, value = un objet (String, Boolean etc...). Si un parametre doit être une liste de valeur, exprimer l'ensemble des valeurs sous la forme <tt>"{val1, val2, val3, ...}"</tt>
+ * @return true/false (succes/echec)
+ */
+ public boolean checkParameters(Hashtable<String, Object> hashParams) {
+ boolean ret = true;
+ DocumentControlModel dcm = mc.getDocumentControl();
+ for (ParamModel param : dcm.getParams()) {
+
+ Object val = hashParams.get(param.getId());
+ if (val == null) {
+ System.err.println("ERROR: Mandatory parameter " + param.getId() + " Not found ");
+ ret = false;
+ continue;
+ }
+ }
+ return ret;
+ }
+
+ /**
+ * Pour aider à la mise au point
+ * donne la liste des parametres obligatoires
+ * pour le type de document choisis
+ */
+ public void listMandatoryParameters() {
+
+ DocumentControlModel dcm = mc.getDocumentControl();
+ System.err.println("Mandatory parameters are:");
+ for (ParamModel param : dcm.getParams()) {
+ System.err.println(param.getId() + "( " + param.getDatatype() + ")");
+
+ }
+
+ }
+
+ public String getParameterDataType(String paramId) {
+ DocumentControlModel dcm = mc.getDocumentControl();
+ ParamModel param = dcm.getParamById(paramId);
+ if (param != null) {
+ return param.getDatatype();
+ } else {
+ return null;
+ }
+
+ }
+
+ /**
+ *
+ * @param fileToRead le fichier à analyser/enrichir
+ * @param parameters hashtable key = id de parametre, value = Object correspondant. Si une valeur est une liste de valeurs, il faut passer l'ensemble des valeurs sous la forme <tt>{val1, val2, val3, ...}</tt>.
+ * @return une Hashtable key = DocumentEnrichi ou Rapport, value = dom.document. {DocumentEnrichi=org.w3c.dom.Document, Rapport=org.w3c.dom.Document}
+ * @throws Exception
+ */
+ public Hashtable<String, Document> controle(File fileToRead, Hashtable<String, Object> parameters) throws Exception {
+ // XemeliosUser localUser = new LocalUser();
+
+
+ Hashtable<String, Document> domDocuments = new Hashtable<String, Document>();
+ if (!checkParameters(parameters)) {
+ listMandatoryParameters();
+ return domDocuments;// qui est vide
+ }
+ File rapport = File.createTempFile("rapport", "xml");
+
+ File tmpEnrichi = File.createTempFile("pesv2-enrichi", "xml");
+ mc.setControlProgressListener(this);
+ mc.setParameters(parameters);
+ mc.setFileToControl(fileToRead);
+ mc.setFichierEnrichiLocation(tmpEnrichi.getAbsolutePath());
+ mc.setRapportLocation(rapport.getAbsolutePath());
+
+ // use any utility to run control
+ mc.run();
+
+ if (mc.getControlStatus() != MainControl.STATUS_NOT_CONTROLLED) {
+ if (mc.getControlStatus() > MainControl.STATUS_NOT_SCHEMA_VALID) {
+ // on applique la XSL d'import specifique aux controle standalone au flux enrichi
+ TransformerFactory tFactory = FactoryProvider.getTransformerFactory();
+ Transformer tr = tFactory.newTransformer(new StreamSource(new File(pesConfig.getBaseDirectory(), pesConfig.getGlobalImportXsltFile())));
+ DOMResult result = new DOMResult();
+
+ tr.transform(new StreamSource(tmpEnrichi), result);
+ tmpEnrichi.delete();
+
+ domDocuments.put("DocumentEnrichi", (Document) result.getNode());
+ }
+ if (rapportConfig.getGlobalImportXsltFile() != null && rapportConfig.getGlobalImportXsltFile().length() > 0) {
+ TransformerFactory tFactory = FactoryProvider.getTransformerFactory();
+ Transformer tr = tFactory.newTransformer(new StreamSource(new File(rapportConfig.getBaseDirectory(), rapportConfig.getGlobalImportXsltFile())));
+ DOMResult result = new DOMResult();
+ tr.transform(new StreamSource(rapport), result);
+ domDocuments.put("Rapport", (Document) result.getNode());
+ } else {
+
+ DocumentBuilderFactory dFactory = FactoryProvider.getDocumentBuilderFactory();
+ Document drapport = dFactory.newDocumentBuilder().parse(rapport);
+ domDocuments.put("Rapport", drapport);
+ rapport.delete();
+ }
+ }
+ return domDocuments;
+ }
+
+ @Override
+ public void notifyImportFinished(MainControl.Triplet triplet) {
+ }
+
+ @Override
+ public void notifyImportInterrupted(boolean hide) {
+ }
+
+ @Override
+ public void stopWaiting() {
+ }
+
+ @Override
+ public void notifyTechniqueValidationFailed() {
+ }
+
+ /**
+ * @TODO : AUTHORISATIONS A GERER CORRECTEMENT
+ * LM = recopié tel quel mais inutilisé
+ */
+ public static class LocalUser implements XemeliosUser {
+
+ @Override
+ public String getId() {
+ return "local";
+ }
+
+ @Override
+ public String getDisplayName() {
+ return getId();
+ }
+
+ @Override
+ public boolean hasRole(String arg0) {
+ return true;
+ }
+
+ @Override
+ public boolean hasDocument(String arg0) {
+ return true;
+ }
+
+ @Override
+ public boolean hasCollectivite(String arg0, DocumentModel dm) {
+ return true;
+ }
+ }
+
+ private ControlsModel getControlsModel() {
+ ControlsModel ret = null;
+ try {
+ ControlParser cp = new ControlParser();
+ cp.parse(new File(pesConfig.getBaseDirectory(), pesConfig.getControlConfigFile()));
+ ControlsModel c = (ControlsModel) cp.getMarshallable();
+ c.validate();
+ ret = c;
+ } catch (Exception ex) {
+ logger.debug("Error in getControlsModel()!!!", ex);
+ }
+ return ret;
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.controls.editors;
+
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import fr.gouv.finances.dgfip.utils.Base64;
+import fr.gouv.finances.dgfip.utils.IoUtils;
+import fr.gouv.finances.dgfip.utils.NavigationContext;
+import fr.gouv.finances.cp.utils.StartUrl;
+import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
+import fr.gouv.finances.cp.utils.ui.IhmFactory;
+import fr.gouv.finances.dgfip.utils.xml.NamespaceContextImpl;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentsModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.EtatModel;
+import fr.gouv.finances.cp.xemelios.ui.HtmlViewer;
+import fr.gouv.finances.cp.xemelios.ui.UpdatableToolbar;
+import fr.gouv.finances.cp.xemelios.ui.xhtmlviewer.LocalException;
+import fr.gouv.finances.cp.xemelios.ui.xhtmlviewer.XemeliosUserAgent;
+import fr.gouv.finances.cp.xemelios.ui.xhtmlviewer.XemeliosXhtmlPanel;
+import fr.gouv.finances.dgfip.xemelios.utils.AbstractUriTransformer;
+import fr.gouv.finances.dgfip.utils.Dest;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
+import fr.gouv.finances.dgfip.utils.xml.transform.CustomURIResolver;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+import fr.gouv.finances.dgfip.xemelios.common.config.Loader;
+import fr.gouv.finances.dgfip.xemelios.ui.ImageResources;
+import fr.gouv.finances.dgfip.xemelios.utils.FileUtils;
+import fr.gouv.finances.dgfip.xemelios.utils.XmlUtils;
+import java.awt.BorderLayout;
+import java.awt.Component;
+import java.awt.Dimension;
+import java.awt.Toolkit;
+import java.awt.datatransfer.StringSelection;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.ItemEvent;
+import java.awt.event.ItemListener;
+import java.awt.event.MouseListener;
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.URL;
+import java.net.URLDecoder;
+import java.util.Hashtable;
+import java.util.StringTokenizer;
+import java.util.zip.GZIPInputStream;
+import javax.swing.AbstractAction;
+import javax.swing.Action;
+import javax.swing.JButton;
+import javax.swing.JComboBox;
+import javax.swing.JComponent;
+import javax.swing.JFrame;
+import javax.swing.JOptionPane;
+import javax.swing.JTextField;
+import javax.swing.JToolBar;
+import javax.swing.KeyStroke;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathConstants;
+import javax.xml.xpath.XPathFactory;
+import org.w3c.dom.Document;
+import org.w3c.dom.DocumentFragment;
+import org.w3c.dom.Element;
+import org.xhtmlrenderer.pdf.ITextRenderer;
+import org.xhtmlrenderer.simple.FSScrollPane;
+import org.xhtmlrenderer.swing.ScalableXHTMLPanel;
+import org.xhtmlrenderer.swing.ScaleChangeEvent;
+import org.xhtmlrenderer.swing.ScaleChangeListener;
+import org.xhtmlrenderer.swing.SelectionHighlighter;
+
+/**
+ *
+ * @author chm
+ */
+public class EditorHtmlViewer extends JFrame implements UpdatableToolbar, ScaleChangeListener {
+ public static String DEFAULT_TITLE = "Document XeMeLios";
+
+ private Hashtable<String,File> documents = null;
+ private DocumentsModel documentsModel = null;
+ private XemeliosUserAgent userAgent = null;
+ private final XemeliosXhtmlPanel xhtmlRenderer;
+ private JComboBox cbxZoom;
+ private HtmlViewer.ScaleFactor[] availableScales;
+ private JButton pbPrint, pbPrevious, pbNext;
+ private JTextField dfUrl;
+ private SelectionHighlighter highlighter;
+ private JButton pbCopy;
+
+ private PropertiesExpansion applicationConfiguration;
+
+ /** Creates a new instance of EditorHtmlViewer */
+ public EditorHtmlViewer(Hashtable<String,File> documents, DocumentsModel documentsModel, String uri,XemeliosUser user, PropertiesExpansion applicationConfiguration) {
+ super(DEFAULT_TITLE);
+ this.applicationConfiguration = applicationConfiguration;
+ this.documents=documents;
+ this.documentsModel=documentsModel;
+ userAgent = new LocalUserAgent((Component)this,this,this.documentsModel,this.documents,applicationConfiguration, user);
+ xhtmlRenderer = new XemeliosXhtmlPanel(userAgent, this) {
+ @Override
+ public void setDocument(File file) throws Exception {
+ super.setDocument(file);
+ setScalePolicy(SCALE_POLICY_NONE);
+ }
+
+ @Override
+ public void setDocument(Document doc, String url) {
+ super.setDocument(doc, url);
+ setScalePolicy(SCALE_POLICY_NONE);
+ }
+
+ @Override
+ public void setDocument(InputStream stream, String url) throws Exception {
+ super.setDocument(stream, url);
+ setScalePolicy(SCALE_POLICY_NONE);
+ }
+ };
+ initializeComponents(uri);
+ setDefaultCloseOperation(EXIT_ON_CLOSE);
+ }
+
+ public class LocalUserAgent extends XemeliosUserAgent {
+ private DocumentBuilder db = null;
+ private DocumentsModel documentsModel = null;
+ private Hashtable<String,File> documents = null;
+
+ public LocalUserAgent(Component parent, UpdatableToolbar tb, DocumentsModel docs, Hashtable<String,File> documents,PropertiesExpansion applicationProperties, XemeliosUser user) {
+ //super(null,parent,tb,user);
+ super(parent, applicationProperties, user);
+ setToolbar(tb);
+ this.documentsModel=docs;
+ this.documents=documents;
+ DocumentBuilderFactory dbf = FactoryProvider.getDocumentBuilderFactory();
+ dbf.setNamespaceAware(true);
+ try {
+ db = dbf.newDocumentBuilder();
+ } catch(Throwable t) {
+ // we ignore it, suppose Dom is correctly configured if editors can build xml files...
+ }
+ }
+ @Override
+ public Dest calculateQuery(String query) {
+ AbstractUriTransformer uriTransformer = null;
+ NavigationContext ctx = null;
+ if(nc==null) {
+ ctx=new NavigationContext();
+ } else {
+ ctx = nc.clone();
+ }
+ Hashtable<String,Object> params = new Hashtable<String,Object>();
+ params.put(HtmlViewer.PARAM_DESTINATION,HtmlViewer.VALUE_DESTINATION_INTERNAL);
+ String servlet = null;
+ String sTmp = query;
+ int start = query.indexOf('?');
+ if(start>=0) {
+ servlet = query.substring(query.indexOf("/")+1,start);
+ sTmp = query.substring(start+1);
+ }
+ if("query".equals(servlet)) {
+ StringTokenizer st = new StringTokenizer(sTmp,"&");
+ while(st.hasMoreTokens()) {
+ String data = st.nextToken();
+ int pos = data.indexOf('=');
+ if(pos>0) {
+ String paramName = data.substring(0,pos);
+ String paramValue = null;
+ try {
+ paramValue=URLDecoder.decode(data.substring(pos+1),"UTF-8");
+ } catch(Throwable t) {
+ }
+ if("docId".equals(paramName)) {
+ ctx.setDocId(paramValue);
+ String className = null;
+ try {
+ className = Loader.getDocumentsInfos(null).getDocumentById(paramValue).getGlobalUriTransformer();
+ } catch(Exception ex) {
+ ex.printStackTrace();
+ }
+ if(className!=null) {
+ try {
+ Class clazz = Class.forName(className);
+ Object o = clazz.newInstance();
+ if(o instanceof AbstractUriTransformer) {
+ uriTransformer = (AbstractUriTransformer)o;
+ }
+ } catch(Exception ex) {
+ ex.printStackTrace(System.err);
+ }
+ }
+ }
+ else if("etatId".equals(paramName)) ctx.setEtatId(paramValue);
+ else if("elementId".equals(paramName)) ctx.setElementId(paramValue);
+ else if("collectivite".equals(paramName)) ctx.setCollectivite(paramValue);
+ else if("budget".equals(paramName)) ctx.setBudget(paramValue);
+ else if("sp1".equals(paramName)) ctx.setSp1(paramValue);
+ else if("sp2".equals(paramName)) ctx.setSp2(paramValue);
+ else if("path".equals(paramName)) ctx.setPath(paramValue);
+ else {
+ if(paramName.startsWith("xsl:param")) {
+ int virg = paramValue.indexOf(',');
+ String pName = paramValue.substring(1,virg);
+ String pValue = paramValue.substring(virg+1,paramValue.length()-1);
+ params.put(pName,pValue);
+ }
+ }
+ if(uriTransformer!=null) uriTransformer.transformUriParam(paramName, paramValue, params);
+ }
+ }
+ return generateDestContext(ctx,params,HtmlViewer.INTERNAL_DESTINATION);
+ } else if("resource".equals(servlet)) {
+ Dest ret = null;
+ try {
+ File resourceDir = new File(applicationConfiguration.getProperty("xemelios.resources.location"));
+ File res = new File(resourceDir,sTmp);
+ ret = new Dest(res.toURI().toURL(),false);
+ } catch(Throwable t) {}
+ return ret;
+ } else if("attachment".equals(servlet)) {
+ DocumentModel dm = documentsModel.getDocumentById(ctx.getDocId());
+ if(dm.getId().equals("pes-aller")) {
+ File fDoc = documents.get(ctx.getDocId());
+ if(fDoc==null) {
+ JOptionPane.showMessageDialog(EditorHtmlViewer.this,"Aucun "+dm.getTitre()+" disponible.","Erreur",JOptionPane.ERROR_MESSAGE);
+ }
+ try {
+ String[] args = sTmp.split("&");
+ String idUnique = null;
+ for(String s:args) {
+ if(s.startsWith("pjId")) {
+ idUnique = s.substring(5);
+ break;
+ }
+ }
+ Document doc = db.parse(fDoc);
+ XPathFactory xpf = XPathFactory.newInstance();
+ XPath xp = xpf.newXPath();
+ NamespaceContextImpl ns = new NamespaceContextImpl();
+ ns.addMapping("n", "http://www.minefi.gouv.fr/cp/helios/pes_v2/Rev0/aller");
+ xp.setNamespaceContext(ns);
+ Element pj = (Element)xp.evaluate("//n:PJ[n:IdUnique/@V='"+idUnique+"']", doc, XPathConstants.NODE);
+ if(pj!=null) {
+ String nomFichier = xp.evaluate("//n:PJ[n:IdUnique/@V='"+idUnique+"']/n:NomPJ/@V",pj);
+ nomFichier = nomFichier.replaceAll(" ", "_");
+ Element contenu = (Element)xp.evaluate("//n:PJ[n:IdUnique/@V='"+idUnique+"']/n:Contenu",pj,XPathConstants.NODE);
+ if(contenu!=null) {
+ File tmp = new File(FileUtils.getTempDir(),nomFichier);
+ if(tmp.exists()) tmp.delete();
+ Element pesFacture = (Element)xp.evaluate("n:PESFacture",contenu,XPathConstants.NODE);
+ if(pesFacture!=null) {
+ TransformerFactory tFactory = FactoryProvider.getTransformerFactory();
+ Transformer t = tFactory.newTransformer();
+ t.transform(new DOMSource(pesFacture), new StreamResult(tmp));
+ } else {
+ // c'est un fichier
+ String text = xp.evaluate("//n:PJ[n:IdUnique/@V='"+idUnique+"']/n:Contenu/n:Fichier/text()",contenu);
+ byte[] buffer = Base64.decode(text);
+ GZIPInputStream gz = new GZIPInputStream(new ByteArrayInputStream(buffer));
+ FileOutputStream fos = new FileOutputStream(tmp);
+ byte[] array = new byte[1024];
+ int read = gz.read(array);
+ while(read>0) {
+ fos.write(array, 0, read);
+ read = gz.read(array);
+ }
+ fos.flush(); fos.close();
+ }
+ StartUrl.startUrl(tmp.toURI().toURL().toExternalForm());
+ } else {
+ JOptionPane.showMessageDialog(EditorHtmlViewer.this,"Le contenu de la PJ n'est pas fournit","Erreur",JOptionPane.ERROR_MESSAGE);
+ }
+ } else {
+ JOptionPane.showMessageDialog(EditorHtmlViewer.this,"La PJ "+idUnique+" n'est pas disponible dans le flux.","Erreur",JOptionPane.ERROR_MESSAGE);
+ }
+ } catch(Exception ex) {
+ JOptionPane.showMessageDialog(EditorHtmlViewer.this,ex.getMessage(),ex.getClass().getName(),JOptionPane.ERROR_MESSAGE);
+ ex.printStackTrace();
+ }
+ }
+// return null;
+ }
+ return null;
+ }
+ @Override
+ public Dest generateDestContext(NavigationContext ctx, Hashtable<String,Object> params, final boolean toExternalDest) {
+// boolean noException = false;
+ Dest ret = null;
+ try {
+ DocumentModel dm = documentsModel.getDocumentById(ctx.getDocId());
+ if(dm==null) throw new LocalException("doc "+ctx.getDocId()+" inconnu");
+ EtatModel em = dm.getEtatById(ctx.getEtatId());
+ if(em==null) throw new LocalException("etat "+ctx.getEtatId()+" inconnu");
+ ElementModel element=(ctx.getElementId()!=null?em.getElementById(ctx.getElementId()):em.getBrowsableElement());
+ File fDoc = documents.get(dm.getId());
+ if(fDoc==null) throw new LocalException("Aucun "+dm.getTitre()+" disponible.");
+ Document doc = db.parse(fDoc);
+ File f = null;
+ f = new File(new File(new File(System.getProperty("user.home")),"xemelios/documents-def-ovrrd"),element.getXslt());
+ if(!f.exists())
+ f = new File(em.getParent().getBaseDirectory(),element.getXslt());
+// File f = new File(em.getParent().getBaseDirectory(),element.getXslt());
+// DEBUG
+// FileChannel fChIn = new FileInputStream(f).getChannel();
+// WritableByteChannel wbc = Channels.newChannel(System.out);
+// fChIn.transferTo(0, fChIn.size(), wbc);
+// fChIn.close(); wbc.close();
+// END DEBUG
+ InputStream is = IoUtils.getInputStream(f.getPath());
+// Hashtable<String,Object> parameters = new Hashtable<String,Object>();
+// parameters.putAll(params);
+ TransformerFactory tFactory = FactoryProvider.getTransformerFactory();
+ tFactory.setURIResolver(new CustomURIResolver(tFactory.getURIResolver(),f.getParentFile().toURI().toURL().toExternalForm()));
+ Transformer t = tFactory.newTransformer(new StreamSource(is));
+ if(params.get(HtmlViewer.PARAM_DESTINATION)==null) {
+ t.setParameter(HtmlViewer.PARAM_DESTINATION,em.useExternalBrowser()?HtmlViewer.VALUE_DESTINATION_EXTERNAL:HtmlViewer.VALUE_DESTINATION_INTERNAL);
+ }
+ for(String key:params.keySet()) {
+ t.setParameter(key, params.get(key));
+ }
+ // on passe la nomenclature en parametre
+ t.setParameter("repository", doc);
+ // on passe la config
+ t.setParameter("config",documentsModel.getSmallDOM());
+ if(ctx.getCollectivite()!=null)
+ t.setParameter("collectivite",ctx.getCollectivite());
+ if(ctx.getBudget()!=null)
+ t.setParameter("budget",ctx.getBudget());
+// InputStream htmlStream = DematTransform.transform(doc,is,parameters,f.getParentFile().toURI().toURL().toExternalForm());
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ t.transform(new DOMSource(doc), new StreamResult(baos));
+ ByteArrayInputStream htmlStream = new ByteArrayInputStream(baos.toByteArray());
+ File tmp = File.createTempFile("xemelios-data-",".html",FileUtils.getTempDir());
+ BufferedInputStream bis = new BufferedInputStream(htmlStream);
+ BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmp));
+ byte[] buff = new byte[1024];
+ int lengthRead = bis.read(buff);
+ while(lengthRead>0) {
+ bos.write(buff,0,lengthRead);
+ lengthRead = bis.read(buff);
+ }
+ bos.flush();
+ bos.close();
+ URL url = tmp.toURI().toURL();
+ nc=ctx;
+ ret = new Dest(url,toExternalDest);
+ } catch(LocalException lEx) {
+ JOptionPane.showMessageDialog(getViewer(),lEx.getMessage(),"Erreur de paramétrage",JOptionPane.ERROR_MESSAGE);
+ } catch(Exception ex) {
+ Component comp2 = getViewer();
+ while(comp2!=null && !(comp2 instanceof JFrame))
+ comp2 = comp2.getParent();
+ if(comp2!=null)
+ new DisplayExceptionDlg((JFrame)comp2,ex);
+ else
+ new DisplayExceptionDlg((JFrame)null,ex);
+ }
+ return ret;
+ }
+
+ }
+
+ @Override
+ public void scaleChanged(ScaleChangeEvent evt) {
+ if(evt.getComponent()==xhtmlRenderer) {
+ double scale = evt.getScale();
+ int ix = -1;
+ for(int i=0;i<availableScales.length;i++) {
+ HtmlViewer.ScaleFactor sf=availableScales[i];
+ if(sf.getFactor()==scale) {
+ ix = i;
+ break;
+ }
+ }
+ ItemListener[] iListeners = cbxZoom.getItemListeners();
+ for(ItemListener il:iListeners) cbxZoom.removeItemListener(il);
+ if(ix==-1) {
+ int scalePolicy = xhtmlRenderer.getScalePolicy();
+ switch (scalePolicy) {
+ case ScalableXHTMLPanel.SCALE_POLICY_FIT_WIDTH: ix = 8; break;
+ case ScalableXHTMLPanel.SCALE_POLICY_FIT_HEIGHT: ix = 9; break;
+ case ScalableXHTMLPanel.SCALE_POLICY_FIT_WHOLE: ix = 10; break;
+ }
+ }
+ cbxZoom.setSelectedIndex(ix);
+ for(ItemListener il:iListeners) cbxZoom.addItemListener(il);
+ }
+ }
+ protected void initializeComponents(String uri) {
+ HtmlViewer.ScaleFactor[] scales = HtmlViewer.initializeScales();
+ availableScales=scales;
+ IhmFactory iF=IhmFactory.newInstance();
+ xhtmlRenderer.addScaleChangeListener(this);
+ MouseListener[] lls = xhtmlRenderer.getMouseListeners();
+// for (int i = 0; i < lls.length; i++) {
+// MouseListener ll = lls[i];
+// if ( ll instanceof LinkListener ) {
+// xhtmlRenderer.addMouseMotionListener((MouseMotionListener)ll);
+// }
+// }
+ highlighter = new SelectionHighlighter();
+ highlighter.install(xhtmlRenderer);
+ xhtmlRenderer.addMouseListener(highlighter);
+
+ FSScrollPane scroller;
+ getContentPane().setLayout(new BorderLayout());
+ JToolBar tb = new JToolBar();
+ tb.add(pbPrevious=new JButton(IhmFactory.getIconFromResource(ImageResources.BRW_PREVIOUS)));
+ tb.add(pbNext=new JButton(IhmFactory.getIconFromResource(ImageResources.BRW_NEXT)));
+ tb.add(pbPrint = new JButton(IhmFactory.getIconFromResource(ImageResources.PRINT)));
+ final Action copyAction = new AbstractAction(null,IhmFactory.getIconFromResource(ImageResources.EDIT_COPY)) {
+
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ try {
+ DocumentFragment df = highlighter.getSelectionRange().extractContents();
+ StringSelection ss = new StringSelection(XmlUtils.getStringRepresentation(df));
+ Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, ss);
+ } catch(Exception ex) {}
+ }
+ };
+ tb.add(pbCopy = new JButton(copyAction));
+ pbCopy.setToolTipText("Copier");
+
+ final Action selectAllAction = new AbstractAction(null,IhmFactory.getIconFromResource(ImageResources.EDIT_SELECT_ALL)) {
+
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ highlighter.selectAll();
+ }
+
+ };
+ JButton pbSelectAll = new JButton(selectAllAction);
+ pbSelectAll.setToolTipText("Tout sélectionner");
+ tb.add(pbSelectAll);
+
+ getRootPane().registerKeyboardAction(copyAction, "copy", KeyStroke.getKeyStroke("ctrl C"), JComponent.WHEN_IN_FOCUSED_WINDOW);
+ getRootPane().registerKeyboardAction(selectAllAction, "selectAll", KeyStroke.getKeyStroke("ctrl A"), JComponent.WHEN_IN_FOCUSED_WINDOW);
+ tb.addSeparator();
+ tb.add(iF.newLabel("URL ","normal"));
+ tb.add(dfUrl = new JTextField());
+ dfUrl.setEditable(false);
+ Dimension dim = dfUrl.getMinimumSize();
+ dfUrl.setMinimumSize(new Dimension(100,(int)dim.getHeight()));
+ tb.addSeparator();
+ tb.add(iF.newLabel("Zoom ","normal"));
+ cbxZoom = new JComboBox(scales);
+ cbxZoom.addItemListener(new ItemListener() {
+ @Override
+ public void itemStateChanged(ItemEvent e) {
+ if (e.getStateChange() == ItemEvent.SELECTED) {
+ HtmlViewer.ScaleFactor factor = (HtmlViewer.ScaleFactor) e.getItem();
+ if (factor.getFactor() == HtmlViewer.ScaleFactor.PAGE_WIDTH) {
+ xhtmlRenderer.setScalePolicy(ScalableXHTMLPanel.SCALE_POLICY_FIT_WIDTH);
+ xhtmlRenderer.doLayout();
+ } else if (factor.getFactor() == HtmlViewer.ScaleFactor.PAGE_HEIGHT) {
+ xhtmlRenderer.setScalePolicy(ScalableXHTMLPanel.SCALE_POLICY_FIT_HEIGHT);
+ xhtmlRenderer.doLayout();
+ } else if (factor.getFactor() == HtmlViewer.ScaleFactor.PAGE_WHOLE) {
+ xhtmlRenderer.setScalePolicy(ScalableXHTMLPanel.SCALE_POLICY_FIT_WHOLE);
+ xhtmlRenderer.doLayout();
+ } else {
+ xhtmlRenderer.setScale(factor.getFactor());
+ }
+ }
+ }
+ });
+ cbxZoom.setSelectedIndex(2);
+ tb.add(cbxZoom);
+ getContentPane().add(tb,BorderLayout.PAGE_START);
+ getContentPane().add(scroller = new FSScrollPane(xhtmlRenderer),BorderLayout.CENTER);
+ scroller.setMinimumSize(new Dimension(WIDTH,HEIGHT));
+ scroller.setPreferredSize(new Dimension(WIDTH, HEIGHT));
+ scroller.setIgnoreRepaint(false);
+ pbPrint.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ printToPDF();
+ }
+ });
+ pbPrint.setToolTipText("Imprimer");
+ pbPrevious.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ goBack();
+ }
+ });
+ pbNext.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ goForward();
+ }
+ });
+ pbPrevious.setEnabled(false); pbNext.setEnabled(false);
+ if(uri!=null) {
+ try {
+ String eForm = userAgent.resolveURI(uri);
+ if(eForm!=null) {
+ dfUrl.setText(eForm);
+ xhtmlRenderer.setDocument(eForm);
+ }
+ } catch(Throwable t) {
+ t.printStackTrace();
+ System.exit(1);
+ }
+ }
+ pack();
+ setSize(700,600);
+ }
+ protected void printToPDF() {
+ try {
+ File tmp = File.createTempFile("xemelios-data-",".pdf",FileUtils.getTempDir());
+ OutputStream os = new FileOutputStream(tmp);
+ ITextRenderer renderer = new ITextRenderer();
+ // G. DON contribution
+ String fileName = dfUrl.getText();
+ int posDiez = fileName.indexOf("#");
+ if (posDiez!=-1) {
+ fileName = fileName.substring(0,posDiez);
+ }
+ File fToPDFize = new File(new URL(fileName).toURI());
+ // END contribution G.DON
+ if(fToPDFize.exists()) {
+ renderer.setDocument(fToPDFize);
+ renderer.layout();
+ renderer.createPDF(os,true);
+ os.flush(); os.close();
+ StartUrl.startUrl(tmp.getAbsolutePath());
+ }
+ } catch(Exception ex) {
+ ex.printStackTrace();
+ }
+ }
+ protected void goBack() {
+ if(userAgent.hasBack())
+ xhtmlRenderer.setDocument(userAgent.getBack());
+ else updateToolbarButtons();
+ }
+ protected void goForward() {
+ if(userAgent.hasForward())
+ xhtmlRenderer.setDocument(userAgent.getForward());
+ else updateToolbarButtons();
+ }
+ @Override
+ public void updateToolbarButtons() {
+ pbPrevious.setEnabled(userAgent.hasBack());
+ pbNext.setEnabled(userAgent.hasForward());
+ }
+ @Override
+ public void setBaseUrl(String url) {
+ dfUrl.setText(url);
+ }
+}
--- /dev/null
+/*
+ *
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 Christophe Marchand <christophe.marchand@axyus.com>
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+package fr.gouv.finances.cp.xemelios.controls.editors;
+
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentsModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.Loader;
+import fr.gouv.finances.dgfip.xemelios.controls.core.AbstractControlContentHandler;
+import fr.gouv.finances.dgfip.xemelios.controls.core.ControlParser;
+import fr.gouv.finances.dgfip.xemelios.controls.core.ControlProgressListener;
+import fr.gouv.finances.dgfip.xemelios.controls.core.MainControl;
+import fr.gouv.finances.dgfip.xemelios.controls.core.models.ControlsModel;
+import fr.gouv.finances.dgfip.xemelios.controls.core.models.DocumentControlModel;
+import fr.gouv.finances.dgfip.xemelios.auth.UnauthorizedException;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+import fr.gouv.finances.dgfip.xemelios.common.ToolException;
+import fr.gouv.finances.dgfip.xemelios.utils.FileUtils;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.math.BigDecimal;
+import java.util.Hashtable;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.transform.stream.StreamSource;
+import org.apache.log4j.Logger;
+
+/**
+ *
+ * @author chm
+ */
+public class StandaloneController implements ControlProgressListener {
+ private static final Logger logger = Logger.getLogger(StandaloneController.class);
+
+ private static final int MODE_CTRL = 1;
+ private static final int MODE_DISPLAY = 2;
+
+ private DocumentModel pesConfig = null;
+
+ /** Creates a new instance of StandaloneController */
+ public StandaloneController(int mode) throws Exception {
+ XemeliosUser localUser = new LocalUser();
+ DocumentsModel config = Loader.getDocumentsInfos(System.getProperty(Constants.SYS_PROP_DOC_DEF_DIR));
+
+ pesConfig = config.getDocumentById("PES_Aller");
+ DocumentModel rapportConfig = config.getDocumentById("rapportapport");
+ Hashtable<String, File> documents = new Hashtable<String, File>();
+ StringBuffer uri = new StringBuffer();
+
+ File fichierEnrichi = new File("/home/chm/tmp/pesv2-enrichi.xml");
+ File rapport = new File("/home/chm/tmp/rapport.xml");
+// File fileToRead = new File("/home/chm/devel/RECETTE_XEMELIOS/3.3.0.5/fichiers/CONTROLE_PESV2_OK.xml");
+// File fileToRead = new File("/mnt/perso/christophe.marchand/PES_DEP_ET_REC_AVEC_PJ.xml");
+ File fileToRead = new File("/home/chm/DGCP/magnus/testGDONXemeliosV4SansEspace (32).xml");
+ File rapportEnrichi = new File("/home/chm/tmp/rapport-enrichi.xml");
+
+ if (mode == MODE_CTRL) {
+ final DocumentModel dm2 = pesConfig;
+ final ControlsModel cm = getControlsModel();
+ final DocumentControlModel dcm = cm.getDocumentById(pesConfig.getId());
+
+ MainControl mc = new MainControl(
+ pesConfig,
+ pesConfig.getNamespaces(),
+ dcm,
+// pesConfig.getTitre(),
+ new File(pesConfig.getBaseDirectory(), dcm.getControlTechById("TECH03").getParamTechById("schemaLocation").getValue())) {
+
+ @Override
+ public AbstractControlContentHandler getControlContentHandler(String documentModelId, DocumentControlModel docCtrlMod, Hashtable<String, Object> parameters, String file, ControlProgressListener cpl) {
+ AbstractControlContentHandler cch = new AbstractControlContentHandler(
+ getDocumentModelId(),
+ dm2.getNamespaces(),
+ dcm,
+ parameters, file, null) {
+
+ @Override
+ public Pair getCollectivite(String documentModelId, String fileName) throws ToolException {
+ return new Pair("xxxxxxxxxxx", "Collectivité d'analyse");
+ }
+
+ @Override
+ public Pair getBudget(String documentModelId, Pair collectivite, String fileName) throws ToolException, UnauthorizedException {
+ return new Pair("00", "Budget principal");
+ }
+ };
+ return cch;
+ }
+
+ @Override
+ public void writeControlConfigFile() throws IOException {
+ File output = new File(dm2.getBaseDirectory(), dm2.getControlConfigFile());
+ OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(output), "ISO-8859-1");
+ XmlOutputter outputter = new XmlOutputter(os, "ISO-8859-1");
+ cm.marshall(outputter);
+ os.flush();
+ os.close();
+ }
+ };
+ mc.setControlProgressListener(this);
+ if(pesConfig.getTextToXmlTransformer()!=null)
+ mc.setTextToXmlTransformer(pesConfig.getTextToXmlTransformer());
+
+ File tmpEnrichi = new File(FileUtils.getTempDir(), "tmp-pesv2-enrichi.xml");
+
+ mc.setParameters(getControlParameters());
+ mc.setFileToControl(fileToRead);
+ mc.setFichierEnrichiLocation(tmpEnrichi.getAbsolutePath());
+ mc.setRapportLocation(rapport.getAbsolutePath());
+
+ // use any utility to run control
+ mc.run();
+
+ if (mc.getControlStatus() != MainControl.STATUS_NOT_CONTROLLED) {
+ if (mc.getControlStatus() > MainControl.STATUS_NOT_SCHEMA_VALID) {
+ // on applique la XSL d'import specifique aux controle standalone au flux enrichi
+ TransformerFactory tFactory = FactoryProvider.getTransformerFactory();
+ Transformer tr = tFactory.newTransformer(new StreamSource(new File(pesConfig.getBaseDirectory(), pesConfig.getGlobalImportXsltFile())));
+ StreamResult result = new StreamResult(fichierEnrichi);
+ tr.transform(new StreamSource(tmpEnrichi), result);
+ result.getOutputStream().flush();
+ result.getOutputStream().close();
+ // change this if not forked
+ tmpEnrichi.deleteOnExit();
+
+ documents.put("PES_Aller", fichierEnrichi);
+ }
+ if (rapportConfig.getGlobalImportXsltFile() != null && rapportConfig.getGlobalImportXsltFile().length() > 0) {
+ TransformerFactory tFactory = FactoryProvider.getTransformerFactory();
+ Transformer tr = tFactory.newTransformer(new StreamSource(new File(rapportConfig.getBaseDirectory(), rapportConfig.getGlobalImportXsltFile())));
+ StreamResult result = new StreamResult(rapportEnrichi);
+ tr.transform(new StreamSource(rapport), result);
+ result.getOutputStream().flush();
+ result.getOutputStream().close();
+ } else {
+ rapportEnrichi = rapport;
+ }
+ documents.put("rapport", rapportEnrichi);
+ uri.append("xemelios:/query?collectivite=").append(mc.getCollectivite() != null ? mc.getCollectivite().key : "").append("&budget=").append(mc.getBudget() != null ? mc.getBudget().key : "");
+ uri.append("&docId=rapport&etatId=DonneesRapport&path=[n:Id/@n:V='").append(mc.getIdRapport()).append("']");
+ }
+ tmpEnrichi.deleteOnExit();
+ } else {
+ TransformerFactory tFactory = FactoryProvider.getTransformerFactory();
+ Transformer tr = tFactory.newTransformer(new StreamSource(new File(pesConfig.getBaseDirectory(), pesConfig.getGlobalImportXsltFile())));
+ StreamResult result = new StreamResult(fichierEnrichi);
+ tr.transform(new StreamSource(fileToRead), result);
+ result.getOutputStream().flush();
+ result.getOutputStream().close();
+// DEBUG PURPOSES
+ Transformer tra = tFactory.newTransformer();
+ tra.transform(new StreamSource(fichierEnrichi), new StreamResult(System.out));
+
+ documents.put("PES_Aller", fichierEnrichi);
+ uri.append("xemelios:/query?docId=PES_Aller&etatId=general_view");
+ }
+ EditorHtmlViewer ehv = new EditorHtmlViewer(documents, config, uri.toString(), localUser, new PropertiesExpansion(System.getProperties()));
+ ehv.setLocationRelativeTo(null);
+ ehv.setVisible(true);
+ }
+
+ protected Hashtable<String, Object> getControlParameters() {
+ // in control config file, param types are
+ // string -> java.lang.String
+ // boolean -> java.lang.Boolean
+ // decimal -> java.math.BigDecimal
+ // integer -> java.lang.Integer
+ //
+ // multi-valued params are String arrays (java.lang.String[]) values
+
+
+ // here, filled with default values from PES as an example
+ Hashtable<String, Object> ret = new Hashtable<String, Object>();
+ ret.put("nomencl", "M14"); // values can be M14, M21, M22, M31, M52, M61, M71
+ ret.put("typnomencl", "Nature"); // values can be Nature, Fonction, Nature-ref-fonct
+ ret.put("votop", Boolean.FALSE);
+ ret.put("suivdgp", Boolean.TRUE);
+ ret.put("dureedgp", new Integer(45));
+ ret.put("coltva", Boolean.TRUE);
+ ret.put("servTVA", new String[]{}); // list of services
+ ret.put("compteTVA", new String[]{}); // list of comptes
+ ret.put("tauxTVA", new String[]{"2.1", "5.5", "19.6"}); // String array of VAT rates
+ ret.put("seuilMax", new BigDecimal(90000));
+ ret.put("seuilEmission", new BigDecimal(10));
+ ret.put("codProd", new String[]{"69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80",
+ "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97",
+ "98", "99", "100", "101", "102", "103", "104", "105", "106", "107", "248", "300", "302", "305",
+ "306", "307", "308"}); // String array of product codes
+ return ret;
+ }
+
+ @Override
+ public void notifyImportFinished(MainControl.Triplet triplet) {
+ }
+
+ @Override
+ public void notifyImportInterrupted(boolean hide) {
+ }
+
+ @Override
+ public void stopWaiting() {
+ }
+
+ @Override
+ public void notifyTechniqueValidationFailed() {
+ }
+
+ public static void main(String[] args) {
+ try {
+ new StandaloneController(MODE_CTRL);
+ } catch (Throwable t) {
+ t.printStackTrace();
+ }
+ }
+
+ /**
+ * @TODO : AUTHORISATIONS A GERER CORRECTEMENT
+ */
+ public static class LocalUser implements XemeliosUser {
+
+ @Override
+ public String getId() {
+ return "local";
+ }
+
+ @Override
+ public String getDisplayName() {
+ return getId();
+ }
+
+ @Override
+ public boolean hasRole(String arg0) {
+ return true;
+ }
+
+ @Override
+ public boolean hasDocument(String arg0) {
+ return true;
+ }
+
+ @Override
+ public boolean hasCollectivite(String arg0, DocumentModel dm) {
+ return true;
+ }
+ }
+ private ControlsModel getControlsModel() {
+ ControlsModel ret = null;
+ try {
+ ControlParser cp = new ControlParser();
+ cp.parse(new File(pesConfig.getBaseDirectory(), pesConfig.getControlConfigFile()));
+ ControlsModel c = (ControlsModel) cp.getMarshallable();
+ c.validate();
+ ret = c;
+ } catch (Exception ex) {
+ logger.debug("Error in getControlsModel()!!!", ex);
+ }
+ return ret;
+ }
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.3" maxVersion="1.3" type="org.netbeans.modules.form.forminfo.JDialogFormInfo">
+ <Properties>
+ <Property name="defaultCloseOperation" type="int" value="0"/>
+ <Property name="title" type="java.lang.String" value="Mise à jour de la base de données"/>
+ <Property name="alwaysOnTop" type="boolean" value="true"/>
+ <Property name="resizable" type="boolean" value="false"/>
+ </Properties>
+ <SyntheticProperties>
+ <SyntheticProperty name="formSizePolicy" type="int" value="1"/>
+ </SyntheticProperties>
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="2"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="1" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="1" attributes="0">
+ <Component id="progress" alignment="0" pref="364" max="32767" attributes="0"/>
+ <Component id="message" alignment="0" pref="364" max="32767" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Component id="message" pref="9" max="32767" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="progress" min="-2" max="-2" attributes="0"/>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Component class="javax.swing.JLabel" name="message">
+ </Component>
+ <Component class="javax.swing.JProgressBar" name="progress">
+ <Properties>
+ <Property name="stringPainted" type="boolean" value="true"/>
+ </Properties>
+ </Component>
+ </SubComponents>
+</Form>
--- /dev/null
+/*
+ * DlgPatchProgress.java
+ *
+ * Created on 22 mars 2007, 11:43
+ */
+
+package fr.gouv.finances.cp.xemelios.data.ui;
+
+import javax.swing.JFrame;
+import javax.swing.SwingUtilities;
+
+/**
+ *
+ * @author chm
+ */
+public class DlgPatchProgress extends javax.swing.JDialog implements fr.gouv.finances.dgfip.xemelios.data.ui.PatchProgress {
+ private long maxProgress, currentProgress;
+
+ /** Creates new form DlgPatchProgress */
+ public DlgPatchProgress() {
+ super((JFrame)null, false);
+ initComponents();
+ setLocationRelativeTo(null);
+ }
+
+ @Override
+ public void startProgress(String message) {
+ this.message.setText(message);
+ startProgress();
+ pack();
+ }
+
+ @Override
+ public void startProgress() {
+ currentProgress = 0L;
+ }
+
+ @Override
+ public void setMaxProgress(long maxProgress) {
+ this.maxProgress = maxProgress;
+ }
+
+ @Override
+ public void pushProgress() {
+ currentProgress++;
+ displayProgress();
+ }
+
+ @Override
+ public void endProgress() {
+ currentProgress = maxProgress;
+ displayProgress();
+ }
+ private void displayProgress() {
+ final int progressValue = (int)((float)currentProgress/(float)maxProgress*100f);
+ Runnable p = new Runnable() {
+ @Override
+ public void run() {
+ progress.setValue(progressValue);
+ progress.paintImmediately(0,0,progress.getWidth(),progress.getHeight());
+ }
+ } ;
+ if(SwingUtilities.isEventDispatchThread()) {
+ p.run();
+ }
+ else try {
+ SwingUtilities.invokeAndWait(p);
+ } catch(Throwable t) {
+ t.printStackTrace();
+ }
+ }
+
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
+ private void initComponents() {
+ message = new javax.swing.JLabel();
+ progress = new javax.swing.JProgressBar();
+
+ setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
+ setTitle("Mise \u00e0 jour de la base de donn\u00e9es");
+ setAlwaysOnTop(true);
+ setResizable(false);
+
+ progress.setStringPainted(true);
+
+ org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
+ .addContainerGap()
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
+ .add(org.jdesktop.layout.GroupLayout.LEADING, progress, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 364, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.LEADING, message, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 364, Short.MAX_VALUE))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(message, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 9, Short.MAX_VALUE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(progress, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .addContainerGap())
+ );
+ pack();
+ }// </editor-fold>//GEN-END:initComponents
+
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JLabel message;
+ private javax.swing.JProgressBar progress;
+ // End of variables declaration//GEN-END:variables
+
+ @Override
+ public long getProgress() {
+ return currentProgress;
+ }
+
+ @Override
+ public void setProgress(long progress) {
+ currentProgress = progress;
+ displayProgress();
+ }
+
+ @Override
+ public void setMessage(String message) {
+ this.message.setText(message);
+ Runnable rr = new Runnable() {
+ @Override
+ public void run() {
+ DlgPatchProgress.this.message.paintImmediately(0, 0, DlgPatchProgress.this.message.getWidth(), DlgPatchProgress.this.message.getHeight());
+ }
+ };
+ if(SwingUtilities.isEventDispatchThread())
+ rr.run();
+ else
+ try {
+ SwingUtilities.invokeAndWait(rr);
+ } catch(Throwable t) {}
+ }
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.debug;
+
+import javax.swing.JComponent;
+import javax.swing.RepaintManager;
+import javax.swing.SwingUtilities;
+
+public class CheckThreadViolationRepaintManager extends RepaintManager {
+
+ // it is recommended to pass the complete check
+ private boolean completeCheck = true;
+
+ public boolean isCompleteCheck() {
+ return completeCheck;
+ }
+
+ public void setCompleteCheck(boolean completeCheck) {
+ this.completeCheck = completeCheck;
+ }
+
+ @Override
+ public synchronized void addInvalidComponent(JComponent component) {
+ checkThreadViolations(component);
+ super.addInvalidComponent(component);
+ }
+
+ @Override
+ public void addDirtyRegion(JComponent component, int x, int y, int w, int h) {
+ checkThreadViolations(component);
+ super.addDirtyRegion(component, x, y, w, h);
+ }
+
+ private void checkThreadViolations(JComponent c) {
+ if (!SwingUtilities.isEventDispatchThread() && (completeCheck || c.isShowing())) {
+ Exception exception = new Exception();
+ boolean repaint = false;
+ boolean fromSwing = false;
+ StackTraceElement[] stackTrace = exception.getStackTrace();
+ for (StackTraceElement st : stackTrace) {
+ if (repaint && st.getClassName().startsWith("javax.swing.")) {
+ fromSwing = true;
+ }
+ if ("repaint".equals(st.getMethodName())) {
+ repaint = true;
+ }
+ }
+ if (repaint && !fromSwing) {
+ //no problems here, since repaint() is thread safe
+ return;
+ }
+ exception.printStackTrace();
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2008 axYus - www.axyus.com
+ * 2008 L. Meckert - laurent.meckert@axyus.com
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.export;
+
+import java.util.Hashtable;
+import java.util.Vector;
+import java.util.Enumeration;
+import fr.gouv.finances.dgfip.utils.Amount;
+import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
+import java.io.IOException;
+import java.io.FileWriter;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.nio.channels.FileChannel;
+import java.text.NumberFormat;
+import java.text.SimpleDateFormat;
+import org.apache.log4j.Logger;
+
+import fr.gouv.finances.dgfip.utils.StringUtilities;
+
+import fr.gouv.finances.dgfip.xemelios.utils.CSVWriter;
+
+// ABANDONNE POUR LE MOMENT
+import fr.gouv.finances.dgfip.xemelios.export.ExportElementModel;
+// AU BESOIN REPRENDRE D'APRES HtmlTableExporter.java
+
+public class CsvExporter extends ExportUndertaker {
+
+ private static final Logger logger = Logger.getLogger(CsvExporter.class);
+ private static final int MAX_ROWS_PER_SHEET = 65000; // test 30
+ // contiendra la liste des sheets XLS, dans l'ordre devant être créé (par ex : SHEET_Bordereau, SHEET_Titre, SHEET_Ligne)
+ private Hashtable<String, Vector<CsvSheet>> sheets = new Hashtable<String, Vector<CsvSheet>>();
+ private Exporter caller;
+ // private HtmlSheet mainSheet;
+ private String workbookPrefix = null;
+ private SimpleDateFormat df;
+
+ public CsvExporter(Exporter caller) {
+ this.caller = caller;
+ df = new SimpleDateFormat(caller.getApplicationConfiguration().getProperty("xemelios.date.format", "dd/MM/yyyy"));
+ }
+
+ // Fonctions appellees par Exporter.java
+ /**
+ * Initialisation
+ */
+ void initialize() throws Exception {
+ /**
+ *
+ * Version rudimentaire pour demarrer
+ * A partir du nom de fichier demande, deduit le prefixe
+ * utilise par tous les fchiers csv.
+ */
+ // Pour que l'appelant soit content je lui genene un fichier excel vide
+ //
+ FileWriter xl = new FileWriter(caller.fDest);
+ xl.close();
+
+ workbookPrefix = StringUtilities.removeFileNameSuffix(caller.fDest.getPath());
+
+ }
+
+ void recopieFichier(String src, String dst, boolean overwrite) {
+ FileChannel in = null; // canal d'entrée
+ FileChannel out = null; // canal de sortie
+
+ try {
+ // Initimport java.nio.channels.FileChannel;
+ in = new FileInputStream(src).getChannel();
+ out = new FileOutputStream(dst).getChannel();
+
+ // Copie depuis le in vers le out
+ in.transferTo(0, in.size(), out);
+ } catch (Exception e) {
+ e.printStackTrace(); // n'importe quelle exception
+ } finally { // finalement on ferme
+ if (in != null) {
+ try {
+ in.close();
+ } catch (IOException e) {
+ }
+ }
+ if (out != null) {
+ try {
+ out.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+ }
+
+ /**
+ * Crée un <tt>CsvSheet</tt> et ajoute la liste des entetes de colonne
+ * @param eem
+ * @throws Exception
+ */
+ void buildSheet(ExportElementModel eem) throws Exception {
+ Vector<CsvSheet> v = sheets.get(eem.getId());
+ if (v == null) {
+ v = new Vector<CsvSheet>();
+ }
+ sheets.put(eem.getId(), v);
+ String libelle = eem.getLibelle();
+ libelle = StringUtilities.toAscii(libelle,"_").replaceAll(" ", "_");
+
+ if (libelle.length() >= 31) {
+ libelle = libelle.substring(0, 30);
+ if (libelle.endsWith(".")) {
+ libelle = libelle.substring(0, 29);
+ }
+ }
+
+ String fileName = workbookPrefix + "_" + libelle; // + ".csv";
+
+ CsvSheet sheet = new CsvSheet();
+ sheet.open(fileName);
+
+ v.add(sheet);
+
+ for (ExportElementModel e : eem.getEnfants()) {
+ buildSheet(e);
+ }
+ caller.firstSheetId = eem.getId();
+ }
+
+ /**
+ * Apporte des finitions
+ */
+ void finish() throws Exception {
+ // pour l'instant rien
+ }
+
+ /**
+ * Fermeture et nettoyage
+ */
+ void close() {
+ Enumeration elems = sheets.keys();
+ while (elems.hasMoreElements()) {
+ String k = (String) elems.nextElement();
+ Vector<CsvSheet> v = sheets.get(k);
+ for (CsvSheet s : v) {
+
+ s.close();
+ }
+
+ }
+ // mainSheet.close();
+ }
+
+ /**
+ * Verifie l'existence d'unr feuille dans le classeur
+ * @param sheetId le nom de la feuille
+ */
+ boolean sheetExists(String sheetId) {
+ Vector<CsvSheet> v = sheets.get(sheetId);
+ if (v != null) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * renvoie le dernier numero de ligne utilisee dans la derniere feuille de nom sheetId
+ */
+ int getLastLineLastSheet(String sheetId) {
+ // suppose qu'on a appele sheetExists(sheetId)
+ CsvSheet ws = getLastSheet(sheetId);
+ return (ws.getRows() < 2 ? 2 : ws.getRows());
+ }
+
+ /**
+ * Remplit une cellule avec la valeur correctement formatée.
+ * @param sheet
+ * @param o
+ * @param ligne
+ * @param col
+ * @throws WriteException
+ */
+ void writeCell(String sheetId, Object o, int line, int col, boolean bypassLineRenum) throws Exception {
+
+
+
+ int newline = 0;
+ if (bypassLineRenum) {
+ newline = line;
+ } else {
+ int _ligne = caller.getLastLine(sheetId);
+ if (_ligne >= (MAX_ROWS_PER_SHEET * sheets.get(sheetId).size())) {
+ splitSheet(sheetId);
+ }
+
+ // renumérotation de la ligne
+ newline = _ligne;
+ newline = _ligne % (MAX_ROWS_PER_SHEET) + 2;
+ }
+
+ CsvSheet sheet = getLastSheet(sheetId);
+ String s = formatted(o, line);
+ // Si line = 0 = c'est un titre
+ if (line == 0) {
+ sheet.addTitle(s, col);
+ } else if (line == 1) {
+ // Si line = 1 = c'est un nom de champ
+ sheet.addName(s, col);
+ } else {
+ // sinon c'est une ligne normale
+ sheet.addEntry(s, col);
+ }
+
+
+ }
+
+ /**
+ * reunit des cellules dans la derniere des feuilles de nom sheetId
+ * @param sheetId = nom de la feuille
+ * @param col1 = colonne de depart
+ * @param row1 = ligne de depart
+ * @param col2 = colonne d'arrivee
+ * @param row2= ligne d'arrivee
+
+ */
+ void mergeCells(String sheetId, int col1, int row1, int col2, int row2) {
+ /* forget it
+ CsvSheet _ws = getLastSheet(sheetId);
+
+ try {
+ _ws.mergeCells(col1, row1, col2, row2);
+ } catch(Exception e) {}
+ */
+ }
+
+ void flushLine(String sheetId) {
+ CsvSheet _ws = getLastSheet(sheetId);
+ _ws.flushLine();
+ }
+
+ // Fonctions a usage interne mises en protected on sait jamais
+ /**
+ * Formatage de l'objet a ecrire
+ */
+ protected String formatted(Object o, Integer line) {
+ String rawStr;
+ if (o instanceof java.lang.Integer) {
+ rawStr = ((Integer) o).toString();
+ } else if (o instanceof java.lang.Float) {
+ rawStr = ((Float) o).toString();
+ } else if (o instanceof java.util.Date) {
+ rawStr = df.format(o);
+ } else if (o instanceof Amount) {
+ Double d = new Double(((Amount) o).doubleValue());
+ rawStr = d.toString();
+ } else if (o instanceof java.lang.String) {
+ rawStr = (String) o;
+ } else {
+ rawStr = (String) o;
+ }
+ return rawStr;
+ }
+
+ /**
+ * Numero d'ordre suivant celui de la feuille de nom id
+ */
+ protected int afterSheet(String id) {
+ /* String[]names = workbook.getSheetNames();
+ for (int i=1; i<names.length; i++) {
+ if (names[i].equals(id)) return i+1;
+ }
+ return 1;*/
+ return 1;
+ }
+
+ /**
+ * Récupère la derniere feuille correspondant a
+ * l'objet de nom id (c'est celle en cours d'edition)
+ */
+ protected CsvSheet getLastSheet(String sheetId) {
+ Vector<CsvSheet> v = sheets.get(sheetId);
+ if (v != null) {
+ return v.get(v.size() - 1);
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Récupère la premiere feuille correspondant au premier parent de
+ * l'objet de nom id
+ */
+ protected CsvSheet getRootSheetBefore(String id) {
+ CsvSheet ret = null;
+ ElementModel e = caller.getEMFromId(id);
+ if (e.getSimpleParent() != null) {
+ String pName = e.getSimpleParent().getElement();
+ ret = sheets.get(pName).get(0);
+ }
+ return ret;
+ }
+
+ /**
+ * creee une nouvelle feuille de nom id suivi d'un _ er d'un numero d'ordre
+ * appelle lorsque la feuille
+ * precedente de meme nom "deborde"
+ */
+ protected CsvSheet splitSheet(String id) {
+ Vector<CsvSheet> v = sheets.get(id);
+ CsvSheet wsRef = v.get(0);
+ CsvSheet otherRef = getLastSheet(id);
+
+ wsRef.close();
+
+ CsvSheet ws = new CsvSheet();
+
+
+ NumberFormat nf = NumberFormat.getInstance(); // Get Instance of NumberFormat
+ nf.setMinimumIntegerDigits(2); // The minimum Digits required is 5
+ nf.setMaximumIntegerDigits(3); // The maximum Digits required is 5
+
+ String sb = (nf.format((long) v.size()));
+ String fname = wsRef.getName() + "_" + sb;
+ ws.open(fname);
+
+ addRefInMainSheet(fname, false);
+ ws.titles = wsRef.titles;
+ ws.names = wsRef.names;
+ ws.maxTitle = wsRef.maxTitle;
+ ws.maxName = wsRef.maxName;
+ // ws.maxEntry = wsRef.maxEntry;
+
+ ws.flushTitles();
+ ws.flushNames();
+
+ v.add(ws);
+ return ws;
+
+
+ }
+
+ void addRefInMainSheet(String libelle, boolean addPrefix) {
+ String fileName;
+ if (addPrefix) {
+ fileName = workbookPrefix + "_" + libelle + ".csv";
+ } else {
+ fileName = libelle + ".csv";
+ }
+
+ String href = "<A HREF=\"file:///" + fileName + "\">" + libelle + "</A>";
+
+ // mainSheet.addEntry(href, 0);
+ //mainSheet.flushLine();
+
+ }
+
+ protected class CsvSheet {
+
+ String name; // nom de la "feuille"
+ CSVWriter writer; // objet consituant les lignes et les ecrivant dans le fichier
+ String[] titles; // pour noter la ligne de titre
+ String[] names; // pour noter la ligne de noms de champs
+ String[] entries; // pour noter la ligne en cours
+ int curTitle;
+ int curName;
+ int curEntry;
+ int colCount;
+ int rowCount;
+ int maxTitle;
+ int maxName;
+ int maxEntry;
+ boolean titlesFlushed;
+ boolean namesFlushed;
+
+ void open(String fname) {
+ try {
+ FileWriter out = new FileWriter(fname + ".csv");
+ writer = new CSVWriter(out);
+ } catch (IOException e) {
+ logger.error("HtmlSheet.open(" + fname + ")", e);
+ }
+ // Version initial tableau surdimensionnnes hum=
+ name = fname;
+ titles = new String[100];
+ names = new String[100];
+ entries = new String[100];
+ maxTitle = 0;
+ maxName = 0;
+ maxEntry = 0;
+ rowCount = 0;
+ titlesFlushed = false;
+ namesFlushed = false;
+ }
+
+ void close() {
+ if (writer != null) {
+ try {
+ writer.close();
+
+ } catch (IOException e) {
+ logger.error("HtmlSheet.close()", e);
+ }
+ writer = null;
+ }
+ }
+
+ String getName() {
+ return name;
+ }
+
+ int getRows() {
+ return rowCount;
+ }
+
+ void addTitle(String s, int col) {
+ if (!titlesFlushed) {
+ if (col >= titles.length || maxTitle >= titles.length) {
+ // cas ou il faut redimensionner
+ int oldlength = titles.length;
+ int newlength = oldlength + oldlength / 2;
+ String[] tm = new String[newlength];
+ for (int i = 0; i < oldlength; ++i) {
+ tm[i] = titles[i];
+ }
+ titles = tm;
+ }
+ while (maxTitle + 1 < col) {
+ maxTitle++;
+ titles[maxTitle] = formatted("", 0); // pour simuler la presentation en Excel pur
+
+ }
+ titles[col] = s;
+ if (col > maxTitle) {
+ maxTitle = col;
+ }
+
+ }
+ }
+
+ void addName(String s, int col) {
+ if (!namesFlushed) {
+ if (col >= names.length || maxName >= names.length) {
+ // cas ou il faut redimensionner
+ int oldlength = names.length;
+ int newlength = oldlength + oldlength / 2;
+ String[] tm = new String[newlength];
+ for (int i = 0; i < oldlength; ++i) {
+ tm[i] = names[i];
+ }
+ names = tm;
+ }
+ while (maxName + 1 < col) {
+ maxName++;
+ names[maxName] = formatted("", 1);
+ }
+ names[col] = s;
+ if (col > maxName) {
+ maxName = col;
+ }
+
+ }
+ }
+
+ void addEntry(String s, int col) {
+ if (col >= entries.length || maxEntry >= entries.length) {
+ // cas ou il faut redimensionner
+ int oldlength = entries.length;
+ int newlength = oldlength + oldlength / 2;
+ String[] tm = new String[newlength];
+ for (int i = 0; i < oldlength; ++i) {
+ tm[i] = entries[i];
+ }
+ entries = tm;
+ }
+
+
+ while (maxEntry + 1 < col) {
+ maxEntry++;
+ entries[maxEntry] = formatted("", 999);
+ }
+ entries[col] = s;
+ if (col > maxEntry) {
+ maxEntry = col;
+ }
+ }
+
+ void mergeCells(int col1, int row1, int col2, int row2) {
+ /* INUTILE if( col1 == col2) { // on ne sait pas faire autrement!!
+ int i = row1 + 1;
+ while(i < row2) {
+ if(col1 == 0) { // titres
+ titles[i] = formatted("", 0);
+ } else if(col1 == 1) {// noms de champs
+ names[i] = formatted("", 0);
+ }
+ ++i;
+ }
+ }*/
+ }
+
+ void flushTitles() {
+ writer.writeNext(titles, maxTitle);
+ titlesFlushed = true;
+ ++rowCount;
+ }
+
+ void flushNames() {
+ writer.writeNext(names, maxName);
+ namesFlushed = true;
+ ++rowCount;
+ }
+
+ void flushLine() {
+ if (!titlesFlushed) {
+ flushTitles();
+ }
+ if (!namesFlushed) {
+ flushNames();
+ }
+
+ writer.writeNext(entries, maxEntry);
+ maxEntry = 0;
+ ++rowCount;
+ }
+ };
+}
--- /dev/null
+/*
+ * Copyright
+ * 2008 axYus - www.axyus.com
+ * 2007 N.Le Corre - nicolas.lecorre@axyus.com
+ * 2008 L. Meckert - laurent.meckert@axyus.com
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.export;
+
+import fr.gouv.finances.dgfip.xemelios.export.ExportElementModel;
+
+public abstract class ExportUndertaker {
+ public ExportUndertaker() {};
+ public ExportUndertaker(Exporter e) {};
+ /**
+ * Permet d'initialiser l'ExportUndertaker
+ * @throws Exception
+ */
+ abstract void initialize() throws Exception;
+ /**
+ * Demande la construction de la feuille correspondant à cet element
+ * @param eem
+ * @throws Exception
+ */
+ abstract void buildSheet (ExportElementModel eem) throws Exception ;
+ abstract void finish() throws Exception;
+ abstract void close();
+ /**
+ * Indique si une feuille pour cet élément a déjà été créée
+ * @param sheetId
+ * @return
+ */
+ abstract boolean sheetExists(String sheetId) ;
+ abstract int getLastLineLastSheet (String sheetId) ;
+ abstract void mergeCells( String sheetId, int col1, int row1, int col2, int row2);// throws Exception;
+ abstract void writeCell (String sheetId, Object o, int line, int col, boolean bypassLineRenum) throws Exception;
+ abstract void flushLine(String el);
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 N.Le Corre - nicolas.lecorre@axyus.com
+ * 2008 L. Meckert - laurent.meckert@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.export;
+
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import java.io.File;
+import java.util.Hashtable;
+import java.util.Stack;
+import java.util.Vector;
+
+
+import java.util.Enumeration;
+
+import javax.swing.JDialog;
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathConstants;
+import javax.xml.xpath.XPathFactory;
+
+
+import org.apache.log4j.Logger;
+import org.jdesktop.swingworker.SwingWorker;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+import fr.gouv.finances.dgfip.utils.xml.dompath.DomPath;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import fr.gouv.finances.dgfip.xemelios.common.config.ChampModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ListeResultatModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.SimpleElement;
+import fr.gouv.finances.dgfip.xemelios.data.DataResultSet;
+import fr.gouv.finances.cp.xemelios.ui.export.DlgSearchConfig;
+import fr.gouv.finances.dgfip.xemelios.data.DataHandler;
+
+import fr.gouv.finances.dgfip.xemelios.utils.HashSwap;
+
+import fr.gouv.finances.dgfip.xemelios.utils.LongueurMax;
+import fr.gouv.finances.dgfip.xemelios.export.ConfigModel;
+import fr.gouv.finances.dgfip.xemelios.export.ExportChampModel;
+import fr.gouv.finances.dgfip.xemelios.export.ExportElementModel;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+
+public class Exporter extends SwingWorker {
+
+ public class ExportedElementTag {
+
+ @LongueurMax(value = 1)
+ public int dummy;
+
+ public ExportedElementTag(int i) {
+ dummy = i;
+ }
+ }
+ static Logger logger = Logger.getLogger(Exporter.class);
+ private JDialog parentFrame = null;
+ // private EtatResultTableModel ertm;
+ private DataResultSet drs = null;
+ File fDest;
+ private ConfigModel cf = null;
+ private DocumentModel dm = null;
+ private String etatId;
+ private ElementModel em = null;
+ // LM statistiques
+ double timeStartGenerate = 0;
+ double timeEndGenerate = 0;
+ double gapGenerate = 0;
+ // Lm objet redefinissable reealisanteffectivement l'export.
+ // Selon sa classe genere Excel pur ou csv ou table Html(ou tout a fait autre chose que du Excel si on veut)
+ private ExportUndertaker undertaker;
+ private PropertiesExpansion applicationConfiguration;
+ // contiendra la liste des id d'élément déjà exportés
+ // -- regroupés par type d'élément. --
+ // Ceci afin de ne pas exporter plusieurs fois le même élément
+ // La valeur ajoutée dans le Vector est constituée de la concaténation des éléments formant la clef d'un Element
+ // On trouve la liste des éléments d'une clef dans la liste des champs, de la listeResultat d'un ElementModel
+ // private Hashtable<String, Hashtable<String,String >> exportedElements = new Hashtable<String, Hashtable<String,String >>();
+ private Hashtable<String, HashSwap<ExportedElementTag>> exportedElements = new Hashtable<String, HashSwap<ExportedElementTag>>();
+ /**
+ * Contient, pour chaque type d'élément exporté (Bordereau, Titre, Ligne de titre), un compteur indiquant quel était le dernier numéro de ligne
+ */
+ private Hashtable<String, Integer> lignesExporteesForElement = new Hashtable<String, Integer>();
+
+ protected ExportUndertaker getUndertaker() {
+ String undertakerClassName = applicationConfiguration.getProperty(Constants.SYS_PROP_XEMELIOS_EXPORTER_CLASS);
+ if(undertakerClassName==null) undertakerClassName = "fr.gouv.finances.cp.xemelios.export.FullXlsExporter";
+
+
+ try {
+ Class undertakerClass = Class.forName(undertakerClassName);
+ Class[] exporterArgsClass = new Class[]{Exporter.class};
+ Object[] exporterArgs = new Object[]{this};
+ Constructor constructor = undertakerClass.getConstructor(exporterArgsClass);
+ ExportUndertaker ud = (ExportUndertaker) constructor.newInstance(exporterArgs);
+ return ud;
+ } catch (ClassNotFoundException e) {
+ logger.error("",e);
+ return null;
+ } catch (NoSuchMethodException e) {
+ logger.error("",e);
+ return null;
+ } catch (InstantiationException e) {
+ logger.error("",e);
+ return null;
+ } catch (IllegalAccessException e) {
+ logger.error("",e);
+ return null;
+ } catch (IllegalArgumentException e) {
+ logger.error("",e);
+ return null;
+ } catch (InvocationTargetException e) {
+ logger.error("",e);
+ return null;
+ }
+ }
+
+ private void addLine(String el) {
+ Integer l = lignesExporteesForElement.get(el);
+ if (l == null) {
+ l = new Integer(0);
+ }
+ l = new Integer(l.intValue() + 1);
+ lignesExporteesForElement.put(el, l);
+
+ undertaker.flushLine(el);
+ }
+
+ int getLastLine(String el) {
+ Integer l = lignesExporteesForElement.get(el);
+ if (l == null) {
+ l = new Integer(0);
+ }
+ return l.intValue();
+ }
+
+
+ public Exporter(File f, DataResultSet drs, DocumentModel dm, String etatId, ElementModel em, ConfigModel cf, PropertiesExpansion applicationConfiguration) {
+ this.drs = drs;
+ this.fDest = f;
+ this.dm = dm;
+ this.etatId = etatId;
+ this.em = em;
+ this.cf = cf;
+ this.applicationConfiguration = applicationConfiguration;
+ // on vire la clause ORDER BY du DataResultSet
+ drs.getListeResultatModel().setTriDefaut(null);
+ drs.getListeResultatModel().setOrdre(null);
+ }
+
+ @Override
+ protected Object doInBackground() throws Exception {
+ doExport();
+ if (!isCancelled()) {
+ ((DlgSearchConfig) getParentFrame()).showXLS();
+ } else {
+ ((DlgSearchConfig) getParentFrame()).getGlassPane().setVisible(false);
+ }
+ return null;
+ }
+
+ @Override
+ protected void done() {
+ super.done();
+ cleanAfterRun();
+ }
+
+ public PropertiesExpansion getApplicationConfiguration() {
+ return applicationConfiguration;
+ }
+
+ public void cleanAfterRun() {
+ // nettoyage de la mémoire
+ timeEndGenerate = System.currentTimeMillis();
+ gapGenerate = timeEndGenerate - timeStartGenerate;
+ //quelle est la memoire utilisee par exported elements
+ System.gc();
+ Enumeration cles = exportedElements.keys();
+ while (cles.hasMoreElements()) {
+ String k = (String) cles.nextElement();
+ HashSwap<ExportedElementTag> val = (HashSwap<ExportedElementTag>) exportedElements.get(k);
+ try {
+ val.destruct();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+
+ exportedElements.clear();
+ exportedElements = null;
+ System.gc();
+ }
+
+ /** Le point d'entrée est l'élément que l'on a recherché (em)
+ * a partir de lui, on exporte ses champs en respectant la config
+ * puis on exporte son/ses parent(s)
+ * puis on exporte son/ses enfant(s)
+ */
+ protected void doExport() {
+ logger.debug("Exporter.doExport();");
+ try {
+ undertaker = getUndertaker();
+ timeStartGenerate = System.currentTimeMillis();
+ undertaker.initialize();
+
+ /**
+ * Création des feuilles du classeur
+ */
+ for (ExportElementModel eem : cf.getExportModel().getEnfants()) {
+ if (shouldEEMBeExported(eem)) {
+ undertaker.buildSheet(eem);
+ }
+ }
+ /**
+ * Export de l'élément concerné par la recherche
+ */
+ int ligne = 2;
+ /*
+ * le LRM contient une série de champs qui ne correspond pas forcément à la sélection de l'utilisateur dans la configuration de l'export
+ * on le clone, vide sa liste de champs et y ajoute tous les champs exportables
+ */
+ ListeResultatModel lrm = drs.getListeResultatModel();
+ ListeResultatModel lrmClone = lrm.clone();
+ lrmClone.setParent(lrm.getParent());
+ // il est possible que le tri se fasse sur des champs non exportables; il faut les inclure dans le select quand même
+ String tridefault = lrmClone.getTriDefaut();
+ lrmClone.removeAllChamps();
+ addAllExportableChamps(lrmClone, drs.getListeResultatModel().getParent(), tridefault);
+ drs.setListeResultatModel(lrmClone);
+ drs.firstPage();
+ int page = 0;
+ do {
+
+ // on avance d'une page que si l'on ne lit pas la première.
+ // comment ça il ne vous revient pas mon "++!=" ?? :p
+ if (page++ != 0) {
+ drs.nextPage();
+ }
+ // on avance d'une ligne
+ while (drs.hasNext() && !isCancelled()) {
+ DataHandler dh = drs.next();
+ logger.debug("exporting "+dh.getDocumentId());
+ exportEM(drs.getListeResultatModel().getParent(), dh, drs.getListeResultatModel().getParent().getId(), ligne);
+ ligne++;
+ }
+ } while (drs.hasNextPage() && !isCancelled());
+
+ if (!isCancelled()) {
+ undertaker.finish();
+ }
+ } catch (Exception e) {
+ logger.error("Exporter Error catched", e);
+ } finally {
+ undertaker.close();
+ }
+logger.debug("endOf doExport()");
+ }
+
+ /**
+ * Ajoute au <tt>ListeResultatModel</tt> tous les champs exportables contenus dans l'<tt>ElementModel</tt>
+ * ainsi que ceux qui sont critères de tri
+ * @param l
+ * @param e
+ * @throws Exception
+ */
+ private void addAllExportableChamps(ListeResultatModel l, ElementModel e, String tridefault) throws Exception {
+ Vector<String> tri = new Vector<String>();
+ if(tridefault!=null) {
+ for (String s : tridefault.split(",")) {
+ tri.add(s);
+ }
+ }
+ for (ChampModel c : e.getListeResultat().getListeChamps()) {
+ if (c.isExportable() || tri.contains(c.getId())) {
+ l.addChild(c, ChampModel.QN);
+ }
+ }
+ }
+
+ /**
+ * Rempli une ligne de <tt>WritableSheet</tt> avec les informations contenues dans le <tt>DataHandler</tt>
+ * conformément à la configuration
+ * @param _em
+ * @param _dh
+ * @param _ws
+ * @param _ligne
+ * @throws Exception
+ */
+ private void exportEM(ElementModel _em, DataHandler _dh, String sheetId, int _ligne) throws Exception {
+ // La configuration de l'élément concerné
+ ExportElementModel eem = null;
+ for (ExportElementModel e : cf.getExportModel().getEnfants()) {
+ eem = getEEMFromId(e, _em.getId());
+ if (eem != null) {
+ break;
+ }
+ }
+ // remplissage des feuilles des parents
+ Vector<SimpleElement> parents = pushParents(_em, "");
+ exportParents(parents, _dh);
+
+ // Ajout des colonnes des parents
+ int col = 0, oldCol = 0;
+ // si _ws est null, on ne peut pas exporter. C'est notamment le cas quand on a fait une recherche sur des lignes et qu'on exporte que le bordereau.
+ if (undertaker.sheetExists(sheetId)) {
+ for (int i = (parents.size() - 1); i >= 0; i--) {
+// if (_ligne < 2) {
+// }
+ col = writeCellsOfParent(dm.getEtatById(etatId).getElementById(parents.get(i).getElement()), parents.get(i).getPseudoCompletePath(), _dh, sheetId, _ligne, col, (_ligne <= 2), false);
+ undertaker.mergeCells(sheetId, oldCol, 0, col - 1, 0);
+ oldCol = col;
+ }
+
+ boolean firstCol = true;
+ // parcours des colonnes configurées
+ for (ExportChampModel ecm : eem.getChamps()) {
+ if (ecm.isSelectionne()) {
+ // première ligne => entete
+ if (_ligne == 2) {
+ if (firstCol) {
+ undertaker.writeCell(sheetId, _em.getTitre(), 0, col, true);
+ }
+ undertaker.writeCell(sheetId, ecm.getLibelle(), 1, col, true);
+ }
+ int index = getColumnIndex(ecm.getId(), _em);
+ if(index<0) {
+ throw new Exception("champ "+ecm.getId()+" not found in "+_em.getConfigXPath());
+ }
+ undertaker.writeCell(sheetId, _dh.getValueAtColumn(index), _ligne, col, false);
+ col++;
+ firstCol = false;
+ }
+ }
+
+ undertaker.mergeCells(sheetId, oldCol, 0, col - 1, 0);
+ // remplissage des feuilles des enfants
+ if (hasChildrenToExport(em)) {
+ exportEnfants(parents, em, _dh);
+ }
+
+ // mise à jour de la liste des éléments exportés
+ /* Hashtable<String, String> h = exportedElements.get(_em.getId());
+ if (h == null) h = new Hashtable<String, String>();
+ */
+ HashSwap<ExportedElementTag> h = exportedElements.get(_em.getId());
+ // Hashtable<String, String> h = exportedElements.get(_em.getId());
+ if (h == null) {
+ logger.info("new HashSwap..");
+ h = new HashSwap<ExportedElementTag>(ExportedElementTag.class);
+ logger.info("done");
+ exportedElements.put(_em.getId(), h);
+
+ }
+
+ // String vId = getIdentifiant (eem, _dh, _em);
+ String vId = getIdentifiant(_dh, _em);
+ if (!h.containsKey(vId)) {
+ h.put(vId, new ExportedElementTag(1));
+ }
+
+ addLine(sheetId);
+ }
+ }
+
+ private void exportEnfants(Vector<SimpleElement> parents, ElementModel _em, DataHandler _dh) throws Exception {
+ if (_em.getEnfant() != null) {
+ for (String s : _em.getEnfant().getEnfants().keySet()) {
+ SimpleElement enfantToExport = _em.getEnfant().getEnfants().get(s);
+
+ // la clé de cet élément
+ // La configuration de l'élément concerné
+ ExportElementModel eem = null;
+ for (ExportElementModel e : cf.getExportModel().getEnfants()) {
+ eem = getEEMFromId(e, s);
+ if (eem != null) {
+ break;
+ }
+ }
+ ExportElementModel eemP = null;
+ for (ExportElementModel e : cf.getExportModel().getEnfants()) {
+ eemP = getEEMFromId(e, _em.getId());
+ if (eemP != null) {
+ break;
+ }
+ }
+
+ // doit-on exporter cet enfant ?
+ if (shouldEEMBeExported(eem)) {
+
+ enfantToExport.setPseudoCompletePath("./" + enfantToExport.getPath());
+
+ // export des valeurs du fils en question
+ // export des clés de ce fils dans les feuilles de ses fils
+ Vector<Object> parentsValues = getParentsValues(parents, _dh);
+ for (ExportChampModel ecm : eemP.getChamps()) {
+ if (ecm.isIdentifiant()) {
+ parentsValues.add(_dh.getValueAtColumn(getColumnIndex(ecm.getId(), _em)));
+ }
+ }
+
+ exportEnfant(parentsValues, enfantToExport.getPseudoCompletePath(), enfantToExport, _dh.getElement(), enfantToExport.getElement(), _dh);
+ }
+ }
+ }
+ }
+
+ private Vector<Object> getParentsValues(Vector<SimpleElement> parents, DataHandler _dh) throws Exception {
+ Vector<Object> ret = new Vector<Object>();
+
+ for (int p = parents.size() - 1; p >= 0; p--) {
+ ret.addAll(getParentValues(parents.get(p), _dh));
+ }
+
+ return ret;
+ }
+
+ private Vector<Object> getParentValues(SimpleElement parent, DataHandler _dh) throws Exception {
+ Vector<Object> ret = new Vector<Object>();
+
+ ElementModel element = getEMFromId(parent.getElement());
+
+ XPathFactory xpf;
+ try {
+ xpf = XPathFactory.newInstance(XPathFactory.DEFAULT_OBJECT_MODEL_URI);
+ } catch (Throwable t) {
+ xpf = XPathFactory.newInstance();
+ }
+ XPath xp = xpf.newXPath();
+ xp.setNamespaceContext(dm.getNamespaces());
+ Node n = (Node) xp.evaluate(parent.getPseudoCompletePath(), _dh.getElement(), XPathConstants.NODE);
+ for (ChampModel cm : element.getListeResultat().getListeChamps()) {
+ if (cm.isIdentifiant()) {
+ DomPath dp = new DomPath(cm.getPath().getPath(), dm.getNamespaces());
+ ret.add(dp.getValue(n, false));
+ }
+ }
+
+ return ret;
+
+ }
+
+ private Vector<Object> getParentId(ElementModel parent, Object rootElement) throws Exception {
+ Vector<Object> ret = new Vector<Object>();
+
+ for (ChampModel cm : parent.getListeResultat().getListeChamps()) {
+ if (cm.isIdentifiant()) {
+ DomPath dp = new DomPath(cm.getPath().getPath(), dm.getNamespaces());
+ ret.add(dp.getValue((Node) rootElement, false));
+ }
+ }
+
+ return ret;
+
+ }
+
+ private void exportEnfant(Vector<Object> parentsValues, String pathToEnfant, SimpleElement enfantToExport, Object rootElement, String sheetId, DataHandler _dh) throws Exception {
+ // int col = 0;
+
+ int ligne = undertaker.getLastLineLastSheet(sheetId);
+ // // écriture des clefs des parents
+ // for (int p=0; p<parentsValues.size(); p++) {
+ // writeCell (_ws, parentsValues.get(p), ligne, col++);
+ // }
+
+ // écriture des valeurs de moi même
+ Vector<Node> nodes = writeCellsOfEnfant(parentsValues, getEMFromId(enfantToExport.getElement()), rootElement, pathToEnfant, sheetId, ligne/*, col*/, (ligne <= 2));
+
+ // appel de l'export de chaque enfant en lui passant ma clef, constituée de celle de mon parent et de la mienne
+ ElementModel e = getEMFromId(enfantToExport.getElement());
+ if (e.getEnfant() != null) {
+ for (String s : e.getEnfant().getEnfants().keySet()) {
+ SimpleElement se = e.getEnfant().getEnfants().get(s);
+
+ ExportElementModel eem = null;
+ for (ExportElementModel m : cf.getExportModel().getEnfants()) {
+ eem = getEEMFromId(m, se.getElement());
+ if (eem != null) {
+ break;
+ }
+ }
+ if (shouldEEMBeExported(eem)) {
+ for (Node n : nodes) {
+ Vector<Object> newParentsValues = new Vector<Object>();
+ newParentsValues.addAll(parentsValues);
+ newParentsValues.addAll(getParentId(getEMFromId(enfantToExport.getElement()), n));
+ exportEnfant(newParentsValues, se.getPath(), se, n, se.getElement(), _dh);
+ }
+ } else {
+ break;
+ }
+ }
+ }
+ }
+
+ private void exportParents(Vector<SimpleElement> parents, DataHandler _dh) throws Exception {
+ for (int i = 0; i < parents.size(); i++) {
+ SimpleElement parentToExport = parents.get(i);
+ if (undertaker.sheetExists(parentToExport.getElement())) {
+
+ // si ws est null, c'est un parent qu'on ne veux pas exporter
+
+ int ligne = getLastLine(parentToExport.getElement());
+ exportParent(parentToExport, parents, i, parentToExport.getElement(), _dh, ligne, true);
+ }
+ }
+ }
+
+ private int exportParent(SimpleElement parentToExport, Vector<SimpleElement> parents, int indInParents, String sheetId, DataHandler _dh, int ligne, boolean doCheckMAJ) throws Exception {
+ // a-t-on déjà exporté cet élément ?
+ ElementModel element = getEMFromId(parentToExport.getElement());
+ String parentPath = parentToExport.getPseudoCompletePath();
+ if (doCheckMAJ && isExporte(parentToExport.getElement(), getIdentifiant(_dh, parentPath, element))) {
+ return 0;
+ }
+
+ // on est arrivé au parent de plus haut niveau
+ int col = 0;
+ if (indInParents == parents.size() - 1) {
+ if (ligne < 2) {
+ }
+ col += writeCellsOfParent(element, parentToExport.getPseudoCompletePath(), _dh, sheetId, ligne, col, (ligne <= 2), (firstSheetId.equals(sheetId)));
+ if (doCheckMAJ) {
+ majExportes(parentToExport.getElement(), _dh, parentPath, element);
+ }
+ } // sinon il nous faut exporter les parents de plus haut niveau avant celui-ci
+ else {
+ // dans le cas où ce parent a lui aussi un parent à exporter, il faut l'exporter, peu importe si on l'a déjà fait car on en a besoin
+ col += exportParent(parents.get(indInParents + 1), parents, (indInParents + 1), sheetId, _dh, ligne, false);
+ if (indInParents == parents.size() - 1) {
+ if (ligne < 2) {
+ }
+ col += writeCellsOfParent(element, parentToExport.getPseudoCompletePath(), _dh, sheetId, ligne, col, (ligne <= 2), true);
+ if (doCheckMAJ) {
+ majExportes(parentToExport.getElement(), _dh, parentPath, element);
+ }
+ }
+ }
+ return col;
+ }
+
+ private boolean isExporte(String idColl, String id) {
+ // Hashtable<String,String> h = exportedElements.get(idColl);
+
+ boolean ret = false;
+ HashSwap<ExportedElementTag> h = exportedElements.get(idColl);
+ if (h == null) {
+ return false;
+ } else {
+ try {
+ if (h.containsKey(id)) {
+ ret = true;
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ return ret;
+ }
+
+ private void majExportes(String id, DataHandler _dh, String parentPath, ElementModel em) throws Exception {
+ // Hashtable<String,String> h = exportedElements.get(id);
+
+ HashSwap<ExportedElementTag> h = exportedElements.get(id);
+ if (h == null) {
+ // h = new Hashtable<String,String>();
+ logger.info("new HashSwap..");
+ h = new HashSwap<ExportedElementTag>(ExportedElementTag.class);
+ logger.info("done");
+ exportedElements.put(id, h);
+ }
+ String vId = getIdentifiant(_dh, parentPath, em);
+ if (!h.containsKey(vId)) {
+// logger.debug("putting "+vId+" in Hashswap");
+ h.put(vId, new ExportedElementTag(1));
+ }
+ }
+
+ /**
+ * Empile dans un <tt>Vector</tt> les ancêtres de _em du plus proche au plus ancien
+ * @param _em
+ * @param parentPath
+ * @return
+ */
+ private Vector<SimpleElement> pushParents(ElementModel _em, String parentPath) {
+ Vector<SimpleElement> ret = new Vector<SimpleElement>();
+
+ SimpleElement parent = _em.getSimpleParent();
+ if (parent != null) {
+ parent.setPseudoCompletePath(parent.getPath() + (!parentPath.equals("") ? "/" + parentPath : ""));
+ ret.add(parent);
+ ret.addAll(pushParents(dm.getEtatById(etatId).getElementById(parent.getElement()), parent.getPseudoCompletePath()));
+ }
+
+ return ret;
+ }
+
+ /**
+ * crée les cellules d'un parent d'un élément
+ * @param parent
+ * @param parentPath
+ * @param _dh
+ * @param _ws
+ * @param _ligne
+ * @return
+ * @throws Exception
+ */
+ private int writeCellsOfParent(ElementModel parent, String parentPath, DataHandler _dh, String sheetId, int _ligne, int _col, boolean firstLine, boolean completeLine) throws Exception {
+ int oldCol = _col;
+ XPathFactory xpf;
+ try {
+ xpf = XPathFactory.newInstance(XPathFactory.DEFAULT_OBJECT_MODEL_URI);
+ } catch (Throwable t) {
+ xpf = XPathFactory.newInstance();
+ }
+ XPath xp = xpf.newXPath();
+ xp.setNamespaceContext(dm.getNamespaces());
+ Node n = (Node) xp.evaluate(parentPath, _dh.getElement(), XPathConstants.NODE);
+ boolean firstCol = true;
+ for (ChampModel cm : parent.getListeResultat().getListeChamps()) {
+ if (cm.isIdentifiant()) {
+ DomPath dp = new DomPath(cm.getPath().getPath(), dm.getNamespaces());
+ Object o = dp.getValue(n, false);
+ // première ligne => entete
+ if (firstLine) {
+ // si c'est la première cellule, on ajoute le nom du parent au dessus
+ if (firstCol) {
+ undertaker.writeCell(sheetId, parent.getTitre(), 0, _col, true);
+ }
+ undertaker.writeCell(sheetId, cm.getLibelle(), 1, _col, true);
+ }
+ if (_ligne < 2) {
+ _ligne += 2;
+ }
+ Object value = cm.getValueOf(o);
+ undertaker.writeCell(sheetId, value, _ligne, _col++, false);
+ firstCol = false;
+ }
+ }
+ if (completeLine) {
+ addLine(sheetId);
+ }
+
+ // merge des cellules
+ if (firstLine) {
+ undertaker.mergeCells(sheetId, oldCol, 0, _col - 1, 0);
+ }
+
+ return _col;
+ }
+
+ private Vector<Node> writeCellsOfEnfant(Vector<Object> parentsValues, ElementModel enfant, Object rootElement, String enfantPath, String sheetId, int _ligne/*, int _col*/, boolean firstLine) throws Exception {
+ Vector<Node> ret = new Vector<Node>();
+ XPathFactory xpf;
+ try {
+ xpf = XPathFactory.newInstance(XPathFactory.DEFAULT_OBJECT_MODEL_URI);
+ } catch (Throwable t) {
+ xpf = XPathFactory.newInstance();
+ }
+ XPath xp = xpf.newXPath();
+ xp.setNamespaceContext(dm.getNamespaces());
+ Object xpathRet = xp.evaluate(enfantPath, rootElement, XPathConstants.NODESET);
+
+ // La configuration de l'élément concerné
+ ExportElementModel eem = null;
+ for (ExportElementModel e : cf.getExportModel().getEnfants()) {
+ eem = getEEMFromId(e, enfant.getId());
+ if (eem != null) {
+ break;
+ }
+ }
+
+ if (firstLine) {
+ Stack<ExportElementModel> s = new Stack<ExportElementModel>();
+ ExportElementModel tmp = eem;
+ while (true) {
+ ExportElementModel p = tmp.getParent();
+ tmp = p;
+ if (p != null) {
+ s.push(p);
+ } else {
+ break;
+ }
+ }
+
+ ExportElementModel ptmp = null;
+ int oldColTitre = 0, colTitre = 0;
+ while (!s.empty()) {
+ ptmp = s.pop();
+ oldColTitre = colTitre;
+ undertaker.writeCell(sheetId, ptmp.getLibelle(), 0, colTitre, true);
+
+ for (ExportChampModel ecm : ptmp.getChamps()) {
+ if (ecm.isIdentifiant()) {
+ undertaker.writeCell(sheetId, ecm.getLibelle(), 1, colTitre++, true);
+ }
+ }
+ undertaker.mergeCells(sheetId, oldColTitre, 0, (colTitre - 1), 0);
+
+ }
+ }
+
+ boolean firstCol = true;
+ int maligne = _ligne;
+ int macolonne = 0;
+ int maxCol = 0;
+ if(xpathRet instanceof NodeList) {
+ NodeList nodeListe = (NodeList)xpathRet;
+ for (int n = 0; n < nodeListe.getLength(); n++) {
+ // écriture des clefs des parents
+ int col = 0;
+ for (int p = 0; p < parentsValues.size(); p++) {
+ undertaker.writeCell(sheetId, parentsValues.get(p), maligne, col++, false);
+ }
+ macolonne = col;
+
+ Node node = nodeListe.item(n);
+ ret.add(node);
+ for (ExportChampModel ecm : eem.getChamps()) {
+ if (ecm.isSelectionne()) {
+ DomPath dp = new DomPath(enfant.getListeResultat().getChamps().get(ecm.getId()).getPath().getPath(), dm.getNamespaces());
+ Object o = "";
+ try {
+ o = dp.getValue(node, false);
+ } catch (Exception e) {
+ }
+ // première ligne => entete
+ if (firstLine) {
+ // si c'est la première cellule, on ajoute le nom du parent au dessus
+ if (firstCol) {
+ undertaker.writeCell(sheetId, enfant.getTitre(), 0, macolonne, true);
+ }
+ undertaker.writeCell(sheetId, ecm.getLibelle(), 1, macolonne, true);
+ }
+ try {
+ Object computed = enfant.getListeResultat().getChamps().get(ecm.getId()).getValueOf(o);
+ undertaker.writeCell(sheetId, computed, maligne, macolonne++, false);
+ }
+ catch(Exception ex) {
+ logger.error("while exporting "+enfant.getId()+"."+ecm.getId());
+ }
+ firstCol = false;
+ }
+ }
+ addLine(sheetId);
+
+ maligne++;
+ maxCol = macolonne;
+ macolonne = col;
+ // merge des cellules de l'entête
+ if (firstLine) {
+ firstLine = false;
+ undertaker.mergeCells(sheetId, col, 0, maxCol - 1, 0);
+ }
+ }
+// } else if(xpathRet instanceof List) {
+// List l = (List) xpathRet;
+// for(Iterator it = l.iterator();it.hasNext();) {
+// // écriture des clefs des parents
+// int col = 0;
+// for (int p = 0; p < parentsValues.size(); p++) {
+// undertaker.writeCell(sheetId, parentsValues.get(p), maligne, col++, false);
+// }
+// macolonne = col;
+//
+// Node node = (Node)it.next();
+// ret.add(node);
+// for (ExportChampModel ecm : eem.getChamps()) {
+// if (ecm.isSelectionne()) {
+// DomPath dp = new DomPath(enfant.getListeResultat().getChamps().get(ecm.getId()).getPath().getPath(), dm.getNamespaces());
+// Object o = "";
+// try {
+// o = dp.getValue(node, false);
+// } catch (Exception e) {
+// }
+// // première ligne => entete
+// if (firstLine) {
+// // si c'est la première cellule, on ajoute le nom du parent au dessus
+// if (firstCol) {
+// undertaker.writeCell(sheetId, enfant.getTitre(), 0, macolonne, true);
+// }
+// undertaker.writeCell(sheetId, ecm.getLibelle(), 1, macolonne, true);
+// }
+// try {
+// Object computed = enfant.getListeResultat().getChamps().get(ecm.getId()).getValueOf(o);
+// undertaker.writeCell(sheetId, computed, maligne, macolonne++, false);
+// }
+// catch(Exception ex) {
+// logger.error("while exporting "+enfant.getId()+"."+ecm.getId());
+// }
+// firstCol = false;
+// }
+// }
+// addLine(sheetId);
+//
+// maligne++;
+// maxCol = macolonne;
+// macolonne = col;
+// // merge des cellules de l'entête
+// if (firstLine) {
+// firstLine = false;
+// undertaker.mergeCells(sheetId, col, 0, maxCol - 1, 0);
+// }
+//
+// }
+ }
+
+ return ret;
+ }
+
+ /**
+ * Renvoie une chaine constituée de la concaténation des valeurs des champs formant l'identifiant (xx-yyy-zzzz)
+ * @param _eem
+ * @param _dh
+ * @param _em
+ * @return
+ * @throws Exception
+ */
+ private String getIdentifiant(DataHandler _dh, String parentPath, ElementModel _em) throws Exception {
+ String ret = "";
+
+ XPathFactory xpf;
+ try {
+ xpf = XPathFactory.newInstance(XPathFactory.DEFAULT_OBJECT_MODEL_URI);
+ } catch (Throwable t) {
+ xpf = XPathFactory.newInstance();
+ }
+ XPath xp = xpf.newXPath();
+ xp.setNamespaceContext(dm.getNamespaces());
+ Node node = (Node) xp.evaluate(parentPath, _dh.getElement(), XPathConstants.NODE);
+
+ for (ChampModel cm : _em.getListeResultat().getListeChamps()) {
+ if (cm.isIdentifiant()) {
+ DomPath dp = new DomPath(cm.getPath().getPath(), dm.getNamespaces());
+ Object o = dp.getValue(node, false);
+ if (o != null) {
+ if (ret.length() > 0) {
+ ret += "-";
+ }
+ ret += String.valueOf(o);
+ }
+ }
+ }
+
+ return ret;
+ }
+
+ private String getIdentifiant(DataHandler _dh, ElementModel _em) throws Exception {
+ String ret = "";
+
+ for (ChampModel cm : _em.getListeResultat().getListeChamps()) {
+ if (cm.isIdentifiant()) {
+ Object o = _dh.getValueAtColumn(getColumnIndex(cm.getId(), _em));
+ if (o != null) {
+ if (ret.length() > 0) {
+ ret += "-";
+ }
+ ret += String.valueOf(o);
+ }
+ }
+ }
+
+ return ret;
+ }
+
+ /**
+ * Retourne l'ExportElementModel de l'élément identifié par son id dans la configuration
+ * @param id
+ * @return
+ */
+ private ExportElementModel getEEMFromId(ExportElementModel _eem, String id) {
+ ExportElementModel ret = null;
+ if (_eem.getId().equals(id)) {
+ ret = _eem;
+ } else {
+ for (ExportElementModel e : _eem.getEnfants()) {
+ ret = getEEMFromId(e, id);
+ if (ret != null) {
+ break;
+ } // on a trouvé; inutile d'aller plus loin
+ }
+ }
+ return ret;
+ }
+
+ /**
+ * Retourne l'ElementModel de l'élément identifié par son id
+ * @param id
+ * @return
+ */
+ /*private*/ ElementModel getEMFromId(String id) {
+ return dm.getEtatById(etatId).getElementById(id);
+ }
+
+ /**
+ * Retourne l'index d'une colonne à partir de son id
+ * @param id l'id de la colonne
+ * @param em l'élément dans lequel on chreche la colonne
+ * @return
+ */
+ private int getColumnIndex(String id, ElementModel em) {
+ int ret = -1;
+ int j = 0;
+
+ Vector<String> tri = new Vector<String>();
+ String tridefault = em.getListeResultat().getTriDefaut();
+ for (String s : tridefault.split(",")) {
+ tri.add(s);
+ }
+
+ for (ChampModel cm : em.getListeResultat().getListeChamps()) {
+ if (cm.isExportable() || tri.contains(cm.getId())) {
+ if (id.equals(cm.getId())) {
+ ret = j;
+ break;
+ }
+ j++;
+ }
+ }
+ return ret;
+ }
+ String firstSheetId = "";
+
+ /**
+ * Indique si un ExportElementModel a au moins un champ qui doit être exporté et donc si on doit l'exporter
+ * @param _eem
+ * @return
+ */
+ private boolean shouldEEMBeExported(ExportElementModel _eem) {
+ if (_eem != null) {
+ for (ExportChampModel ecm : _eem.getChamps()) {
+ if (ecm.isSelectionne()) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Détermine si l'élément _em a au moins un enfant qui doit être exporté.
+ * On peut se contenter de tester les enfants directs de l'élément.
+ * En effet, si un petit fils est sélectionné à l'export, on aura pris soin de sélectionner
+ * ce qui constitue la clef de ses parents.
+ * @param _em
+ * @return
+ */
+ private boolean hasChildrenToExport(ElementModel _em) {
+ if (_em.getEnfant() == null) {
+ return false;
+ } else {
+ for (String s : _em.getEnfant().getEnfants().keySet()) {
+ SimpleElement se = _em.getEnfant().getEnfants().get(s);
+ // La configuration de l'élément concerné
+ ExportElementModel eem = null;
+ for (ExportElementModel e : cf.getExportModel().getEnfants()) {
+ eem = getEEMFromId(e, se.getElement());
+ if (eem != null) {
+ break;
+ }
+ }
+ if (shouldEEMBeExported(eem)) {
+ return true;
+ }
+ }
+ return false;
+ }
+ }
+
+ public JDialog getParentFrame() {
+ return parentFrame;
+ }
+
+ public void setParentFrame(JDialog parentFrame) {
+ this.parentFrame = parentFrame;
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2011 axYus - http://www.axyus.com
+ * 2011 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS_NB.
+ *
+ * XEMELIOS_NB 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 2 of the License, or
+ * (at your option) any later version.
+ *
+ * XEMELIOS_NB 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 Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with XEMELIOS_NB; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+
+package fr.gouv.finances.cp.xemelios.export;
+
+import fr.gouv.finances.dgfip.utils.Amount;
+import fr.gouv.finances.dgfip.utils.StringUtilities;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import fr.gouv.finances.dgfip.xemelios.export.ExportElementModel;
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.Hashtable;
+import jxl.CellView;
+import jxl.Workbook;
+import jxl.WorkbookSettings;
+import jxl.format.CellFormat;
+import jxl.write.DateFormat;
+import jxl.write.Formula;
+import jxl.write.Label;
+import jxl.write.NumberFormats;
+import jxl.write.WritableCell;
+import jxl.write.WritableCellFormat;
+import jxl.write.WritableFont;
+import jxl.write.WritableHyperlink;
+import jxl.write.WritableSheet;
+import jxl.write.WritableWorkbook;
+import org.apache.log4j.Logger;
+
+/**
+ * Cette classe réalise un export où chaque feuille est un docuemnt XLS indépendant,
+ * produit par JXL. Il n'est pas prévu de réassembler les feuilles dans un unique
+ * classeur
+ * @author cmarchand
+ */
+public class FullXlsExporter extends ExportUndertaker {
+ /**
+ * Le nombre maximal de lignes écrites dans une feuille
+ */
+ public static final int MAX_ROWS_PER_SHEET = 64000;
+ private static final Logger logger = Logger.getLogger(FullXlsExporter.class);
+
+ private WorkbookSettings settings;
+ private File baseFile;
+ private Exporter exporter;
+ private WritableWorkbook index;
+ private String baseFileName;
+
+ private ArrayList<String> sheetNames;
+ private Hashtable<String,ArrayList<WorkbookWrapper>> sheets;
+
+ // formattage des colonnes d'entête
+ private WritableFont fontEntete1 = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD, false);
+
+ public FullXlsExporter(Exporter exporter) {
+ super(exporter);
+ this.exporter=exporter;
+ }
+ @Override
+ void initialize() throws Exception {
+ settings = new WorkbookSettings();
+ settings.setUseTemporaryFileDuringWrite(true);
+ settings.setTemporaryFileDuringWriteDirectory(new File("."));
+ settings.setCellValidationDisabled(true);
+ settings.setGCDisabled(false);
+ settings.setDrawingsDisabled(true);
+ sheetNames = new ArrayList<String>();
+ sheets = new Hashtable<String, ArrayList<WorkbookWrapper>>();
+
+ baseFile = exporter.fDest;
+ baseFileName = baseFile.getName();
+ baseFileName = StringUtilities.removeFileNameSuffix(baseFileName);
+
+ index = Workbook.createWorkbook(baseFile);
+// index.set
+
+ logger.debug("JXL version="+Workbook.getVersion());
+ }
+
+ @Override
+ void buildSheet(ExportElementModel eem) throws Exception {
+ ArrayList<WorkbookWrapper> v = sheets.get(eem.getId());
+ if (v == null) {
+ v = new ArrayList<WorkbookWrapper>();
+ }
+ sheets.put(eem.getId(), v);
+ String sheetName = StringUtilities.toAscii(eem.getLibelle(),"_");
+ if(sheetName.length()>=31) {
+ sheetName = sheetName.substring(sheetName.length()-30);
+ if(sheetName.endsWith(".")) sheetName = sheetName.substring(0, sheetName.length()-1);
+ }
+
+ String fileName = baseFileName+"-"+sheetName+"-"+(v.size()+1)+".xls";
+ File sheetFile = new File(baseFile.getAbsoluteFile().getParentFile(), fileName);
+ WritableWorkbook sheet = Workbook.createWorkbook(sheetFile, settings);
+ sheet.createSheet(sheetName, 0);
+ WorkbookWrapper ww = new WorkbookWrapper(sheet, sheetFile, eem);
+ v.add(ww);
+
+ for (ExportElementModel e : eem.getEnfants()) {
+ buildSheet(e);
+ }
+ exporter.firstSheetId = eem.getId();
+ sheetNames.add(eem.getId());
+ }
+
+ @Override
+ void finish() throws Exception {
+// logger.debug("finish()");
+ }
+
+ @Override
+ void close() {
+ for(String sheetName: sheets.keySet()) {
+ ArrayList<WorkbookWrapper> books = sheets.get(sheetName);
+ for(WorkbookWrapper ww: books) {
+ try {
+ ww.purge();
+ } catch (Throwable t) {
+ logger.error("in close() - "+ww.file.getAbsolutePath(),t);
+ }
+ }
+ }
+ // TODO: écrire dans Index
+ WritableSheet ws = index.createSheet("Index", 0);
+ int elementCount=0;
+ try {
+ WritableCellFormat wcf = new WritableCellFormat(fontEntete1);
+ CellView cvCol = new CellView();
+ cvCol.setAutosize(true);
+ for(String key:sheetNames) {
+ ArrayList<WorkbookWrapper> books = sheets.get(key);
+ Label titre = new Label(elementCount, 0, books.get(0).eem.getLibelle(), wcf);
+ ws.addCell(titre);
+ int row = 1;
+ for(WorkbookWrapper ww:books) {
+// Label lbl = new Label(elementCount, row, ww.file.getName());
+ WritableHyperlink wh = new WritableHyperlink(
+ elementCount,
+ row,
+ new File(ww.file.getAbsoluteFile().getParentFile().getAbsoluteFile(),ww.file.getName()),
+// new File(ww.file.getName()),
+ ww.file.getName());
+// URL url = new URL("file://"+ww.file.getName());
+// WritableHyperlink wh = new WritableHyperlink(elementCount, row, elementCount, row, url, ww.file.getName());
+// ws.addCell(lbl);
+ ws.addHyperlink(wh);
+// String sF = "=HYPERLINK(\""+new File(ww.file.getAbsoluteFile().getParentFile().getAbsoluteFile(),ww.file.getName()).toURI().toURL().toExternalForm()+"\",\""+ww.file.getName()+"\")";
+// logger.debug(sF);
+// Formula formula = new Formula(elementCount, row, sF);
+// ws.addCell(formula);
+ row++;
+ }
+ ws.setColumnView(elementCount, cvCol);
+ CellView cvRow = new CellView();
+ cvRow.setSize(18*20);
+ ws.setRowView(0, cvRow);
+ elementCount++;
+ }
+ } catch(Exception ex) {
+ logger.error("writting index:",ex);
+ }
+ try {
+ index.write();
+ index.close();
+ index = null;
+ } catch (Throwable t) {
+ logger.error("in close() - "+baseFile.getAbsolutePath(),t);
+ }
+ }
+
+ @Override
+ boolean sheetExists(String sheetId) {
+// logger.debug("sheetExists("+sheetId+")");
+ ArrayList<WorkbookWrapper> v = sheets.get(sheetId);
+ return (v!=null);
+ }
+
+ @Override
+ int getLastLineLastSheet(String sheetId) {
+ WorkbookWrapper ww = getLastWorkbookWrapper(sheetId);
+ WritableSheet ws = ww.workbook.getSheet(0);
+ return (ws.getRows() < 2 ? 2 : ws.getRows());
+ }
+
+ @Override
+ void mergeCells(String sheetId, int col1, int row1, int col2, int row2) {
+ // on ne fait rien !
+ }
+
+ @Override
+ void writeCell(String sheetId, Object o, int line, int col, boolean bypassLineRenum) throws Exception {
+ int newline = 0;
+ if (bypassLineRenum) {
+ newline = line;
+ } else {
+ int _ligne = exporter.getLastLine(sheetId);
+ if (_ligne >= (MAX_ROWS_PER_SHEET * sheets.get(sheetId).size())) {
+ splitSheet(sheetId);
+ }
+
+ // renumérotation de la ligne
+ newline = _ligne;
+ newline = _ligne % (MAX_ROWS_PER_SHEET) + 2;
+ }
+
+ WorkbookWrapper ww = getLastWorkbookWrapper(sheetId);
+ WritableSheet sheet = ww.workbook.getSheet(0);
+
+ if (o instanceof java.lang.Integer) {
+ WritableCellFormat integerFormat = ww.intFormats[newline == 0 ? 0 : newline == 1 ? 1 : 2];
+ jxl.write.Number number = new jxl.write.Number(col, newline, (Integer) o, integerFormat);
+ sheet.addCell(number);
+ } else if (o instanceof java.lang.Float) {
+ WritableCellFormat floatFormat = ww.floatFormats[newline == 0 ? 0 : newline == 1 ? 1 : 2];
+ jxl.write.Number number = new jxl.write.Number(col, newline, (Float) o, floatFormat);
+ sheet.addCell(number);
+ } else if (o instanceof java.util.Date) {
+ WritableCellFormat dateFormat = ww.dateFormats[newline == 0 ? 0 : newline == 1 ? 1 : 2];
+ jxl.write.DateTime date = new jxl.write.DateTime(col, newline, (Date) o, dateFormat);
+ sheet.addCell(date);
+ } else if (o instanceof Amount) {
+ WritableCellFormat floatFormat = ww.floatFormats[newline == 0 ? 0 : newline == 1 ? 1 : 2];
+ jxl.write.Number number = new jxl.write.Number(col, newline, ((Amount) o).doubleValue(), floatFormat);
+ sheet.addCell(number);
+ } else {
+ WritableCellFormat format = ww.lblFormats[newline == 0 ? 0 : newline == 1 ? 1 : 2];
+ jxl.write.Label label = new jxl.write.Label(col, newline, (String) o, format);
+ sheet.addCell(label);
+ }
+ }
+
+ @Override
+ void flushLine(String el) {
+// logger.debug("flushLine("+el+")");
+ }
+
+ /**
+ * Récupére la derniere feuille correspondant a
+ * l'objet de nom id (c'est celle en cours d'edition)
+ */
+ private WorkbookWrapper getLastWorkbookWrapper(String sheetId) {
+ ArrayList<WorkbookWrapper> v = sheets.get(sheetId);
+ if (v != null) {
+ return v.get(v.size() - 1);
+ } else {
+ return null;
+ }
+ }
+ /**
+ * creee une nouvelle feuille de nom id suivi d'un _ et d'un numero d'ordre
+ * appelle lorsque la feuille
+ * precedente de meme nom "deborde"
+ */
+ protected WritableSheet splitSheet(String id) throws Exception {
+ ArrayList<WorkbookWrapper> v = sheets.get(id);
+ WorkbookWrapper ww = v.get(v.size()-1);
+
+
+ WritableSheet wsRef = ww.workbook.getSheet(0);
+ String sheetName = wsRef.getName();
+ String fileName = baseFileName+"-"+sheetName+"-"+(v.size()+1)+".xls";
+ logger.debug("splitting sheet and produces "+fileName);
+ File sheetFile = new File(baseFile.getAbsoluteFile().getParentFile(), fileName);
+ WritableWorkbook sheet = Workbook.createWorkbook(sheetFile, settings);
+ sheet.createSheet(sheetName, 0);
+ WorkbookWrapper newWw = new WorkbookWrapper(sheet, sheetFile, ww.eem);
+ v.add(newWw);
+ WritableSheet ws = sheet.createSheet(sheetName, 0);
+ for (int i = 0; i < 2; i++) {
+ for (int j = 0; j < wsRef.getColumns(); j++) {
+ WritableCell readCell = (WritableCell) wsRef.getCell(j, i);
+ WritableCell newCell = readCell.copyTo(j, i);
+ CellFormat readFormat = readCell.getCellFormat();
+ if(readFormat!=null)
+ newCell.setCellFormat(new WritableCellFormat(readFormat));
+ ws.addCell(newCell);
+ }
+ }
+ // on peut le fermer la dernière feuille tout de suite, ça liberera de la mémoire
+ try {
+ ww.purge();
+ } catch(Exception ex) {
+ logger.error("closing not-last sheet", ex);
+ }
+ return ws;
+ }
+
+
+ private class WorkbookWrapper {
+ private WritableWorkbook workbook;
+ private File file;
+ private ExportElementModel eem;
+ private WritableCellFormat[] dateFormats = null;
+ private WritableCellFormat[] intFormats = null;
+ private WritableCellFormat[] floatFormats = null;
+ private WritableCellFormat[] lblFormats = null;
+
+ public WorkbookWrapper(WritableWorkbook workbook, File file, ExportElementModel eem) {
+ this.workbook = workbook;
+ this.file = file;
+ this.eem = eem;
+ initFormats();
+ }
+ public void purge() throws Exception {
+ if(workbook!=null) {
+ CellView cv = new CellView();
+ cv.setSize(18*20);
+ workbook.getSheet(0).setRowView(0, cv);
+ workbook.write();
+ workbook.close();
+ workbook = null;
+ }
+ dateFormats =null;
+ intFormats = null;
+ floatFormats = null;
+ lblFormats = null;
+ }
+ private void initFormats() {
+ WritableFont fontEntete1 = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD, false);
+ WritableFont fontEntete2 = new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD, false);
+ WritableFont fontAutre = new WritableFont(WritableFont.ARIAL, 10);
+ dateFormats = new WritableCellFormat[3];
+ String dateFmt = exporter.getApplicationConfiguration().getProperty(Constants.SYS_PROP_DATE_FORMAT);
+ if(dateFmt==null)
+ dateFmt = "dd/MM/yyyy";
+ DateFormat myDateFormat = new DateFormat(dateFmt);
+ dateFormats[0] = new WritableCellFormat(fontEntete1, myDateFormat);
+ dateFormats[1] = new WritableCellFormat(fontEntete2, myDateFormat);
+ dateFormats[2] = new WritableCellFormat(fontAutre, myDateFormat);
+
+ intFormats = new WritableCellFormat[3];
+ intFormats[0] = new WritableCellFormat(fontEntete1, NumberFormats.INTEGER);
+ intFormats[1] = new WritableCellFormat(fontEntete2, NumberFormats.INTEGER);
+ intFormats[2] = new WritableCellFormat(fontAutre, NumberFormats.INTEGER);
+
+ floatFormats = new WritableCellFormat[3];
+ floatFormats[0] = new WritableCellFormat(fontEntete1, NumberFormats.FLOAT);
+ floatFormats[1] = new WritableCellFormat(fontEntete2, NumberFormats.FLOAT);
+ floatFormats[2] = new WritableCellFormat(fontAutre, NumberFormats.FLOAT);
+
+ lblFormats = new WritableCellFormat[3];
+ lblFormats[0] = new WritableCellFormat(fontEntete1);
+ lblFormats[1] = new WritableCellFormat(fontEntete2);
+ lblFormats[2] = new WritableCellFormat(fontAutre);
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2008 axYus - www.axyus.com
+ * 2008 L. Meckert - laurent.meckert@axyus.com
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.export;
+
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import java.util.Hashtable;
+import java.util.Vector;
+import java.util.Enumeration;
+
+import fr.gouv.finances.dgfip.utils.Amount;
+import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
+import fr.gouv.finances.dgfip.utils.StringUtilities;
+import fr.gouv.finances.dgfip.xemelios.utils.HtmlTableWriter;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+
+import fr.gouv.finances.dgfip.xemelios.export.ExportElementModel;
+import java.io.IOException;
+import java.io.FileWriter;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.nio.channels.FileChannel;
+import java.text.DecimalFormat;
+import java.text.NumberFormat;
+import java.text.SimpleDateFormat;
+import org.apache.log4j.Logger;
+
+/**
+ * Cette classe exporte au format HTML
+ * @author cmarchand
+ */
+public class HtmlTableExporter extends ExportUndertaker {
+
+ private static final Logger logger = Logger.getLogger(HtmlTableExporter.class);
+ private static final int MAX_ROWS_PER_SHEET = 65000;// 65000 ; // test 30
+ // contiendra la liste des sheets XLS, dans l'ordre devant être créé (par ex : SHEET_Bordereau, SHEET_Titre, SHEET_Ligne)
+ private Hashtable<String, Vector<HtmlSheet>> sheets = new Hashtable<String, Vector<HtmlSheet>>();
+ private Exporter caller;
+ private String workbookPrefix = null;
+ protected SimpleDateFormat sdf;
+ DecimalFormat df = null;
+ private PropertiesExpansion applicationProperties;
+
+ public HtmlTableExporter(Exporter caller, PropertiesExpansion applicationProperties) {
+ this.caller = caller;
+ this.applicationProperties = applicationProperties;
+ String dateFormat = applicationProperties.getProperty("xemelios.date.format");
+ if(dateFormat==null) dateFormat = "dd/MM/yyyy";
+ sdf = new SimpleDateFormat(dateFormat);
+ df = new DecimalFormat("0.00");
+ df.getDecimalFormatSymbols().setDecimalSeparator(',');
+ df.setGroupingUsed(false);
+ }
+
+ protected String getModelFileName() {
+ return "/modeleExportXemelios.xls";
+ }
+
+ // Fonctions appellees par Exporter.java
+ /**
+ * Initialisation
+ */
+ @Override
+ void initialize() throws Exception {
+ // Pour que l'appelant soit content je copie un modele vide
+ String dirRessources = applicationProperties.getProperty(Constants.SYS_PROP_RESOURCES_LOCATION);
+ recopieFichier(dirRessources + getModelFileName(), caller.fDest.getPath(), true);
+ workbookPrefix = StringUtilities.removeFileNameSuffix(caller.fDest.getPath());
+ }
+
+ void recopieFichier(String src, String dst, boolean overwrite) {
+ FileChannel in = null; // canal d'entrée
+ FileChannel out = null; // canal de sortie
+
+ try {
+ // Init
+ in = new FileInputStream(src).getChannel();
+ out = new FileOutputStream(dst).getChannel();
+
+ // Copie depuis le in vers le out
+ in.transferTo(0, in.size(), out);
+ } catch (Exception e) {
+ e.printStackTrace(); // n'importe quelle exception
+ } finally { // finalement on ferme
+ if (in != null) {
+ try {
+ in.close();
+ } catch (IOException e) {
+ }
+ }
+ if (out != null) {
+ try {
+ out.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+ }
+
+ /**
+ * Obsolete
+ */
+ void addRefInMainSheet(String libelle, boolean addPrefix) {
+ String fileName;
+ if (addPrefix) {
+ fileName = workbookPrefix + "_" + libelle + ".xls";
+ } else {
+ fileName = libelle + ".xls";
+ }
+
+ String href = "<A HREF=\"file:///" + fileName + "\">" + libelle + "</A>";
+ }
+
+ /**
+ * Crée un <tt>HtmlSheet</tt> et ajoute la liste des entetes de colonne
+ * @param eem
+ * @throws Exception
+ */
+ @Override
+ void buildSheet(ExportElementModel eem) throws Exception {
+ logger.debug("buildSheet(" + eem + ")");
+ Vector<HtmlSheet> v = sheets.get(eem.getId());
+ if (v == null) {
+ v = new Vector<HtmlSheet>();
+ sheets.put(eem.getId(), v);
+ }
+
+ String fileName = eem.getId() + "-" + eem.getLibelle(); // + ".xls";
+ fileName = StringUtilities.toAscii(fileName, "_").replaceAll(" ", "_");
+ if(fileName.length()>=31) {
+ fileName = fileName.substring(0, 30);
+ if(fileName.endsWith(".")) fileName = fileName.substring(0, fileName.length()-1);
+ }
+logger.debug("fname="+fileName);
+ HtmlSheet sheet = new HtmlSheet(applicationProperties);
+ sheet.open(workbookPrefix + "_" + fileName);
+
+ addRefInMainSheet(workbookPrefix + "_" + fileName, true);
+ v.add(sheet);
+
+ for (ExportElementModel e : eem.getEnfants()) {
+ buildSheet(e);
+ }
+ caller.firstSheetId = eem.getId();
+ }
+
+ /**
+ * Apporte des finitions
+ */
+ @Override
+ void finish() throws Exception {
+ // pour l'instant rien
+ }
+
+ /**
+ * Fermeture et nettoyage
+ */
+ @Override
+ void close() {
+ Enumeration elems = sheets.keys();
+ while (elems.hasMoreElements()) {
+ String k = (String) elems.nextElement();
+ Vector<HtmlSheet> v = sheets.get(k);
+ for (HtmlSheet s : v) {
+
+ s.close();
+ }
+
+ }
+ }
+
+ /**
+ * Verifie l'existence d'unr feuille dans le classeur
+ * @param sheetId le nom de la feuille
+ */
+ @Override
+ boolean sheetExists(String sheetId) {
+ Vector<HtmlSheet> v = sheets.get(sheetId);
+ if (v != null) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * renvoie le dernier numero de ligne utilisee dans la derniere feuille de nom sheetId
+ */
+ @Override
+ int getLastLineLastSheet(String sheetId) {
+ // suppose qu'on a appele sheetExists(sheetId)
+ HtmlSheet ws = getLastSheet(sheetId);
+ return (ws.getRows() < 2 ? 2 : ws.getRows());
+ }
+
+ /**
+ * Remplit une cellule avec la valeur correctement formatée.
+ * @param sheet
+ * @param o
+ * @param ligne
+ * @param col
+ * @throws WriteException
+ */
+ @Override
+ void writeCell(String sheetId, Object o, int line, int col, boolean bypassLineRenum) throws Exception {
+
+ int newline = 0;
+ if (bypassLineRenum) {
+ newline = line;
+ } else {
+ int _ligne = caller.getLastLine(sheetId);
+ if (_ligne >= (MAX_ROWS_PER_SHEET * sheets.get(sheetId).size())) {
+ splitSheet(sheetId);
+ }
+
+ // renumérotation de la ligne
+ newline = _ligne;
+ newline = _ligne % (MAX_ROWS_PER_SHEET) + 2;
+ }
+
+ HtmlSheet sheet = getLastSheet(sheetId);
+ String s = formatted(o, line);
+ // Si line = 0 = c'est un titre
+ if (line == 0) {
+ sheet.addTitle(s, col);
+ } else if (line == 1) {
+ // Si line = 1 = c'est un nom de champ
+ sheet.addName(s, col);
+ } else {
+ // sinon c'est une ligne normale
+ sheet.addEntry(s, col);
+ }
+
+
+ }
+
+ /**
+ * reunit des cellules dans la derniere des feuilles de nom sheetId
+ * @param sheetId = nom de la feuille
+ * @param col1 = colonne de depart
+ * @param row1 = ligne de depart
+ * @param col2 = colonne d'arrivee
+ * @param row2= ligne d'arrivee
+ */
+ @Override
+ void mergeCells(String sheetId, int col1, int row1, int col2, int row2) {
+ HtmlSheet _ws = getLastSheet(sheetId);
+ _ws.mergeCells(col1, row1, col2, row2);
+ }
+
+ @Override
+ void flushLine(String sheetId) {
+ HtmlSheet _ws = getLastSheet(sheetId);
+ _ws.flushLine();
+ }
+
+ // Fonctions a usage interne mises en protected on sait jamais
+ /**
+ * Formatage de l'objet a ecrire
+ */
+ protected String formatted(Object o, Integer line) {
+
+ // Reconnaitre selon le type
+ String rawStr;
+ Integer styleId;
+ Integer level = 3;
+ if (o instanceof java.lang.Integer) {
+ rawStr = ((Integer) o).toString();
+ styleId = HtmlTableWriter.INTEGER_CELLFORMAT;
+ } else if (o instanceof java.lang.Float) {
+ // changement du point en virgule
+ rawStr = df.format((Float) o);
+ styleId = HtmlTableWriter.FLOAT_CELLFORMAT;
+ } else if (o instanceof java.util.Date) {
+ rawStr = sdf.format(o);
+ styleId = HtmlTableWriter.DATE_CELLFORMAT;
+ } else if (o instanceof Amount) {
+ Double d = new Double(((Amount) o).doubleValue());
+ // changement du point en virgule
+ rawStr = df.format(d);
+ styleId = HtmlTableWriter.FLOAT_CELLFORMAT;
+ } else if (o instanceof java.lang.String) {
+ rawStr = (String) o;
+ styleId = HtmlTableWriter.TEXT_CELLFORMAT;
+ } else {
+ rawStr = (String) o;
+ styleId = -1;
+ }
+
+ // mettre en gras les titres
+ if (line == 0) {
+ level = 1;
+ }
+ if (line == 1) {
+ level = 2;
+ }
+ return HtmlTableWriter.buildCell(rawStr, styleId, level);
+ }
+
+ /**
+ * Numero d'ordre suivant celui de la feuille de nom id
+ */
+ protected int afterSheet(String id) {
+ return 1;
+ }
+
+ /**
+ * Récupére la derniere feuille correspondant a
+ * l'objet de nom id (c'est celle en cours d'edition)
+ */
+ protected HtmlSheet getLastSheet(String sheetId) {
+ Vector<HtmlSheet> v = sheets.get(sheetId);
+ if (v != null) {
+ return v.get(v.size() - 1);
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Récupére la premiere feuille correspondant au premier parent de
+ * l'objet de nom id
+ */
+ protected HtmlSheet getRootSheetBefore(String id) {
+ HtmlSheet ret = null;
+ ElementModel e = caller.getEMFromId(id);
+ if (e.getSimpleParent() != null) {
+ String pName = e.getSimpleParent().getElement();
+ ret = sheets.get(pName).get(0);
+ }
+ return ret;
+ }
+
+ /**
+ * creee une nouvelle feuille de nom id suivi d'un _ er d'un numero d'ordre
+ * appelle lorsque la feuille
+ * precedente de meme nom "deborde"
+ */
+ protected HtmlSheet splitSheet(String id) {
+ Vector<HtmlSheet> v = sheets.get(id);
+ HtmlSheet wsRef = v.get(0);
+ HtmlSheet otherRef = getLastSheet(id);
+ wsRef.close();
+ HtmlSheet ws = new HtmlSheet(applicationProperties);
+ NumberFormat nf = NumberFormat.getInstance(); // Get Instance of NumberFormat
+ nf.setMinimumIntegerDigits(2); // The minimum Digits required is 5
+ nf.setMaximumIntegerDigits(3); // The maximum Digits required is 5
+ String sb = (nf.format((long) v.size()));
+ String fname = wsRef.getName() + "_" + sb;
+ if(fname.length()>=31) fname = fname.substring(fname.length()-30);
+ ws.open(fname);
+ addRefInMainSheet(fname, false);
+ ws.titles = wsRef.titles;
+ ws.names = wsRef.names;
+ ws.maxTitle = wsRef.maxTitle;
+ ws.maxName = wsRef.maxName;
+ ws.flushTitles();
+ ws.flushNames();
+ v.add(ws);
+ return ws;
+ }
+
+ protected class HtmlSheet {
+ String name; // nom de la "feuille"
+ HtmlTableWriter writer; // objet consituant les lignes et les ecrivant dans le fichier
+ String[] titles; // pour noter la ligne de titre
+ String[] names; // pour noter la ligne de noms de champs
+ String[] entries; // pour noter la ligne en cours
+ int curTitle;
+ int curName;
+ int curEntry;
+ int maxTitle;
+ int maxName;
+ int maxEntry;
+ int colCount;
+ int rowCount;
+ boolean titlesFlushed;
+ boolean namesFlushed;
+
+ private PropertiesExpansion applicationProperties;
+
+ public HtmlSheet(PropertiesExpansion applicationProperties) {
+ this.applicationProperties = applicationProperties;
+ }
+
+ void open(String fname) {
+ try {
+ FileWriter out = new FileWriter(fname + ".xls");
+ writer = new HtmlTableWriter(out, fname, applicationProperties);
+ } catch (IOException e) {
+ logger.error("HtmlSheet.open(" + fname + ")", e);
+ }
+ // Version initial tableau surdimensionnnes hum=
+ name = fname;
+ titles = new String[100];
+ names = new String[100];
+ entries = new String[100];
+ maxTitle = 0;
+ maxName = 0;
+ maxEntry = 0;
+ rowCount = 0;
+ titlesFlushed = false;
+ namesFlushed = false;
+ }
+
+ void close() {
+ if (writer != null) {
+ try {
+ writer.close();
+
+ } catch (IOException e) {
+ logger.error("HtmlSheet.close()", e);
+ }
+ writer = null;
+ }
+ }
+
+ String getName() {
+ return name;
+ }
+
+ int getRows() {
+ return rowCount;
+ }
+
+ void addTitle(String s, int col) {
+ if (!titlesFlushed) {
+ if (col >= titles.length || maxTitle >= titles.length) {
+ // cas ou il faut redimensionner
+ int oldlength = titles.length;
+ int newlength = oldlength + oldlength / 2;
+ String[] tm = new String[newlength];
+ for (int i = 0; i < oldlength; ++i) {
+ tm[i] = titles[i];
+ }
+ titles = tm;
+ }
+ while (maxTitle + 1 < col) {
+ maxTitle++;
+ titles[maxTitle] = formatted("", 0); // pour simuler la presentation en Excel pur
+
+ }
+ titles[col] = s;
+ if (col > maxTitle) {
+ maxTitle = col;
+ }
+
+ }
+ }
+
+ void addName(String s, int col) {
+ if (!namesFlushed) {
+ if (col >= names.length || maxName >= names.length) {
+ // cas ou il faut redimensionner
+ int oldlength = names.length;
+ int newlength = oldlength + oldlength / 2;
+ String[] tm = new String[newlength];
+ for (int i = 0; i < oldlength; ++i) {
+ tm[i] = names[i];
+ }
+ names = tm;
+ }
+ while (maxName + 1 < col) {
+ maxName++;
+ names[maxName] = formatted("", 1);
+ }
+ names[col] = s;
+ if (col > maxName) {
+ maxName = col;
+ }
+
+ }
+ }
+
+ void addEntry(String s, int col) {
+ if (col >= entries.length || maxEntry >= entries.length) {
+ // cas ou il faut redimensionner
+ int oldlength = entries.length;
+ int newlength = oldlength + oldlength / 2;
+ String[] tm = new String[newlength];
+ for (int i = 0; i < oldlength; ++i) {
+ tm[i] = entries[i];
+ }
+ entries = tm;
+ }
+ while (maxEntry + 1 < col) {
+ maxEntry++;
+ entries[maxEntry] = formatted("", 999);
+ }
+ entries[col] = s;
+ if (col > maxEntry) {
+ maxEntry = col;
+ }
+ }
+
+ void mergeCells(int col1, int row1, int col2, int row2) { }
+
+ void flushTitles() {
+ writer.writeNext(titles, maxTitle);
+ titlesFlushed = true;
+ ++rowCount;
+ }
+
+ void flushNames() {
+ writer.writeNext(names, maxName);
+ namesFlushed = true;
+ ++rowCount;
+ }
+
+ void flushLine() {
+ if (!titlesFlushed) {
+ flushTitles();
+ }
+ if (!namesFlushed) {
+ flushNames();
+ }
+
+ writer.writeNext(entries, maxEntry);
+ maxEntry = 0;
+ ++rowCount;
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2008 axYus - www.axyus.com
+ * 2008 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+
+package fr.gouv.finances.cp.xemelios.export;
+
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import fr.gouv.finances.dgfip.utils.Amount;
+import fr.gouv.finances.dgfip.xemelios.utils.HtmlTableWriter;
+import java.text.DecimalFormat;
+import java.text.DecimalFormatSymbols;
+
+/**
+ *
+ * @author chm
+ */
+public class HtmlTableExporterXls97SR1 extends HtmlTableExporter {
+ private static DecimalFormat decF = new DecimalFormat("0.00");
+ static {
+ DecimalFormatSymbols dfs = decF.getDecimalFormatSymbols();
+ dfs.setDecimalSeparator(',');
+ decF.setDecimalFormatSymbols(dfs);
+ decF.setGroupingUsed(false);
+ }
+
+ public HtmlTableExporterXls97SR1(Exporter exporter, PropertiesExpansion applicationProperties) {
+ super(exporter, applicationProperties);
+ }
+
+ @Override
+ protected String getModelFileName() {
+ return "/modeleExportXemelios-97SR1.xls";
+ }
+ /**
+ * Formatage de l'objet a ecrire
+ */
+ @Override
+ protected String formatted(Object o, Integer line) {
+
+ // Reconnaitre seleon me type
+ String rawStr;
+ Integer styleId;
+ Integer level = 3;
+ if (o instanceof java.lang.Integer) {
+ rawStr = ((Integer) o).toString();
+ styleId = HtmlTableWriter.INTEGER_CELLFORMAT;
+ } else if (o instanceof java.lang.Float) {
+ //rawStr = ((Float) o).toString();
+ rawStr = decF.format(((Float)o).floatValue());
+ styleId = HtmlTableWriter.FLOAT_CELLFORMAT;
+ } else if (o instanceof java.util.Date) {
+ rawStr = sdf.format(o);
+ styleId = HtmlTableWriter.DATE_CELLFORMAT;
+ } else if (o instanceof Amount) {
+// Double d = new Double(((Amount) o).doubleValue());
+ rawStr = decF.format(((Amount)o).doubleValue());
+ styleId = HtmlTableWriter.FLOAT_CELLFORMAT;
+ } else if (o instanceof java.lang.String) {
+ rawStr = (String) o;
+ styleId = HtmlTableWriter.TEXT_CELLFORMAT;
+ } else {
+ rawStr = o!=null ? o.toString() : "";
+ styleId = -1;
+ }
+
+ // mettre en gras les titres
+ if (line == 0) {
+ level = 1;
+ }
+ if (line == 1) {
+ level = 2;
+ }
+ return HtmlTableWriter.buildCell(rawStr, styleId, level);
+ }
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2008 axYus - www.axyus.com
+ * 2007 N.Le Corre - nicolas.lecorre@axyus.com
+ * 2008 L. Meckert - laurent.meckert@axyus.com
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.export;
+
+import java.io.File;
+import java.util.Date;
+import java.util.Hashtable;
+import java.util.Vector;
+
+
+import jxl.Workbook;
+import jxl.WorkbookSettings;
+import jxl.format.CellFormat;
+import jxl.write.DateFormat;
+import jxl.write.NumberFormats;
+import jxl.write.WritableCell;
+import jxl.write.WritableCellFormat;
+import jxl.write.WritableFont;
+import jxl.write.WritableSheet;
+import jxl.write.WritableWorkbook;
+import jxl.write.WriteException;
+import jxl.write.biff.RowsExceededException;
+
+import fr.gouv.finances.dgfip.utils.Amount;
+import fr.gouv.finances.dgfip.utils.StringUtilities;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
+import fr.gouv.finances.dgfip.xemelios.export.ExportElementModel;
+import org.apache.log4j.Logger;
+
+/**
+ * 2010-02-18 : reutilisation des WritableCellFormat car on est limité dans leur utilisation
+ * @author N.Le Corre
+ */
+public class JxlExporter extends ExportUndertaker {
+
+ private static final Logger logger = Logger.getLogger(JxlExporter.class);
+ private static final int MAX_ROWS_PER_SHEET = 65000; // test 30;
+ // formattage des colonnes d'entête
+ WritableFont fontEntete1 = new WritableFont(WritableFont.TIMES, 16, WritableFont.BOLD, false);
+ WritableFont fontEntete2 = new WritableFont(WritableFont.TIMES, 12, WritableFont.BOLD, false);
+ WritableFont fontAutre = new WritableFont(WritableFont.TIMES, 10);
+ // contiendra la liste des sheets XLS, dans l'ordre devant être créé (par ex : SHEET_Bordereau, SHEET_Titre, SHEET_Ligne)
+ private Hashtable<String, Vector<WritableSheet>> sheets = new Hashtable<String, Vector<WritableSheet>>();
+ private Exporter caller;
+ private WritableWorkbook workbook = null;
+
+ WritableCellFormat[] dateFormats = null;
+ WritableCellFormat[] intFormats = null;
+ WritableCellFormat[] floatFormats = null;
+ WritableCellFormat[] lblFormats = null;
+
+ public JxlExporter(Exporter caller) {
+ this.caller = caller;
+ dateFormats = new WritableCellFormat[3];
+ DateFormat myDateFormat = new DateFormat(caller.getApplicationConfiguration().getProperty(Constants.SYS_PROP_DATE_FORMAT));
+ dateFormats[0] = new WritableCellFormat(fontEntete1, myDateFormat);
+ dateFormats[1] = new WritableCellFormat(fontEntete2, myDateFormat);
+ dateFormats[2] = new WritableCellFormat(fontAutre, myDateFormat);
+
+ intFormats = new WritableCellFormat[3];
+ intFormats[0] = new WritableCellFormat(fontEntete1, NumberFormats.INTEGER);
+ intFormats[1] = new WritableCellFormat(fontEntete2, NumberFormats.INTEGER);
+ intFormats[2] = new WritableCellFormat(fontAutre, NumberFormats.INTEGER);
+
+ floatFormats = new WritableCellFormat[3];
+ floatFormats[0] = new WritableCellFormat(fontEntete1, NumberFormats.FLOAT);
+ floatFormats[1] = new WritableCellFormat(fontEntete2, NumberFormats.FLOAT);
+ floatFormats[2] = new WritableCellFormat(fontAutre, NumberFormats.FLOAT);
+
+ lblFormats = new WritableCellFormat[3];
+ lblFormats[0] = new WritableCellFormat(fontEntete1);
+ lblFormats[1] = new WritableCellFormat(fontEntete2);
+ lblFormats[2] = new WritableCellFormat(fontAutre);
+
+ }
+
+ // Fonctions appellees par Exporter.java
+ /**
+ * Initialisation
+ */
+ @Override
+ void initialize() throws Exception {
+
+ /**
+ * Création du workbook
+ * sur le fichier fDest
+ */
+ WorkbookSettings ws = new WorkbookSettings();
+ ws.setUseTemporaryFileDuringWrite(true);
+ ws.setTemporaryFileDuringWriteDirectory(new File("."));
+ ws.setCellValidationDisabled(true);
+ ws.setGCDisabled(false);
+ workbook = Workbook.createWorkbook(caller.fDest, ws);
+ }
+
+ /**
+ * Crée un <tt>WritableSheet</tt> et ajoute la liste des entetes de colonne
+ * @param eem
+ * @throws Exception
+ */
+ @Override
+ void buildSheet(ExportElementModel eem) throws Exception {
+
+ Vector<WritableSheet> v = sheets.get(eem.getId());
+ if (v == null) {
+ v = new Vector<WritableSheet>();
+ }
+ sheets.put(eem.getId(), v);
+ String sheetName = StringUtilities.toAscii(eem.getLibelle(),"_");
+ if(sheetName.length()>=31) {
+ sheetName = sheetName.substring(sheetName.length()-30);
+ if(sheetName.endsWith(".")) sheetName = sheetName.substring(0, sheetName.length()-1);
+ }
+// v.add(workbook.createSheet(eem.getLibelle(), workbook.getNumberOfSheets()));
+ v.add(workbook.createSheet(sheetName, workbook.getNumberOfSheets()));
+
+ for (ExportElementModel e : eem.getEnfants()) {
+ buildSheet(e);
+ }
+ caller.firstSheetId = eem.getId();
+ }
+
+ /**
+ * Apporte des finitions
+ */
+ @Override
+ void finish() throws Exception {
+ // recopie des entêtes dans les nouvelles feuilles créées
+ enteteNewSheets();
+ }
+
+ /**
+ * Fermeture et nettoyage
+ */
+ @Override
+ void close() {
+ if (workbook != null) {
+ try {
+ workbook.write();
+ workbook.close();
+ workbook = null;
+ } catch (Throwable t) {
+ }
+ }
+ }
+
+ /**
+ * Verifie l'existence d'unr feuille dans le classeur
+ * @param sheetId le nom de la feuille
+ */
+ @Override
+ boolean sheetExists(String sheetId) {
+ Vector<WritableSheet> v = sheets.get(sheetId);
+ if (v != null) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * renvoie le dernier numero de ligne utilisee dans la derniere feuille de nom sheetId
+ */
+ @Override
+ int getLastLineLastSheet(String sheetId) {
+ // suppose qu'on a appele sheetExists(sheetId)
+ WritableSheet ws = getLastSheet(sheetId);
+ return (ws.getRows() < 2 ? 2 : ws.getRows());
+
+ }
+
+ /**
+ * Remplit une cellule avec la valeur correctement formatée.
+ * @param sheet
+ * @param o
+ * @param ligne
+ * @param col
+ * @throws WriteException
+ */
+ @Override
+ void writeCell(String sheetId, Object o, int line, int col, boolean bypassLineRenum) throws Exception {
+ int newline = 0;
+ if (bypassLineRenum) {
+ newline = line;
+ } else {
+ int _ligne = caller.getLastLine(sheetId);
+ if (_ligne >= (MAX_ROWS_PER_SHEET * sheets.get(sheetId).size())) {
+ splitSheet(sheetId);
+ }
+
+ // renumérotation de la ligne
+ newline = _ligne;
+ newline = _ligne % (MAX_ROWS_PER_SHEET) + 2;
+ }
+
+ WritableSheet sheet = getLastSheet(sheetId);
+
+ if (o instanceof java.lang.Integer) {
+ WritableCellFormat integerFormat = intFormats[newline == 0 ? 0 : newline == 1 ? 1 : 2];
+ jxl.write.Number number = new jxl.write.Number(col, newline, (Integer) o, integerFormat);
+ sheet.addCell(number);
+ } else if (o instanceof java.lang.Float) {
+ WritableCellFormat floatFormat = floatFormats[newline == 0 ? 0 : newline == 1 ? 1 : 2];
+ jxl.write.Number number = new jxl.write.Number(col, newline, (Float) o, floatFormat);
+ sheet.addCell(number);
+ } else if (o instanceof java.util.Date) {
+ WritableCellFormat dateFormat = dateFormats[newline == 0 ? 0 : newline == 1 ? 1 : 2];
+ jxl.write.DateTime date = new jxl.write.DateTime(col, newline, (Date) o, dateFormat);
+ sheet.addCell(date);
+ } else if (o instanceof Amount) {
+ WritableCellFormat floatFormat = floatFormats[newline == 0 ? 0 : newline == 1 ? 1 : 2];
+ jxl.write.Number number = new jxl.write.Number(col, newline, ((Amount) o).doubleValue(), floatFormat);
+ sheet.addCell(number);
+ } else {
+// if (o != null) {
+// logger.debug(sheetId + " -> " + o.getClass().getName());
+// } else {
+// logger.debug("writting null data");
+// }
+ WritableCellFormat format = lblFormats[newline == 0 ? 0 : newline == 1 ? 1 : 2];
+ jxl.write.Label label = new jxl.write.Label(col, newline, (String) o, format);
+ sheet.addCell(label);
+ }
+ }
+
+ /**
+ * reunit des cellules dans la derniere des feuilles de nom sheetId
+ * @param sheetId = nom de la feuille
+ * @param col1 = colonne de depart
+ * @param row1 = ligne de depart
+ * @param col2 = colonne d'arrivee
+ * @param row2= ligne d'arrivee
+ */
+ @Override
+ void mergeCells(String sheetId, int col1, int row1, int col2, int row2) {
+ WritableSheet _ws = getLastSheet(sheetId);
+
+ try {
+// _ws.mergeCells(col1, row1, col2, row2);
+ } catch (Exception e) {
+ }
+
+ }
+
+ // Fonctions a usage interne mises en protected on sait jamais
+ /**
+ * Numero d'ordre suivant celui de la feuille de nom id
+ */
+ protected int afterSheet(String id) {
+ String[] names = workbook.getSheetNames();
+ for (int i = 1; i < names.length; i++) {
+ if (names[i].equals(id)) {
+ return i + 1;
+ }
+ }
+ return 1;
+ }
+
+ /**
+ * Récupére la derniere feuille correspondant a
+ * l'objet de nom id (c'est celle en cours d'edition)
+ */
+ protected WritableSheet getLastSheet(String sheetId) {
+ Vector<WritableSheet> v = sheets.get(sheetId);
+ if (v != null) {
+ return v.get(v.size() - 1);
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Récupére la premiere feuille correspondant au premier parent de
+ * l'objet de nom id
+ */
+ protected WritableSheet getRootSheetBefore(String id) {
+ WritableSheet ret = null;
+ ElementModel e = caller.getEMFromId(id);
+ if (e.getSimpleParent() != null) {
+ String pName = e.getSimpleParent().getElement();
+ ret = sheets.get(pName).get(0);
+ }
+ return ret;
+ }
+
+ /**
+ * creee une nouvelle feuille de nom id suivi d'un _ er d'un numero d'ordre
+ * appelle lorsque la feuille
+ * precedente de meme nom "deborde"
+ */
+ protected WritableSheet splitSheet(String id) {
+ Vector<WritableSheet> v = sheets.get(id);
+ WritableSheet wsRef = v.get(0);
+
+ WritableSheet ws = workbook.createSheet(wsRef.getName() + "_" + (v.size()), afterSheet(v.get(v.size() - 1).getName()));
+ v.add(ws);
+ return workbook.getSheet(workbook.getNumberOfSheets() - 1);
+ }
+
+ /**
+ * Appelee en fin d'execution, retourne sur les feuilles suppelemetaires
+ * creees pas splitSheet
+ * pour leur copier la ligne de titre de la premiere de leur serie
+ */
+ private void enteteNewSheets() throws RowsExceededException, WriteException {
+ for (Vector<WritableSheet> v : sheets.values()) {
+ if (v.size() > 1) {
+ WritableSheet wsRef = v.get(0);
+ for (int iv = 1; iv < v.size(); iv++) {
+ WritableSheet ws = v.get(iv);
+ for (int i = 0; i < 2; i++) {
+ for (int j = 0; j < wsRef.getColumns(); j++) {
+ WritableCell readCell = (WritableCell) wsRef.getCell(j, i);
+ WritableCell newCell = readCell.copyTo(j, i);
+ CellFormat readFormat = readCell.getCellFormat();
+ if (readFormat != null) {
+ WritableCellFormat newFormat = new WritableCellFormat(readFormat);
+ newCell.setCellFormat(newFormat);
+ }
+ ws.addCell(newCell);
+ }
+ }
+
+ }
+ }
+ }
+ }
+
+ @Override
+ void flushLine(String el) {
+ // NOP
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2008 axYus - www.axyus.com
+ * 2008 C.Marchand - christophe.marchand@axyus.com
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.export;
+
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import fr.gouv.finances.dgfip.utils.StringUtilities;
+import fr.gouv.finances.dgfip.xemelios.export.ExportElementModel;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.Writer;
+import java.nio.channels.FileChannel;
+import java.text.DecimalFormat;
+import java.text.DecimalFormatSymbols;
+import java.text.NumberFormat;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Hashtable;
+import java.util.Vector;
+import org.apache.log4j.Logger;
+
+/**
+ *
+ * @author chm
+ */
+public class SylkExporter extends ExportUndertaker {
+ private static DecimalFormat df = new DecimalFormat("#0.00");
+ static {
+ DecimalFormatSymbols dfs = new DecimalFormatSymbols();
+ dfs.setDecimalSeparator(',');
+ df.setDecimalFormatSymbols(dfs);
+ df.setGroupingUsed(false);
+ }
+ private static SimpleDateFormat sdf;
+
+ public static final int MAX_ROWS_PER_SHEET = 65000;
+ private static final Logger logger = Logger.getLogger(SylkExporter.class);
+ private Hashtable<String, Vector<SylkTable>> sheets;
+ private Exporter exporter;
+ private String filenamePrefix;
+
+ public SylkExporter(Exporter exporter) {
+ super(exporter);
+ this.exporter = exporter;
+ sdf = new SimpleDateFormat(exporter.getApplicationConfiguration().getProperty(Constants.SYS_PROP_DATE_FORMAT,"yyyy-MM-dd"));
+ }
+
+ @Override
+ void buildSheet( ExportElementModel eem) throws Exception {
+ Vector<SylkTable> tables = sheets.get(eem.getId());
+ if (tables == null) {
+ tables = new Vector<SylkTable>();
+ sheets.put(eem.getId(), tables);
+ }
+ String libelle = eem.getId()+"-"+eem.getLibelle();
+ libelle = fr.gouv.finances.dgfip.utils.StringUtilities.toAscii(libelle,"_").replaceAll(" ", "_");
+ if(libelle.length()>=31) {
+ libelle = libelle.substring(0, 30);
+ if(libelle.endsWith(".")) libelle = libelle.substring(0, 29);
+ }
+ String filename = filenamePrefix + "_" + libelle;
+
+ SylkTable sheet = new SylkTable(filename);
+ tables.add(sheet);
+
+ addRefInMainSheet(filename, false);
+
+ for ( ExportElementModel fils : eem.getEnfants()) {
+ buildSheet(fils);
+ }
+
+ exporter.firstSheetId = eem.getId();
+ }
+
+ protected void addRefInMainSheet(String filename, boolean addPrefix) {
+ String ref = filename + ".slk";
+ // TODO
+ }
+
+ @Override
+ void flushLine( String el) {
+ }
+
+ protected void splitSheet(String sheetId) throws IOException {
+ Vector<SylkTable> v = sheets.get(sheetId);
+ SylkTable wsRef = v.get(0);
+ SylkTable otherRef = getLastSheet(sheetId);
+
+// wsRef.close();
+ Cell[] titleLine = otherRef.getTitleLine();
+ Cell[] headerLine = otherRef.getHeaderLine();
+
+ otherRef.flush();
+
+
+
+ NumberFormat nf = NumberFormat.getInstance(); // Get Instance of NumberFormat
+ nf.setMinimumIntegerDigits(2); // The minimum Digits required is 5
+ nf.setMaximumIntegerDigits(3); // The maximum Digits required is 5
+
+ String sb = (nf.format((long) v.size()));
+
+ String fname = wsRef.getFileName() + "_" + sb;
+
+ SylkTable newSheet = new SylkTable(fname,titleLine, headerLine);
+
+ addRefInMainSheet(fname, false);
+
+ v.add(newSheet);
+ //return newSheet;
+ }
+
+ @Override
+ void writeCell( String sheetId, Object o, int line, int col, boolean bypassLineRenum) throws Exception {
+ int newline = 0;
+ if (bypassLineRenum) {
+ newline = line;
+ } else {
+ int _ligne = exporter.getLastLine(sheetId);
+ if (_ligne >= (MAX_ROWS_PER_SHEET * sheets.get(sheetId).size())) {
+ splitSheet(sheetId);
+ }
+
+ // renumérotation de la ligne
+ newline = _ligne;
+ newline = _ligne % (MAX_ROWS_PER_SHEET) + 2;
+ }
+
+ SylkTable sheet = getLastSheet(sheetId);
+ if (line == 0) {
+ sheet.addTitle(col, newline, o);
+ } else if (line == 1) {
+ sheet.addHeader(col, newline, o);
+ } else {
+ sheet.addValue(col, newline, o);
+ }
+ }
+
+ private SylkTable getLastSheet(String sheetId) {
+ Vector<SylkTable> v = sheets.get(sheetId);
+ if (v != null) {
+ return v.lastElement();
+ } else {
+ return null;
+ }
+ }
+
+ @Override
+ void mergeCells( String sheetId, int col1, int row1, int col2, int row2) {
+ logger.debug("mergeCells(" + sheetId + "," + col1 + "," + row1 + "," + col2 + "," + row2 + ")");
+ }
+
+ @Override
+ int getLastLineLastSheet( String sheetId) {
+ SylkTable ws = getLastSheet(sheetId);
+ int ret = ws.getRows() < 2 ? 2 : ws.getRows();
+ logger.debug("getLastLineLastSheet(" + sheetId + ") -> " + ret);
+ return ret;
+ }
+
+ @Override
+ boolean sheetExists( String sheetId) {
+ logger.debug("sheetExists(" + sheetId + ")");
+ boolean bRet = sheets.containsKey(sheetId);
+ return bRet;
+ }
+
+ @Override
+ void close() {
+ logger.debug("close()");
+ }
+
+ @Override
+ void finish() throws Exception {
+ logger.debug("finish()");
+ for(String key:sheets.keySet()) {
+ Vector<SylkTable> v=sheets.get(key);
+ for(int i=0;i<v.size();i++) {
+ v.get(i).flush();
+ }
+ v.clear();
+ }
+ sheets.clear();
+ }
+
+ @Override
+ void initialize() throws Exception {
+ logger.debug("initialize()");
+ String dirRessources = exporter.getApplicationConfiguration().getProperty(Constants.SYS_PROP_RESOURCES_LOCATION);
+ recopieFichier(dirRessources + "/modeleExportXemelios-97.xls", exporter.fDest.getPath());
+
+ sheets = new Hashtable<String, Vector<SylkTable>>();
+ filenamePrefix = StringUtilities.removeFileNameSuffix(exporter.fDest.getPath());
+ }
+ /**
+ * Copie le fichier src vers dest
+ * @param src
+ * @param dst
+ */
+ private void recopieFichier(String src, String dst) {
+ FileChannel in = null; // canal d'entrée
+ FileChannel out = null; // canal de sortie
+
+ try {
+ in = new FileInputStream(src).getChannel();
+ out = new FileOutputStream(dst).getChannel();
+ in.transferTo(0, in.size(), out);
+ } catch (Exception e) {
+ e.printStackTrace(); // n'importe quelle exception
+ } finally { // finalement on ferme
+ if (in != null) {
+ try {
+ in.close();
+ } catch (IOException e) { }
+ }
+ if (out != null) {
+ try {
+ out.close();
+ } catch (IOException e) { }
+ }
+ }
+ }
+
+ private class SylkTable {
+
+ public static final transient String SYLK_HEADER = "ID;PWXL;N;E\n"+
+ "P;PGeneral\n"+
+ "P;P0\n"+
+ "P;P0.00\n"+
+ "P;P#,##0\n"+
+ "P;P#,##0.00\n"+
+ "P;P#,##0\\ _\e(0;;\\-#,##0\\ _\e(0\n"+
+ "P;P#,##0\\ _\e(0;;[Red]\\-#,##0\\ _\e(0\n"+
+ "P;P#,##0.00\\ _\e(0;;\\-#,##0.00\\ _\e(0\n"+
+ "P;P#,##0.00\\ _\e(0;;[Red]\\-#,##0.00\\ _\e(0\n"+
+ "P;P#,##0\\ \"$\";;\\-#,##0\\ \"$\"\n"+
+ "P;P#,##0\\ \"$\";;[Red]\\-#,##0\\ \"$\"\n"+
+ "P;P#,##0.00\\ \"$\";;\\-#,##0.00\\ \"$\"\n"+
+ "P;P#,##0.00\\ \"$\";;[Red]\\-#,##0.00\\ \"$\"\n"+
+ "P;P0%\n"+
+ "P;P0.00%\n"+
+ "P;P0.00E+00\n"+
+ "P;P##0.0E+0\n"+
+ "P;P#\" \"?/?\n"+
+ "P;P#\" \"??/??\n"+
+ "P;Pdd/mm/yyyy\n"+
+ "P;Pdd\\-mmm\\-yy\n"+
+ "P;Pdd\\-mmm\n"+
+ "P;Pmmm\\-yy\n"+
+ "P;Ph:mm\\ AM/PM\n"+
+ "P;Ph:mm:ss\\ AM/PM\n"+
+ "P;Phh:mm\n"+
+ "P;Phh:mm:ss\n"+
+ "P;Pdd/mm/yyyy\\ hh:mm\n"+
+ "P;Pmm:ss\n"+
+ "P;Pmm:ss.0\n"+
+ "P;P@\n"+
+ "P;P[h]:mm:ss\n"+
+ "P;P_-* #,##0\\ \"$\"_-;;\\-* #,##0\\ \"$\"_-;;_-* \"-\"\\ \"$\"_-;;_-@_-\n"+
+ "P;P_-* #,##0\\ _\e(0_-;;\\-* #,##0\\ _\e(0_-;;_-* \"-\"\\ _\e(0_-;;_-@_-\n"+
+ "P;P_-* #,##0.00\\ \"$\"_-;;\\-* #,##0.00\\ \"$\"_-;;_-* \"-\"??\\ \"$\"_-;;_-@_-\n"+
+ "P;P_-* #,##0.00\\ _\e(0_-;;\\-* #,##0.00\\ _\e(0_-;;_-* \"-\"??\\ _\e(0_-;;_-@_-\n"+
+ "P;P\"Vrai\";;\"Vrai\";;\"Faux\"\n"+
+ "P;P\"Actif\";;\"Actif\";;\"Inactif\"\n"+
+ "P;FArial;M200\n"+
+ "P;FArial;M200\n"+
+ "P;FArial;M200\n"+
+ "P;FArial;M200\n"+
+ "P;EArial;M200\n"+
+ "P;EArial;M160\n"+
+ "P;EArial;M200;SU;L13\n"+
+ "P;EArial;M200;SU;L21\n"+
+ "P;EArial;M280;SB\n"+
+ "P;EArial;M240;SB\n"+
+ "F;P0;DG0G10;G;M255\n";
+ private String filename;
+ private ArrayList<Cell[]> rowArray;
+ private boolean written = false;
+
+ public SylkTable(String filename) {
+ super();
+ this.filename = filename;
+ rowArray = new ArrayList<Cell[]>();
+ }
+ public SylkTable(String filename, Cell[] titleLine, Cell[] headerLine) {
+ this(filename);
+ rowArray.add(titleLine);
+ rowArray.add(headerLine);
+ }
+
+ public void addTitle(int col, int row, Object data) {
+ ensureCapacity(row);
+ Cell[] line = rowArray.get(row);
+ line[col] = new Cell(data);
+ line[col].setStyle(Cell.CELL_FMT_TITLE);
+ }
+
+ public void addHeader(int col, int row, Object data) {
+ ensureCapacity(row);
+ Cell[] line = rowArray.get(row);
+ line[col] = new Cell(data);
+ line[col].setStyle(Cell.CELL_FMT_HEADER);
+ }
+
+ public void addValue(int col, int row, Object data) {
+ ensureCapacity(row);
+ Cell[] line = rowArray.get(row);
+ line[col] = new Cell(data);
+ }
+
+ public String getFileName() {
+ return filename;
+ }
+
+ public int getRows() {
+ return rowArray.size();
+ }
+
+ private void ensureCapacity(int row) {
+ while(rowArray.size()<(row+1))
+ rowArray.add(new Cell[256]);
+ }
+
+ private void writeTable(Writer w) throws IOException {
+ if(written) return;
+ w.write(SYLK_HEADER);
+ for(int y=0;y<rowArray.size();y++) {
+ Cell[] line = rowArray.get(y);
+ for(int x=0;x<line.length;x++) {
+ if(line[x]!=null) w.write(line[x].getSylkRepresentation(y,x));
+ }
+ }
+ w.write("E\n");
+ written = true;
+ }
+
+ public void flush() throws IOException {
+ if(rowArray.isEmpty()) return;
+ logger.debug("writting "+getFileName()+".slk");
+ File f = new File(getFileName()+".slk");
+ FileWriter fw = new FileWriter(f);
+ writeTable(fw);
+ fw.flush(); fw.close();
+ // empty the data
+ clear();
+ }
+
+ private void clear() {
+ for(Cell[] line:rowArray) {
+ for(int i=0;i<line.length;i++) line[i]=null;
+ }
+ rowArray.clear();
+ }
+
+ public Cell[] getTitleLine() { return rowArray.get(0); }
+ public Cell[] getHeaderLine() { return rowArray.get(1); }
+ }
+
+ private class Cell {
+ public static final int CELL_VALUE = 0;
+ public static final int CELL_FORMULA = 1;
+ public static final int CELL_FMT_STD = 0;
+ public static final int CELL_FMT_TITLE = 1;
+ public static final int CELL_FMT_HEADER = 2;
+ public static final int ALIGN_DEFAULT = 0;
+ public static final int ALIGN_RIGHT = 1;
+ public static final int ALIGN_CENTER = 2;
+ public static final int ALIGN_LEFT = 3;
+ private int datatype;
+ private int format;
+ private int style;
+ private Object value;
+
+ public Cell(Object o) {
+ super();
+ value = o;
+ datatype = CELL_VALUE;
+ if (o instanceof Number) {
+ format = ALIGN_RIGHT;
+ } else if(value instanceof java.util.Date) {
+ format = ALIGN_CENTER;
+ } else {
+ format = ALIGN_LEFT;
+ }
+ }
+ public void setStyle(int style) {
+ this.style=style;
+ }
+
+ public String getSylkRepresentation(int i, int j) {
+ StringBuilder sb = new StringBuilder();
+ if (value != null) {
+ if (datatype == CELL_VALUE) {
+ sb.append("C;Y").append(i + 1).append(";X").append(j + 1).append(";K").append(getFormattedValue()).append("\n");
+ } else {
+ sb.append("C;Y").append(i + 1).append(";X").append(j + 1).append(";E").append(getFormattedValue()).append("\n");
+ }
+
+ sb.append("F;P0;Y").append(i + 1).append(";X").append(j + 1);
+ if (format == ALIGN_RIGHT) {
+ sb.append(";FG0R");
+ } else if (format == ALIGN_CENTER) {
+ sb.append(";FG0C");
+ } else if (format == ALIGN_LEFT) {
+ sb.append(";FG0L");
+ }
+
+ if(style==CELL_FMT_TITLE) sb.append(";SLM0"); //sb.append(";SDLTM15");
+ else if(style==CELL_FMT_HEADER) sb.append(";SDLM10");
+ else sb.append(";SLM0");
+
+ sb.append("\n");
+ }
+ return sb.toString();
+ }
+
+ public String getFormattedValue() {
+ String ret = "";
+ if(value instanceof Integer || value instanceof Long || value instanceof Short) {
+ ret = value.toString();
+ } else if(value instanceof Number) {
+// ret = "\""+df.format(value)+"\"";
+ ret = df.format(value);
+ } else if(value instanceof java.util.Date) {
+ ret = "\""+sdf.format((java.util.Date)value)+"\"";
+ } else {
+ ret = "\""+((String)value).replaceAll(";", ";;")+"\"";
+ }
+ return ret;
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2006 axYus - www.axyus.com
+ * 2006 JP.Tessier- jean-philippe.tessier@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.importers;
+
+import java.awt.Graphics;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+import java.util.TreeSet;
+import java.util.Vector;
+
+import javax.swing.BorderFactory;
+import javax.swing.BoundedRangeModel;
+import javax.swing.JButton;
+import javax.swing.JDialog;
+import javax.swing.JFrame;
+import javax.swing.JOptionPane;
+import javax.swing.JProgressBar;
+import javax.swing.JTextField;
+import javax.swing.SwingUtilities;
+
+import org.apache.log4j.Logger;
+
+import com.jgoodies.forms.builder.PanelBuilder;
+import com.jgoodies.forms.layout.CellConstraints;
+import com.jgoodies.forms.layout.FormLayout;
+
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
+import fr.gouv.finances.cp.utils.ui.DlgGetPair;
+import fr.gouv.finances.cp.utils.ui.IhmFactory;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.dgfip.xemelios.auth.UnauthorizedException;
+import fr.gouv.finances.dgfip.xemelios.common.ToolException;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.importers.ImportServiceProvider;
+import fr.gouv.finances.dgfip.xemelios.data.DataAccessException;
+import fr.gouv.finances.dgfip.xemelios.data.DataConfigurationException;
+import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
+import fr.gouv.finances.dgfip.xemelios.importers.EtatImporteur;
+import fr.gouv.finances.dgfip.xemelios.swing.InfiniteGlassPane;
+
+public class ImportServiceSwingProvider implements ImportServiceProvider {
+
+ private static Logger logger = Logger.getLogger(ImportServiceSwingProvider.class);
+ private MainWindow owner = null;
+ private int lastReponse = -1;
+ private final static boolean SHOW_CANCEL_BUTTON = true;
+ protected ProgressDlg pg;
+ private EtatImporteur ei;
+ private boolean displayFeedback = true;
+ private boolean alwaysOverwrite = false;
+
+ public ImportServiceSwingProvider(MainWindow owner, EtatImporteur ei, int nbfiles) {
+ super();
+ this.owner = owner;
+ //this.pg=new ProgressDlg(owner,nbfiles,ei);
+ this.ei = ei;
+ }
+
+ @Override
+ public Pair getBudget(DocumentModel dm, Pair collectivite, String fileName, Pair budget) throws ToolException {
+ Pair ret = null;
+ if (ret == null) {
+ TreeSet<Pair> existing = new TreeSet<Pair>();
+ try {
+ existing.addAll(DataLayerManager.getImplementation().getBudgets(dm, collectivite, owner.getConnectedUser()));
+ } catch (UnauthorizedException ex) {
+ throw new ToolException(ex, ToolException.ERROR_UNAUTHORIZED);
+ } catch (DataConfigurationException e) {
+ logger.error("in getBudget", e);
+ } catch (DataAccessException e) {
+ logger.error("in getBudget", e);
+ }
+ Vector<Pair> budgetsDm = dm.getDefaultBudgets();
+ existing.addAll(budgetsDm);
+ QueryBudget qb = new QueryBudget(fileName, existing, collectivite.libelle, budget);
+ if (SwingUtilities.isEventDispatchThread()) {
+ qb.run();
+ } else {
+ try {
+ SwingUtilities.invokeAndWait(qb);
+ } catch (Throwable t) {
+ }
+ }
+ ret = qb.getRet();
+ if (ret == null) {
+ throw new ToolException("Action interrompue", ToolException.ERROR_INTERRUPTED);
+ }
+ }
+ return ret;
+ }
+
+ @Override
+ public Pair getCollectivite(DocumentModel dm, String fileName, Pair collectivite) throws ToolException {
+ Pair ret = null;
+ if (ret == null) {
+ QueryCollectivite qc = new QueryCollectivite(dm, fileName, collectivite);
+ if (SwingUtilities.isEventDispatchThread()) {
+ qc.run();
+ } else {
+ try {
+ SwingUtilities.invokeAndWait(qc);
+ } catch (Throwable t) {
+ }
+ }
+ ret = qc.getRet();
+ if (ret == null) {
+ throw new ToolException("Import interrompu", ToolException.ERROR_INTERRUPTED);
+ }
+ }
+ return ret;
+ }
+
+ @Override
+ public boolean getOverwrite(String docName) throws Exception {
+ if (alwaysOverwrite) {
+ return true;
+ }
+ if (lastReponse == 0 || lastReponse == 1) {
+ return (lastReponse == 0);
+ }
+ QueryOverwrite qo = new QueryOverwrite(docName);
+ int ret = -2;
+ if (SwingUtilities.isEventDispatchThread()) {
+ qo.run();
+ } else {
+ try {
+ SwingUtilities.invokeAndWait(qo);
+ } catch (Throwable t) {
+ }
+ }
+ ret = qo.getRet();
+ if (ret == JOptionPane.CLOSED_OPTION || ret == 2) {
+ throw new Exception("Annuler");
+ }
+ lastReponse = ret;
+ return ret == 0;
+ }
+
+ @Override
+ public void setEtatImporter(EtatImporteur ei) {
+ this.ei = ei;
+ try{
+//displayProgress(ei.getFilesToImport().length);
+ } catch (Exception e) {
+ logger.debug("Problèmes dans setEtatImporter(EtatImporteur ei) : Pb de displayProgress()",e);
+ }
+ /*ei.addPropertyChangeListener(new PropertyChangeListener() {
+
+ public void propertyChange(PropertyChangeEvent evt) {
+ String propName = evt.getPropertyName();
+ logger.debug("property " + propName + " changed");
+ if ("FILE_NAME".equals(propName)) {
+ pg.setCurrentFile((String) evt.getNewValue());
+ } else if ("progress".equals(propName)) {
+ Integer progress = (Integer) evt.getNewValue();
+ pg.pushCurrentProgress(progress.intValue());
+ } else if ("terminated".equals(propName)) {
+ pg.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
+ pg.setVisible(false);
+ }
+ }
+ });*/
+ }
+
+ @Override
+ public Pair getCollectivite() {
+ return ei.getCollectivite();
+ }
+
+ @Override
+ public Pair getBudget() {
+ return ei.getBudget();
+ }
+
+ public void terminate() {
+ pg.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
+ pg.setVisible(false);
+ }
+
+ public interface ImmediatlyPaintable {
+
+ public void paintImmediatly();
+ }
+
+ public static class PaintableProgress extends JProgressBar implements ImmediatlyPaintable {
+
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+
+ public PaintableProgress() {
+ super();
+ }
+
+ public PaintableProgress(int orient) {
+ super(orient);
+ }
+
+ public PaintableProgress(int min, int max) {
+ super(min, max);
+ }
+
+ public PaintableProgress(int orient, int min, int max) {
+ super(orient, min, max);
+ }
+
+ public PaintableProgress(BoundedRangeModel newModel) {
+ super(newModel);
+ }
+
+ @Override
+ public void paintImmediatly() {
+ Runnable code = new Runnable() {
+
+ @Override
+ public void run() {
+ paintImmediately(0, 0, getWidth(), getHeight());
+ }
+ };
+ if (SwingUtilities.isEventDispatchThread()) {
+ code.run();
+ } else {
+ try {
+ SwingUtilities.invokeAndWait(code);
+ } catch (Exception ex) {
+ logger.error("tu sais ou", ex);
+ }
+ }
+ }
+ }
+
+ @Override
+ public void displayProgress(final int nbFiles) {
+ Runnable code = new Runnable() {
+
+ @Override
+ public void run() {
+ logger.debug(this.getClass().getName());
+ if (pg == null) {
+ pg = new ProgressDlg(owner, nbFiles, ei);
+ }
+ if (ei != null) {
+ ei.addPropertyChangeListener(new PropertyChangeListener() {
+ @Override
+ public void propertyChange(PropertyChangeEvent evt) {
+ String propName = evt.getPropertyName();
+// logger.debug("property "+propName+" changed");
+ if ("FILE_NAME".equals(propName)) {
+ pg.setCurrentFile((String) evt.getNewValue());
+ } else if ("progress".equals(propName)) {
+ Integer progress = (Integer) evt.getNewValue();
+ pg.pushCurrentProgress(progress.intValue());
+ } else if ("terminated".equals(propName)) {
+ terminate();
+ }
+ }
+ });
+ }
+ pg.setVisible(true);
+ }
+ };
+ if (SwingUtilities.isEventDispatchThread()) {
+ code.run();
+ } else {
+ try {
+ SwingUtilities.invokeAndWait(code);
+ } catch (Throwable t) {
+ }
+ }
+ }
+
+ @Override
+ public void pushCurrentProgress(final int progress) {
+ pg.pushCurrentProgress(progress);
+ }
+
+ @Override
+ public void displayMessage(String msg, int msgType) {
+ if (shouldDisplayFeedback()) {
+ JOptionPane.showMessageDialog(owner, msg, "Import", msgType == ImportServiceProvider.MSG_TYPE_INFORMATION ? JOptionPane.INFORMATION_MESSAGE : JOptionPane.ERROR_MESSAGE);
+ }
+ }
+
+ @Override
+ public void displayException(Throwable t) {
+ new DisplayExceptionDlg((JFrame) owner, t);
+ }
+
+ @Override
+ public void startLongWait() {
+ pg.setUnknownEndded(true);
+ }
+
+ @Override
+ public void endLongWait() {
+ pg.setUnknownEndded(false);
+ }
+
+ private class QueryCollectivite implements Runnable {
+
+ private Pair ret;
+ private String fileName;
+ private DocumentModel dm;
+ Pair collectivite;
+
+ public QueryCollectivite(DocumentModel dm, String fileName, Pair collectivite) {
+ super();
+ this.fileName = fileName;
+ this.dm = dm;
+ this.collectivite = collectivite;
+ }
+
+ @Override
+ public void run() {
+ DlgGetPair dlg = new DlgGetPair(owner, "Sur quel(le) " + dm.getLibelleCollectivite() + " porte ce document :\n" + fileName + " ?", null, null, collectivite);
+
+ if (dlg.run()) {
+ ret = new Pair(dlg.getCode(), dlg.getLibelle());
+ }
+ }
+
+ public Pair getRet() {
+ return ret;
+ }
+ }
+
+ private class QueryBudget implements Runnable {
+
+ private String fileName;
+ private TreeSet<Pair> existing;
+ private Pair ret;
+ private String collectivite = null;
+ private Pair budget;
+
+ public QueryBudget(String fileName, TreeSet<Pair> existing, String collectivite, Pair budget) {
+ super();
+ this.fileName = fileName;
+ this.existing = existing;
+ this.collectivite = collectivite;
+ this.budget = budget;
+ }
+
+ @Override
+ public void run() {
+ DlgGetPair dlg = null;
+// if(existing.size()>0){
+ dlg = new DlgGetPair(owner, "Sur quel budget porte ce document :\n" + fileName + " ?", existing, collectivite, budget);
+
+ if (dlg.run()) {
+ ret = new Pair(dlg.getCode(), dlg.getLibelle());
+ }
+ logger.debug("fin de QueryBudget.run()");
+ }
+
+ public Pair getRet() {
+ logger.debug("QueryBudget.getRet()");
+ return ret;
+ }
+ }
+
+ private class QueryOverwrite implements Runnable {
+
+ private String fileName;
+ private int ret = -2;
+
+ public QueryOverwrite(String fileName) {
+ super();
+ this.fileName = fileName;
+ }
+
+ @Override
+ public void run() {
+ String msg = "Ce document existe déjà : " + fileName + "; voulez-vous l'écraser ?";
+ String[] options = {"Oui", "Non", "Annuler"};
+ ret = JOptionPane.showOptionDialog(owner, msg, "Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
+ }
+
+ public int getRet() {
+ return ret;
+ }
+ }
+
+ public final class ProgressDlg extends JDialog {
+
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+ public static final String DEFAULT_TEXT = "Import en cours : ";
+ private boolean shouldContinue = true;
+ private EtatImporteur ei = null;
+ private int nbFilesToImport, nbFilesImported = -1;
+ PaintableProgress globalProgress, currentProgress;
+ JTextField currentFileName;
+
+ public ProgressDlg(JFrame owner, int nbFilesToImport, EtatImporteur ei) {
+ super(owner, "Import en cours...");
+ this.nbFilesToImport = nbFilesToImport;
+ this.ei = ei;
+ initComponents(nbFilesToImport);
+ }
+
+ protected void initComponents(int nbFilesToImport) {
+ IhmFactory iF = IhmFactory.newInstance();
+ FormLayout fl = null;
+ if (SHOW_CANCEL_BUTTON) {
+ fl = new FormLayout("3dlu,pref,3dlu", "3dlu,pref,1dlu,pref,5dlu,pref,1dlu,pref,3dlu,pref,3dlu");
+ } else {
+ fl = new FormLayout("3dlu,pref,3dlu", "3dlu,pref,1dlu,pref,5dlu,pref,1dlu,pref,3dlu");
+ }
+ CellConstraints cc = new CellConstraints();
+ PanelBuilder pb = new PanelBuilder(fl);
+
+ pb.add(iF.newLabel("Import global", "normal"), cc.xy(2, 2));
+ globalProgress = new PaintableProgress(0, 100);
+ globalProgress.setStringPainted(true);
+ globalProgress.setMaximum(1000);
+ pb.add(globalProgress, cc.xy(2, 4));
+
+ currentFileName = new JTextField(30);
+ currentFileName.setBackground(getBackground());
+ currentFileName.setBorder(BorderFactory.createEmptyBorder());
+ currentFileName.setEditable(false);
+ currentFileName.setText(DEFAULT_TEXT);
+ pb.add(currentFileName, cc.xy(2, 6));
+ currentProgress = new PaintableProgress(0, 100);
+ currentProgress.setStringPainted(true);
+ pb.add(currentProgress, cc.xy(2, 8));
+ if (SHOW_CANCEL_BUTTON) {
+ JButton pbCancel = new JButton("Annuler");
+ pbCancel.addActionListener(new ActionListener() {
+
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ ei.cancel(true);
+ }
+ });
+ pb.add(pbCancel, cc.xy(2, 10));
+ if (ei == null) {
+ pbCancel.setEnabled(false);
+ }
+ }
+
+ setContentPane(pb.getPanel());
+ setResizable(false);
+ setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
+ pack();
+ setLocationRelativeTo(getOwner());
+ setVisible(true);
+ Graphics g = getGraphics();
+ g.setClip(0, 0, getWidth(), getHeight());
+ paint(g);
+ setGlassPane(new InfiniteGlassPane());
+ }
+
+ public boolean setCurrentFile(String fileName) {
+ nbFilesImported++;
+logger.debug("Text import : " + DEFAULT_TEXT + fileName + " ("+(1+nbFilesImported)+"/"+nbFilesToImport+")");
+ currentFileName.setText(DEFAULT_TEXT + fileName + " ("+(1+nbFilesImported)+"/"+nbFilesToImport+")");
+ currentProgress.setMaximum(100);
+ currentProgress.setValue(0);
+ return shouldContinue;
+ }
+
+ public boolean pushCurrentProgress(int value) {
+ // logger.debug("CurrentProgress: "+value);
+ currentProgress.setValue(value);
+ //logger.debug(nbFilesToImport+" fichiers à importer.\n"+nbFilesImported+" fichiers importés.");
+ int progress = (int) (((nbFilesImported + currentProgress.getPercentComplete()) / nbFilesToImport) * 1000);
+//logger.debug("GetMaximum="+globalProgress.getMaximum()+" | GlobalProgress: "+progress);
+ globalProgress.setValue(progress);
+ // paintComponents(g);
+ // paintAll(g);
+ repaintImmediatly();
+ return shouldContinue;
+ }
+
+ public void repaintImmediatly() {
+ // logger.debug("repaintImmediatly");
+ currentProgress.paintImmediatly();
+ globalProgress.paintImmediatly();
+ Graphics g = getGraphics();
+ g.setClip(0, 0, getWidth(), getHeight());
+ if (isLightweight()) {
+ paint(g);
+ } else {
+ update(g);
+ }
+ }
+
+ public void setUnknownEndded(boolean start) {
+ getGlassPane().setVisible(start);
+ }
+ }
+
+ @Override
+ public void setDisplayFeedback(boolean display) {
+ displayFeedback = display;
+ }
+
+ @Override
+ public boolean shouldDisplayFeedback() {
+ return displayFeedback;
+ }
+
+ @Override
+ public void setCollectivite(Pair p) {
+ ei.setCollectivite(p);
+ }
+
+ @Override
+ public void setBudget(Pair p) {
+ ei.setBudget(p);
+ }
+
+ @Override
+ public void setAlwaysOverwrite(boolean b) {
+ alwaysOverwrite = b;
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2008 axYus - www.axyus.com
+ * 2008 Christophe Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.importers.docetatProvider;
+
+import fr.gouv.finances.dgfip.xemelios.common.config.NamespaceModel;
+import java.util.ArrayList;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.Set;
+import javax.xml.XMLConstants;
+
+/**
+ *
+ * @author chm
+ */
+public class NamespaceHolder {
+
+ private Hashtable<String, String> prefixToUri = null;
+ private Hashtable<String, ArrayList<String>> uriToPrefix = null;
+
+ public NamespaceHolder() {
+ super();
+ prefixToUri = new Hashtable<String, String>();
+ uriToPrefix = new Hashtable<String, ArrayList<String>>();
+ }
+
+ public void addMapping(String prefix, String uri) {
+ prefixToUri.put(prefix, uri);
+ ArrayList<String> prefixes = uriToPrefix.get(uri);
+ if (prefixes == null) {
+ prefixes = new ArrayList<String>();
+ uriToPrefix.put(uri, prefixes);
+ }
+ if (!prefixes.contains(prefix)) {
+ prefixes.add(prefix);
+ }
+ }
+
+ public void removeMapping(String prefix) {
+ String uri = prefixToUri.remove(prefix);
+ if (uri == null) {
+ return;
+ }
+ ArrayList<String> prefixes = uriToPrefix.get(uri);
+ if (prefixes != null) {
+ prefixes.remove(prefix);
+ }
+ }
+
+ public String getNamespaceURI(String prefix) {
+ String ret = prefixToUri.get(prefix);
+ return ret;
+ }
+
+ public String getPrefix(String namespaceURI) {
+ String ret = null;
+ if (namespaceURI == null) {
+ throw new IllegalArgumentException("namespaceURI can not be null");
+ } else if (XMLConstants.XML_NS_PREFIX.equals(namespaceURI)) {
+ ret = XMLConstants.XML_NS_URI;
+ } else if (XMLConstants.XMLNS_ATTRIBUTE.equals(namespaceURI)) {
+ ret = XMLConstants.XMLNS_ATTRIBUTE_NS_URI;
+ }
+ ArrayList<String> prefixes = uriToPrefix.get(namespaceURI);
+ if (prefixes != null) {
+ ret = prefixes.get(0);
+ for (String s : prefixes) {
+ if (s.length() < ret.length()) {
+ ret = s;
+ }
+ }
+ }
+ return ret;
+ }
+
+ public Iterator getPrefixes(String namespaceURI) {
+ if (namespaceURI == null) {
+ throw new IllegalArgumentException("namespaceURI must not be null");
+ }
+ ArrayList<String> prefixes = uriToPrefix.get(namespaceURI);
+ if (prefixes != null) {
+ return prefixes.iterator();
+ } else if (XMLConstants.XML_NS_PREFIX.equals(namespaceURI)) {
+ return new NamespaceModel.StringIterator<String>(XMLConstants.XML_NS_URI);
+ } else if (XMLConstants.XMLNS_ATTRIBUTE.equals(namespaceURI)) {
+ return new NamespaceModel.StringIterator<String>(XMLConstants.XMLNS_ATTRIBUTE_NS_URI);
+ }
+ return null;
+ }
+
+ public Set<String> getAllPrefixes() {
+ return prefixToUri.keySet();
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.plugins;
+
+import fr.gouv.finances.cp.utils.StartUrl;
+import java.awt.Cursor;
+import java.io.File;
+import java.io.IOException;
+
+import javax.swing.JFileChooser;
+import javax.swing.JOptionPane;
+import javax.swing.filechooser.FileFilter;
+
+import org.apache.log4j.Logger;
+
+import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+import fr.gouv.finances.dgfip.xemelios.plugins.ExportPlugin;
+import java.io.FileOutputStream;
+import javax.swing.SwingUtilities;
+
+
+/**
+ * Defines contract to make export plugins.
+ * An implementation must provide a constructor with no parameters
+ * @author chm
+ */
+public class ExportPluginRunner extends XemeliosPlugin {
+ private static Logger logger = Logger.getLogger(ExportPluginRunner.class);
+
+ private Throwable exceptionDuringProcess = null;
+ private String fileName=null;
+ private XemeliosUser user;
+ private ExportPlugin plugin;
+
+ public ExportPluginRunner(XemeliosUser user) {
+ super();
+ this.user=user;
+ }
+ @Override
+ public Long doInBackground() throws Exception {
+ Long nbExport = new Long(0);
+ try {
+ nbExport = plugin.doExport();
+ } catch(Throwable t) {
+ logger.error("in doExport:",t);
+ exceptionDuringProcess = t;
+ }
+ return nbExport;
+ }
+ @Override
+ public int getPluginType() {
+ return XemeliosPlugin.TYPE_EXPORT;
+ }
+
+ public ExportPlugin getPlugin() {
+ return plugin;
+ }
+
+ public void setPlugin(ExportPlugin plugin) {
+ this.plugin = plugin;
+ }
+
+ public StringBuffer getBuffer() throws Exception {
+ return (StringBuffer)get();
+ }
+ @Override
+ public void done() {
+ super.done();
+ terminate();
+ }
+ public void terminate() {
+ try {
+ if(plugin.getOutputStream()!=null) {
+ plugin.getOutputStream().flush();
+ plugin.getOutputStream().close();
+ }
+ } catch(IOException ioEx) {
+ logger.error("closing outputstream",ioEx);
+ }
+ setProgressVisible(false);
+ if(exceptionDuringProcess!=null) new DisplayExceptionDlg(SwingUtilities.getWindowAncestor(getSearchWindow()),exceptionDuringProcess);
+ else {
+ try { StartUrl.startUrl(fileName); } catch(Exception ex) {}
+ // new File(fileName).toURI().toURL().toExternalForm()
+ }
+ getSearchWindow().setSearchEnabled(true);
+ try { logger.debug("finished: "+get().toString()); } catch(Throwable t) {logger.fatal("interrupted"); }
+ }
+ public void startExport() throws Exception {
+// plugin.setUser(user);
+ plugin.setProgressListener(this);
+ plugin.computeParameters();
+ File f = getFileToExportTo(plugin.getDefaultFileExtension());
+
+ if(f!=null) {
+ fileName = f.toURL().toExternalForm();
+ if(f.getName().indexOf(".")<0) {
+ f = new File(f.getParent(),f.getName()+"."+plugin.getDefaultFileExtension());
+ fileName = f.toURL().toExternalForm();
+ }
+ plugin.setOutputStream(new FileOutputStream(f));
+ execute();
+ } else {
+ setProgressVisible(false);
+ getSearchWindow().setSearchEnabled(true);
+ getSearchWindow().setCursor(Cursor.getDefaultCursor());
+ getSearchWindow().stopWaiter();
+ }
+ }
+ /**
+ * Returns the file filter to use. This method does not return anything by default, but it can be overriden.
+ * If no file filter is returned, a default file filter based on default file extension is provided.
+ */
+ protected File getFileToExportTo(String defaultExtension) throws IOException {
+ File ret = null;
+ FileFilter ff = null;
+// ff = getFileFilter();
+ if(ff==null) ff = new MyFileFilter(defaultExtension);
+ JFileChooser fc = new JFileChooser();
+// if(defaultExtension!=null) {
+ fc.addChoosableFileFilter(ff);
+// }
+ if(fc.showSaveDialog(MainWindow.getInstance())==JFileChooser.APPROVE_OPTION) {
+ ret = fc.getSelectedFile();
+ if(ret.exists()) {
+ int response = JOptionPane.showConfirmDialog(MainWindow.getInstance(),"Ce fichier existe déjà . Voulez-vous l'écraser ?","Confirmation",JOptionPane.YES_NO_CANCEL_OPTION);
+ switch(response) {
+ case JOptionPane.CANCEL_OPTION: {
+ ret = null;
+ break;
+ }
+ case JOptionPane.NO_OPTION: {
+ ret = getFileToExportTo(defaultExtension);
+ break;
+ }
+ case JOptionPane.YES_OPTION: {
+ ret.delete();
+ }
+ }
+ }
+ }
+ return ret;
+ }
+ protected String getFileName() { return fileName; }
+ public static class MyFileFilter extends FileFilter {
+ private String ext;
+ public MyFileFilter(String extension) {
+ super();
+ if(extension!=null) {
+ if(extension.startsWith(".")) {
+ this.ext=extension;
+ } else {
+ this.ext = "."+extension;
+ }
+ } else {
+ ext = " ";
+ }
+ }
+ @Override
+ public boolean accept(File f) {
+ return f.getName().endsWith(ext);
+ }
+ @Override
+ public String getDescription() {
+ return "Fichiers "+ext.substring(1);
+ }
+ }
+ public XemeliosUser getUser() { return user; }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.plugins;
+
+import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
+import fr.gouv.finances.cp.xemelios.ui.search.ResultDisplayerThread;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+import fr.gouv.finances.dgfip.xemelios.common.config.ListeResultatModel;
+import fr.gouv.finances.dgfip.xemelios.data.DataResultSet;
+import fr.gouv.finances.dgfip.xemelios.plugins.SearchPlugin;
+import javax.swing.SwingUtilities;
+
+/**
+ * Defines contract to make search plugins.
+ * An implementation <b>must</b> provide a constructor with a <tt>XemeliosUser</tt> parameter
+ * @author chm
+ */
+public class SearchPluginRunner extends XemeliosPlugin {
+ private ListeResultatModel lrm;
+ private XemeliosUser user;
+ private SearchPlugin plugin;
+
+ public SearchPluginRunner(XemeliosUser user) {
+ super();
+ this.user=user;
+ }
+
+ public void setPlugin(SearchPlugin plugin) {
+ this.plugin = plugin;
+ }
+ /* (non-Javadoc)
+ * @see org.jdesktop.swingworker.SwingWorker#doInBackground()
+ */
+ @Override
+ public DataResultSet doInBackground() throws Exception {
+ plugin.setParameters(getParameters());
+ plugin.setElementModel(getElementModel());
+ plugin.setListeResultatModel(lrm);
+ return plugin.getResultSet();
+ }
+
+
+ public void startSearch() throws Exception {
+ execute();
+ }
+
+ @Override
+ public int getPluginType() {
+ return XemeliosPlugin.TYPE_SEARCH;
+ }
+
+ public DataResultSet getResultSet() throws Exception {
+ return (DataResultSet) get();
+ }
+
+ public void setListeResultat(ListeResultatModel lrm) { this.lrm = lrm; }
+ public ListeResultatModel getListeResultat() { return lrm; }
+
+
+ public XemeliosUser getUser() { return user; }
+
+ @Override
+ public void done() {
+ try {
+ DataResultSet rs = (DataResultSet)get();
+ Runnable code = new ResultDisplayerThread(rs,getListeResultat(),getStart(),getElementModel(),getSearchWindow());
+ if(SwingUtilities.isEventDispatchThread()) code.run();
+ else try { SwingUtilities.invokeAndWait(code); } catch(Throwable t) {}
+ firePropertyChange("COMPLETED",Boolean.FALSE,Boolean.TRUE);
+ } catch(Throwable t) {
+ DisplayExceptionDlg.displayException(SwingUtilities.getWindowAncestor(getSearchWindow()),t);
+ } finally {
+ setProgressVisible(false);
+ super.done();
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.plugins;
+
+import java.awt.Graphics;
+import java.util.Hashtable;
+
+import javax.swing.JDialog;
+import javax.swing.JFrame;
+import javax.swing.SwingUtilities;
+
+import org.apache.log4j.Logger;
+import org.jdesktop.swingworker.SwingWorker;
+
+import com.jgoodies.forms.builder.PanelBuilder;
+import com.jgoodies.forms.layout.CellConstraints;
+import com.jgoodies.forms.layout.FormLayout;
+
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.cp.utils.ui.IhmFactory;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.EtatModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.PluginModel;
+import fr.gouv.finances.cp.xemelios.importers.ImportServiceSwingProvider.PaintableProgress;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.cp.xemelios.ui.search.PnlSearch;
+import fr.gouv.finances.dgfip.xemelios.plugins.ExportPlugin.ProgressListener;
+
+/**
+ * Defines contract to make plugins.
+ * An implementation must provide a constructor with no parameters
+ * @author chm
+ */
+public abstract class XemeliosPlugin extends SwingWorker<Object, String> implements ProgressListener {
+
+ private static final Logger logger = Logger.getLogger(XemeliosPlugin.class);
+ public static final int TYPE_SEARCH = 1;
+ public static final int TYPE_EXPORT = 2;
+ private ElementModel elementModel;
+ private EtatModel etatModel;
+ private DocumentModel documentModel;
+ private Hashtable<String, String> params;
+ private PluginModel pm;
+ private int maxProgress;
+ private String progressMessage;
+ private ProgressDlg progress = null;
+ private long start;
+ private PnlSearch sw;
+ private Pair collectivite = null, budget = null, refenrenceNomenclature = null;
+
+
+ public abstract int getPluginType();
+// private MainWindow owner;
+//
+// public void setOwner(fr.gouv.finances.cp.xemelios.ui.MainWindow owner) {
+// this.owner = owner;
+// }
+
+// public JFrame getOwner() {
+// return owner;
+// }
+
+ public void setElementModel(ElementModel em) {
+ this.elementModel = em;
+ this.etatModel = this.elementModel.getParent();
+ this.documentModel = this.etatModel.getParent();
+ }
+
+ protected final ElementModel getElementModel() {
+ return elementModel;
+ }
+
+ protected final EtatModel getEtatModel() {
+ return etatModel;
+ }
+
+ protected final DocumentModel getDocumentModel() {
+ return documentModel;
+ }
+
+ public void setParameters(Hashtable<String, String> params) {
+ this.params = params;
+ }
+
+ protected final Hashtable<String, String> getParameters() {
+ return params;
+ }
+
+ public void setModel(PluginModel pm) {
+ this.pm = pm;
+ }
+
+ public void setStart(long start) {
+ this.start = start;
+ }
+
+ public long getStart() {
+ return start;
+ }
+
+ protected final PluginModel getPluginModel() {
+ return pm;
+ }
+
+ public void setCollectivite(Pair collectivite) {
+ this.collectivite = collectivite;
+ }
+
+ public void setBudget(Pair budget) {
+ this.budget = budget;
+ }
+
+ public Pair getBudget() {
+ return budget;
+ }
+
+ public Pair getCollectivite() {
+ return collectivite;
+ }
+
+ public void setProgressInfos(int maxProgress, String progressMessage) {
+ this.maxProgress = maxProgress;
+ this.progressMessage = progressMessage;
+ }
+
+ public void pushProgress() {
+ if (progress != null) {
+ progress.pushProgress();
+ }
+ }
+
+ public void setProgressVisible(boolean show) {
+ if (show) {
+ progress = new ProgressDlg(MainWindow.getInstance(), maxProgress, progressMessage);
+ progress.setVisible(true);
+ } else if (progress != null) {
+ progress.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
+ progress.setVisible(false);
+ }
+ }
+
+ @Override
+ public void done() {
+ sw.stopWaiter();
+ }
+
+ public void setSearchWindow(PnlSearch sw) {
+ this.sw = sw;
+ }
+
+ public PnlSearch getSearchWindow() {
+ return sw;
+ }
+
+ public final class ProgressDlg extends JDialog implements ProgressListener {
+
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+ public static final String DEFAULT_TEXT = "Recherche en cours : ";
+ private PaintableProgress globalProgress;
+ private int maxProgress, value = 0;
+ private String progressMessage;
+
+ public ProgressDlg(JFrame owner, int maxProgress, String progressMessage) {
+ super(owner, DEFAULT_TEXT);
+ this.maxProgress = maxProgress;
+ this.progressMessage = progressMessage;
+ initComponents();
+ }
+
+ protected void initComponents() {
+ IhmFactory iF = IhmFactory.newInstance();
+ FormLayout fl = null;
+ fl = new FormLayout("3dlu,pref,3dlu", "3dlu,pref,1dlu,pref,3dlu");
+ CellConstraints cc = new CellConstraints();
+ PanelBuilder pb = new PanelBuilder(fl);
+
+ pb.add(iF.newLabel(progressMessage, "normal"), cc.xy(2, 2));
+ globalProgress = new PaintableProgress(0, 100);
+ globalProgress.setStringPainted(true);
+ globalProgress.setMaximum(maxProgress);
+ pb.add(globalProgress, cc.xy(2, 4));
+
+ setContentPane(pb.getPanel());
+ setResizable(false);
+ setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
+ pack();
+ setLocationRelativeTo(getOwner());
+ setVisible(true);
+ Graphics g = getGraphics();
+ g.setClip(0, 0, getWidth(), getHeight());
+ paint(g);
+ }
+
+ public void repaintImmediatly() {
+ Runnable code = new Runnable() {
+
+ public void run() {
+ globalProgress.paintImmediatly();
+ Graphics g = getGraphics();
+ g.setClip(0, 0, getWidth(), getHeight());
+ if (isLightweight()) {
+ paint(g);
+ } else {
+ update(g);
+ }
+ }
+ };
+ if (SwingUtilities.isEventDispatchThread()) {
+ code.run();
+ } else {
+ try {
+ SwingUtilities.invokeAndWait(code);
+ } catch (Throwable t) {
+ logger.error("repaintImmediatly", t);
+ }
+ }
+ }
+
+ public void pushProgress() {
+ value++;
+// logger.debug("progress: "+value);
+ globalProgress.setValue(value);
+ repaintImmediatly();
+ //repaint();
+ }
+
+ public void setProgressInfos(int maxProgress, String progressMessage) {
+ //throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ public void setProgressVisible(boolean show) {
+ //throw new UnsupportedOperationException("Not supported yet.");
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui;
+
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.FontMetrics;
+import java.awt.Frame;
+import java.awt.Graphics2D;
+import java.awt.Image;
+import java.awt.Toolkit;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.awt.image.BufferedImage;
+import java.awt.image.ImageObserver;
+import java.io.BufferedInputStream;
+import java.util.StringTokenizer;
+import java.util.Vector;
+
+import javax.swing.BoxLayout;
+import javax.swing.ImageIcon;
+import javax.swing.JButton;
+import javax.swing.JDialog;
+import javax.swing.JLabel;
+import javax.swing.JLayeredPane;
+import javax.swing.JPanel;
+
+import fr.gouv.finances.cp.utils.ui.IhmFactory;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import fr.gouv.finances.dgfip.xemelios.ui.ImageResources;
+import java.io.File;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathFactory;
+import org.w3c.dom.Document;
+
+/**
+ * A propos de l'appli
+ * @author chm
+ */
+public class AboutBox extends JDialog {
+ static {
+ if(System.getProperty("os.name").toLowerCase().indexOf("win")>=0)
+ setDefaultLookAndFeelDecorated(true);
+ }
+
+ private static final int ADDITIONAL_HEIGHT = 74;
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 3689916175660234039L;
+ public AboutBox(Frame owner) {
+ super(owner,"A propos... de "+Constants.NOM_APP);
+ initialize();
+ }
+ private void initialize() {
+ setLayout(new BoxLayout(this,BoxLayout.PAGE_AXIS));
+ JLayeredPane layer = new JLayeredPane();
+ //IhmFactory iF = IhmFactory.newInstance();
+ ImageIcon image = IhmFactory.getIconFromResource(ImageResources.ABOUT);
+ BufferedImage bi = new BufferedImage(image.getIconWidth(),image.getIconHeight()+ADDITIONAL_HEIGHT,BufferedImage.TYPE_4BYTE_ABGR);
+ Graphics2D g = (Graphics2D)bi.getGraphics();
+ g.drawImage(image.getImage(),0,0,new ImageObserver() {
+ @Override
+ public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {return true;}
+ });
+
+ int top = image.getIconHeight();
+ int width = image.getIconWidth();
+
+ g.setColor(Color.WHITE);
+ g.fillRect(0,top,width,ADDITIONAL_HEIGHT);
+ g.setColor(Color.BLACK);
+
+
+ ImageIcon logo = IhmFactory.getIconFromResource(ImageResources.EDITEUR);
+ ImageIcon moa = IhmFactory.getIconFromResource(ImageResources.MOA);
+ g.drawImage(logo.getImage(),width-logo.getIconWidth()-2,top+ADDITIONAL_HEIGHT-logo.getIconHeight()-2,this);
+// g.drawImage(logo.getImage(),width-logo.getIconWidth()-2,top+ADDITIONAL_HEIGHT-logo.getIconHeight()-2,new ImageObserver() {
+// public boolean imageUpdate(Image img, int infoFlags, int x, int y, int width, int height) { return true; }
+// });
+ g.drawImage(moa.getImage(),2,top+ADDITIONAL_HEIGHT-moa.getIconHeight()-2,this);
+ Font font = g.getFont().deriveFont(Font.BOLD, 12f);
+ ecritLigneCentree(g, getVersionText(),90, width, font, Color.BLACK);
+ ecritLigneCentree(g, "Développé par axYus",top + 5, width+moa.getIconWidth()-logo.getIconWidth()-2, font, Color.BLACK);
+ if(getParent() instanceof MainWindow) {
+ XemeliosUser user = ((MainWindow)getParent()).getConnectedUser();
+ ecritLigneCentree(g,"Utilisateur: " + user.getDisplayName(), top-20, width, font, Color.BLACK);
+ }
+ font = g.getFont().deriveFont(Font.ITALIC, 10f);
+ ecritLigneCentree(g, "pour le compte de la", top+18, width+moa.getIconWidth()-logo.getIconWidth()-2, font, Color.BLACK);
+ font = g.getFont().deriveFont(Font.PLAIN, 12f);
+ ecritLigneCentree(g, "Direction Générale des Finances Publiques", top+29, width+moa.getIconWidth()-logo.getIconWidth()-7, font, Color.BLACK);
+
+ JLabel icon = new JLabel(new ImageIcon(bi));
+ //JLabel icon = new JLabel(logo);
+ icon.setOpaque(true);
+ // si on ne definit pas la taille, rien est affiche
+ icon.setBounds(0,0,width,top+ADDITIONAL_HEIGHT);
+ icon.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(MouseEvent evt) {
+ if(evt.getButton()==MouseEvent.BUTTON3 && evt.isControlDown() && evt.getClickCount()==2) {
+ try {
+ Class c = Class.forName("fr.gouv.finances.cp.xemelios.ui.ia.Plateau");
+ c.newInstance();
+ } catch(Throwable t) {}
+ }
+ }
+ });
+ layer.setPreferredSize(new Dimension(width,top+ADDITIONAL_HEIGHT));
+ JButton pbFermer = new JButton("Fermer");
+ pbFermer.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ setVisible(false);
+ }
+ });
+ pbFermer.setBounds((width + moa.getIconWidth() - pbFermer.getPreferredSize().width - logo.getIconWidth()) / 2, top+45, (int)pbFermer.getPreferredSize().getWidth(),(int)pbFermer.getPreferredSize().getHeight());
+ layer.add(icon,new Integer(0));
+ layer.add(pbFermer,new Integer(1));
+
+ JPanel pane = new JPanel();
+ pane.setLayout(new BoxLayout(pane,BoxLayout.PAGE_AXIS));
+ pane.add(layer);
+ pane.setOpaque(true);
+ setContentPane(pane);
+ pack();
+ validate();
+ Dimension sSz = Toolkit.getDefaultToolkit().getScreenSize();
+ Dimension fSz = getSize();
+ setLocation((sSz.width - fSz.width) / 2, (sSz.height - fSz.height) / 2);
+ setResizable(false);
+ setVisible(true);
+ }
+
+ protected String getVersionText() {
+ String ret = "";
+ try {
+ String compFileName = null;
+ if(getParent() instanceof MainWindow) {
+ compFileName = ((MainWindow)getParent()).getEnvProperties().getProperty(Constants.SYS_PROP_COMPONENTS_FILENAME);
+ } else {
+ compFileName = System.getProperty(Constants.SYS_PROP_COMPONENTS_FILENAME);
+ }
+ if(compFileName!=null) {
+ File f = new File(compFileName);
+ if(f.exists()) {
+ DocumentBuilderFactory domFactory = FactoryProvider.getDocumentBuilderFactory();
+ domFactory.setNamespaceAware(true);
+ DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
+ Document dom = domBuilder.parse(f);
+ XPathFactory xpf = FactoryProvider.getXPathFactory();
+ XPath xp = xpf.newXPath();
+ ret = xp.evaluate("/xemelios-components/component[@id='xemelios-core']/@version", new DOMSource(dom));
+ }
+ }
+ } catch(Exception ex) {
+ ex.printStackTrace();
+ }
+ if(ret.length()==0) {
+ try {
+ BufferedInputStream bis = new BufferedInputStream(this.getClass().getClassLoader().getResourceAsStream(ImageResources.VERSION));
+ byte[] buf = new byte[bis.available()];
+ bis.read(buf);
+ ret = new String(buf);
+ } catch(Throwable t) {}
+ }
+ return ret;
+ }
+
+ protected void ecritLigneCentree(Graphics2D graph, String text, int top, int width, Font font, Color c) {
+ Color oldColor = graph.getColor();
+ Font oldFont = graph.getFont();
+ graph.setFont(font);
+ graph.setColor(c);
+
+ FontMetrics fm = graph.getFontMetrics();
+ StringTokenizer st = new StringTokenizer (text, " -");
+ Vector<String> lignes = new Vector<String>();
+ String ligne=null, mot;
+ while (st.hasMoreTokens()) {
+ mot = st.nextToken();
+ if (fm.stringWidth(mot)>width)
+ throw new IllegalArgumentException ("le mot "+mot+" est trop grand; essayez de trouver un autre mot.");
+
+ // si la ligne en cours + le mot en cours dépassent à droite, on commence une nouvelle ligne avec
+ // le mot en cours
+ int lenLigne = (ligne==null ? fm.stringWidth(mot) : fm.stringWidth(ligne+" "+mot) );
+ if (lenLigne > width) {
+ lignes.add (ligne);
+ ligne = mot;
+ } else {
+ if(ligne==null) ligne = mot;
+ else ligne += " "+mot;
+ }
+ }
+ if (!"".equals (ligne)) lignes.add(ligne);
+
+ // calcul de l'interligne
+ int hauteurLigne = fm.getAscent()+fm.getDescent();
+ int interligne = fm.getLeading();
+ // position du texte
+ for (int i=0; i<lignes.size(); i++) {
+ ligne = lignes.get(i);
+ int len = fm.stringWidth(ligne);
+ int x = width/2 - len/2;
+ int y = (i+1)*interligne + fm.getAscent()+ (i)*hauteurLigne + top;
+ graph.drawString (ligne, x, y);
+ }
+
+ graph.setFont(oldFont);
+ graph.setColor(oldColor);
+ }
+
+ public static void main(String[] args) {
+ new AboutBox(null);
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui;
+
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.KeyEvent;
+
+import javax.swing.AbstractAction;
+import javax.swing.Action;
+import javax.swing.JButton;
+import javax.swing.JComboBox;
+import javax.swing.JComponent;
+import javax.swing.JDialog;
+import javax.swing.JFrame;
+import javax.swing.JPanel;
+import javax.swing.JRootPane;
+import javax.swing.JTextArea;
+import javax.swing.KeyStroke;
+
+import com.jgoodies.forms.builder.PanelBuilder;
+import com.jgoodies.forms.layout.CellConstraints;
+import com.jgoodies.forms.layout.FormLayout;
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+
+import fr.gouv.finances.cp.utils.ui.IhmFactory;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentsModel;
+import java.util.ArrayList;
+
+/**
+ * Permet de demander le mot de passe à l'utilisateur
+ * @author chm
+ */
+public class AskDocumentType extends JDialog {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 3546362837975971889L;
+ static {
+ if(System.getProperty("os.name").toLowerCase().indexOf("win")>=0)
+ setDefaultLookAndFeelDecorated(true);
+ }
+ public static final transient String DLG_TITLE="Type de document";
+ private JButton pbOk, pbCancel;
+ private boolean ret;
+ private Action escapeAction;
+ private String fileName;
+ private DocumentsModel documentsType;
+ private DocumentModel dm;
+ private JComboBox cbxTypes;
+ private PropertiesExpansion applicationProperties;
+
+ public AskDocumentType(JFrame owner,String fileName,DocumentsModel dm, PropertiesExpansion applicationProperties) {
+ super(owner,DLG_TITLE,true);
+ this.applicationProperties = applicationProperties;
+ this.fileName = fileName;
+ this.documentsType = dm;
+ initComposants();
+ }
+
+ protected void initComposants() {
+ int sepInfo = 2;
+ int lineInfo = sepInfo + 2;
+ int sepData = lineInfo + 2;
+ int cbxLine = sepData + 2;
+ int buttonLine = cbxLine + 2;
+
+ JTextArea area = null;
+
+ FormLayout fl = new FormLayout(
+ // 0 1 2 3 4 5
+/* "1dlu,20dlu,pref,1dlu,pref,1dlu", */
+ "3dlu,20dlu,pref,3dlu,100dlu,3dlu",
+ "7dlu,"+ // 0
+ "pref,"+ // 1
+ "3dlu,"+ // 2
+ "pref,"+ // 3
+ "7dlu,"+ // 4
+ "pref,"+ // 5
+ "3dlu,"+ // 6
+ "pref,"+ // 7
+// "1dlu,"+ // 8
+// "pref,"+ // 9
+ "10dlu,"+ // 10
+ "pref,"+ // 11
+ "10dlu"); // 12
+ CellConstraints cc = new CellConstraints();
+ PanelBuilder pb = new PanelBuilder(fl);
+ IhmFactory iF=IhmFactory.newInstance();
+
+ pb.addSeparator("Informations", cc.xyw(2,sepInfo,4));
+ pb.add(area = new JTextArea(), cc.xyw(3,lineInfo,3));
+
+ pb.addSeparator("Données", cc.xyw(2,sepData,4));
+ pb.add(iF.newLabel("Type de document","normal"), cc.xy (3,cbxLine));
+ ArrayList<DocumentModel> visibleDocs = new ArrayList<DocumentModel>();
+ for(DocumentModel documentModel:documentsType.getDocuments()) {
+ if(documentModel.isImportable()) {
+ if("true".equals(documentModel.getDisplayInMenuIf())) {
+ if(applicationProperties.getProperty(documentModel.getDisplayInMenuIf())!=null) {
+ visibleDocs.add(documentModel);
+ }
+ } else {
+ visibleDocs.add(documentModel);
+ }
+ }
+ }
+ pb.add(cbxTypes = new JComboBox(visibleDocs.toArray()), cc.xy (5,cbxLine));
+
+ JPanel bPane = new JPanel(new FlowLayout(FlowLayout.CENTER));
+ pbCancel = new JButton(escapeAction);
+ pbOk = new JButton("Ok");
+ bPane.add(pbOk); bPane.add(pbCancel);
+
+ pb.add(bPane, cc.xyw(2,buttonLine,4));
+
+ JComboBox cbxTmp = new JComboBox();
+ cbxTypes.setSize(new Dimension(70,(int)cbxTmp.getPreferredSize().getHeight()));
+ add(pb.getPanel());
+// add(pbCancel); add(pbOk);
+
+ area.setEditable(false);
+ area.setLineWrap(true);
+ area.setRows(3);
+ area.setBackground(getBackground());
+ area.setColumns(100);
+ area.setText("Vous avez choisi d'importer le fichier \n"+fileName+"\nDe quel type de document s'agit-il ?");
+
+ pbOk.setDefaultCapable(true);
+ pbOk.addActionListener(new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ dm = (DocumentModel)cbxTypes.getSelectedItem();
+ ret = true;
+ setVisible(false);
+ }
+ });
+ getRootPane().setDefaultButton(pbOk);
+ pack();
+ setLocationRelativeTo(getParent());
+ }
+ public boolean run() {
+ setVisible(true);
+ return ret;
+ }
+ public DocumentModel getDocumentType() { return dm; }
+ @Override
+ protected JRootPane createRootPane() {
+ KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0);
+ JRootPane rp = new JRootPane();
+ escapeAction = new AbstractAction("Annuler") {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+
+ public void actionPerformed(ActionEvent evt) {
+ ret = false;
+ setVisible(false);
+ }
+ };
+ rp.registerKeyboardAction(escapeAction,"TOTOTOTO",ks,JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
+ }
+ /* (non-Javadoc)
+ * @see java.awt.Component#setVisible(boolean)
+ */
+ @Override
+ public void setVisible(boolean b) {
+ cbxTypes.grabFocus();
+ super.setVisible(b);
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2010 axYus - www.axyus.com
+ * 2010 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui;
+
+import java.awt.Color;
+import java.io.InputStream;
+import java.net.URL;
+import javax.swing.JFrame;
+import javax.swing.JOptionPane;
+import javax.swing.JScrollPane;
+import javax.swing.JTextArea;
+import javax.swing.event.DocumentEvent;
+import javax.swing.event.DocumentListener;
+import javax.swing.text.Element;
+
+public class CodeViewer extends JFrame {
+
+ private static JTextArea jta;
+ private static JTextArea lines;
+ private JScrollPane jsp;
+ private URL input;
+
+ public CodeViewer(URL input) {
+ super(input.getFile());
+ this.input = input;
+ setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
+ jsp = new JScrollPane();
+ jta = new JTextArea();
+// jta.setEditable(false);
+ lines = new JTextArea("1");
+
+ lines.setBackground(Color.LIGHT_GRAY);
+ lines.setEditable(false);
+
+ jta.getDocument().addDocumentListener(new DocumentListener() {
+
+ public String getText() {
+ int caretPosition = jta.getDocument().getLength();
+ Element root = jta.getDocument().getDefaultRootElement();
+ String text = "1" + System.getProperty("line.separator");
+ for (int i = 2; i < root.getElementIndex(caretPosition) + 2; i++) {
+ text += i + System.getProperty("line.separator");
+ }
+ return text;
+ }
+
+ public void changedUpdate(DocumentEvent de) {
+ lines.setText(getText());
+ }
+
+ public void insertUpdate(DocumentEvent de) {
+ lines.setText(getText());
+ }
+
+ public void removeUpdate(DocumentEvent de) {
+ lines.setText(getText());
+ }
+ });
+
+ jsp.getViewport().add(jta);
+ jsp.setRowHeaderView(lines);
+ jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
+
+ add(jsp);
+ pack();
+ setSize(800, 600);
+ setVisible(true);
+
+ doLoadFile();
+
+ }
+
+ protected void doLoadFile() {
+ try {
+ InputStream is = input.openStream();
+ StringBuilder sb = new StringBuilder();
+ byte[] buffer = new byte[1024];
+ int read=is.read(buffer);
+ while(read>0) {
+ sb.append(new String(buffer,0,read));
+ read=is.read(buffer);
+ }
+ jta.setText(sb.toString());
+ // on se repositionne en haut
+ jta.setCaretPosition(0);
+ } catch(Exception ex) {
+ JOptionPane.showMessageDialog(this, ex.getMessage(), "Erreur",JOptionPane.ERROR_MESSAGE);
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ * 2008 JP.Tessier - jean-philippe.tessier@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui;
+
+import java.awt.Component;
+import java.awt.Container;
+import java.awt.Cursor;
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.Image;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.FocusAdapter;
+import java.awt.event.FocusEvent;
+import java.awt.event.FocusListener;
+import java.awt.event.ItemEvent;
+import java.awt.event.ItemListener;
+import java.awt.event.KeyEvent;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.awt.image.BufferedImage;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+import java.util.Enumeration;
+import java.util.Hashtable;
+import java.util.TreeSet;
+import java.util.Vector;
+
+import javax.swing.AbstractAction;
+import javax.swing.Action;
+import javax.swing.Box;
+import javax.swing.Icon;
+import javax.swing.ImageIcon;
+import javax.swing.JButton;
+import javax.swing.JCheckBox;
+import javax.swing.JComboBox;
+import javax.swing.JComponent;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JTextField;
+import javax.swing.KeyStroke;
+import javax.swing.UIManager;
+import javax.swing.border.EmptyBorder;
+import javax.swing.event.CaretEvent;
+import javax.swing.event.CaretListener;
+import javax.swing.text.AttributeSet;
+import javax.swing.text.BadLocationException;
+import javax.swing.text.PlainDocument;
+
+import org.apache.log4j.Logger;
+import org.xml.sax.SAXException;
+
+import com.jgoodies.forms.builder.PanelBuilder;
+import com.jgoodies.forms.layout.CellConstraints;
+import com.jgoodies.forms.layout.FormLayout;
+
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
+import fr.gouv.finances.cp.utils.ui.DlgSelectFromList;
+import fr.gouv.finances.cp.utils.ui.IhmFactory;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.xemelios.ui.search.DlgSearchHelper;
+import fr.gouv.finances.cp.xemelios.ui.search.PnlSearch;
+import fr.gouv.finances.cp.xemelios.ui.search.SearchContext;
+import fr.gouv.finances.dgfip.xemelios.auth.UnauthorizedException;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import fr.gouv.finances.dgfip.xemelios.common.ToolException;
+import fr.gouv.finances.dgfip.xemelios.common.config.CritereModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.InputModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.OptionModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.PropertyModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.RecherchePaireModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ResourceModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ResourceRefModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.SearchHelperModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.SelectModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.SpecialKeyEntryModel;
+import fr.gouv.finances.dgfip.xemelios.data.DataAccessException;
+import fr.gouv.finances.dgfip.xemelios.data.DataConfigurationException;
+import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
+import fr.gouv.finances.dgfip.xemelios.ui.ImageResources;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+import javax.swing.JOptionPane;
+import javax.swing.SwingUtilities;
+import org.jdesktop.swingx.JXDatePicker;
+
+/**
+ * Affiche un critere de recherche
+ *
+ * @author chm
+ */
+public class CriteriaViewer extends JPanel implements ActionListener {
+ public static final transient String OR_ASSOCIATOR = "||";
+
+ public static final transient String AND_ASSOCIATOR = "&&";
+
+ public String DATE_FORMAT;
+
+ public SimpleDateFormat sdf;
+
+ private static Logger logger = Logger.getLogger(CriteriaViewer.class);
+
+ static IhmFactory iF = IhmFactory.newInstance();
+
+ static ImageIcon deleteImg = IhmFactory.getIconFromResource(ImageResources.DELETE_ROW);
+
+ static ImageIcon blankImg = null;
+
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 3258412820227045174L;
+
+ private ElementModel em;
+ private DocumentModel dm;
+ private Pair collectivite,budget;
+ private Hashtable<String, InputData> inputs;
+ private ArrayList<InputData> orderedInputs;
+// private ChampModel optionnalField = null;
+ private boolean hideRemoveIcon, hideChoice;
+
+ private JComboBox cbxAndOr, cbxTypeCritere;
+ private Container replaceMe;
+ private PnlSearch parent;
+ private JComponent componentToFocus = null;
+ private JCheckBox chkDisplayOptionnal = null;
+ private CritereModel currentCritereModel = null;
+ private JLabel defaultLabel = null;
+ private JLabel deleteMe = null;
+
+ public CriteriaViewer(PnlSearch parent, ElementModel em, Pair collectivite, Pair budget,boolean hideRemoveIcon, Vector<CritereModel>criteresOp) {
+ super();
+ this.parent = parent;
+ this.hideRemoveIcon = hideRemoveIcon;
+ this.em = em;
+ this.dm = em.getParent().getParent();
+ DATE_FORMAT = MainWindow.getInstance().getEnvProperties().getProperty(Constants.SYS_PROP_DATE_FORMAT);
+ sdf = new SimpleDateFormat(DATE_FORMAT);
+ this.collectivite=collectivite;
+ this.budget=budget;
+ this.hideChoice = false;
+ if (blankImg == null) {
+ Image img = new BufferedImage(deleteImg.getIconWidth(), deleteImg.getIconHeight(), BufferedImage.TYPE_INT_RGB);
+ Graphics2D gr = (Graphics2D)img.getGraphics();
+ gr.setBackground(parent.getBackground());
+ gr.clearRect(0, 0, deleteImg.getIconWidth(), deleteImg.getIconWidth());
+ blankImg = new ImageIcon(img);
+ }
+ initialize(hideRemoveIcon,false, criteresOp);
+ }
+ public CriteriaViewer(PnlSearch parent, ElementModel em, Pair collectivite, Pair budget,boolean hideRemoveIcon) {
+ this(parent,em,collectivite,budget,hideRemoveIcon,false);
+ }
+ public CriteriaViewer(PnlSearch parent, ElementModel em, Pair collectivite, Pair budget, boolean hideRemoveIcon,boolean hideChoice) {
+ super();
+ this.parent = parent;
+ this.hideRemoveIcon = hideRemoveIcon;
+ this.em = em;
+ this.dm = em.getParent().getParent();
+ DATE_FORMAT = MainWindow.getInstance().getEnvProperties().getProperty(Constants.SYS_PROP_DATE_FORMAT);
+ sdf = new SimpleDateFormat(DATE_FORMAT);
+ this.collectivite=collectivite;
+ this.budget=budget;
+ this.hideChoice = hideChoice;
+ if (blankImg == null) {
+ Image img = new BufferedImage(deleteImg.getIconWidth(), deleteImg.getIconHeight(), BufferedImage.TYPE_INT_RGB);
+ Graphics2D gr = (Graphics2D)img.getGraphics();
+ gr.setBackground(parent.getBackground());
+ gr.clearRect(0, 0, deleteImg.getIconWidth(), deleteImg.getIconWidth());
+ blankImg = new ImageIcon(img);
+ }
+ initialize(hideRemoveIcon,hideChoice);
+ }
+
+ protected void initialize(boolean hideRemoveIcon, boolean hideChoice) {
+ FormLayout fl = new FormLayout("3dlu,pref,3dlu,25dlu,3dlu,110dlu,3dlu,pref:grow(1.0),3dlu", "0dlu,pref");
+ PanelBuilder pb = new PanelBuilder(fl, this);
+ CellConstraints cc = new CellConstraints();
+ if (!hideRemoveIcon) {
+ final AbstractAction act = new AbstractAction() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ parent.removeLine(CriteriaViewer.this);
+ }
+ };
+ deleteMe = new JFocusableLabel(deleteImg,act);
+ deleteMe.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(MouseEvent evt) {
+ act.actionPerformed(null);
+ }
+ });
+ deleteMe.setToolTipText("Supprimer ce critère");
+ pb.add(deleteMe, cc.xy(2, 2));
+ Pair[] data = new Pair[2];
+ data[0] = new Pair(AND_ASSOCIATOR, "ET");
+ data[1] = new Pair(OR_ASSOCIATOR, "OU");
+ pb.add(cbxAndOr = new JComboBox(data), cc.xy(4, 2));
+ } else {
+ JLabel blank = new JLabel(blankImg);
+ blank.setBorder(new EmptyBorder(2,2,2,2));
+ pb.add(blank, cc.xy(2, 2));
+ }
+ if(!hideChoice) {
+ pb.add(cbxTypeCritere = new JComboBox(em.getAvailableCriteres()), cc.xy(6, 2));
+ cbxTypeCritere.addActionListener(this);
+ } else {
+ pb.add(defaultLabel = new JLabel("XXXX"), cc.xy(6, 2));
+ }
+ pb.add(replaceMe = new JPanel(new FlowLayout()), cc.xy(8, 2));
+ if(!hideChoice && cbxTypeCritere.getItemCount()>0) {
+ cbxTypeCritere.setSelectedIndex(0);
+ } else {
+ inputs = new Hashtable<String, InputData>();
+ orderedInputs = new ArrayList<InputData>();
+ }
+ }
+
+ protected void initialize(boolean hideRemoveIcon, boolean hideChoice, Vector<CritereModel> criteresOp) {
+ FormLayout fl = new FormLayout("3dlu,pref,3dlu,25dlu,3dlu,110dlu,3dlu,pref:grow(1.0),3dlu", "0dlu,pref");
+ PanelBuilder pb = new PanelBuilder(fl, this);
+ CellConstraints cc = new CellConstraints();
+ if (!hideRemoveIcon) {
+ final AbstractAction act = new AbstractAction() {
+
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ parent.removeLine(CriteriaViewer.this);
+ }
+
+ };
+ deleteMe = new JFocusableLabel(deleteImg,act);
+ deleteMe.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(MouseEvent evt) {
+ act.actionPerformed(null);
+ }
+ });
+ deleteMe.setToolTipText("Supprimer ce critère");
+ pb.add(deleteMe, cc.xy(2, 2));
+ Pair[] data = new Pair[2];
+ data[0] = new Pair(AND_ASSOCIATOR, "ET");
+ data[1] = new Pair(OR_ASSOCIATOR, "OU");
+ pb.add(cbxAndOr = new JComboBox(data), cc.xy(4, 2));
+ } else {
+ JLabel blank = new JLabel(blankImg);
+ blank.setBorder(new EmptyBorder(2,2,2,2));
+ pb.add(blank, cc.xy(2, 2));
+ }
+ if(!hideChoice) {
+ pb.add(cbxTypeCritere = new JComboBox(criteresOp), cc.xy(6, 2));
+ cbxTypeCritere.addActionListener(this);
+ } else {
+ pb.add(defaultLabel = new JLabel("XXXX"), cc.xy(6, 2));
+ }
+ pb.add(replaceMe = new JPanel(new FlowLayout()), cc.xy(8, 2));
+ if(!hideChoice && cbxTypeCritere.getItemCount()>0) {
+ cbxTypeCritere.setSelectedIndex(0);
+ } else {
+ inputs = new Hashtable<String, InputData>();
+ orderedInputs = new ArrayList<InputData>();
+ }
+ }
+
+ public void focusOnDelete() {
+ deleteMe.grabFocus();
+ }
+
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ if (evt.getSource() == cbxTypeCritere) {
+ inputs = new Hashtable<String, InputData>();
+ orderedInputs = new ArrayList<InputData>();
+ CritereModel cm = (CritereModel)cbxTypeCritere.getSelectedItem();
+ changeCritereModel(cm.clone());
+ }
+ }
+ public void changeCritereModel(final CritereModel newCm) {
+ try {
+ CritereModel cm = null;
+ if(!hideChoice) {
+ for(int i=0;i<cbxTypeCritere.getModel().getSize();i++) {
+ Object other = cbxTypeCritere.getModel().getElementAt(i);
+ if(newCm.equals(other)) {
+ cm = (CritereModel)other;
+ break;
+ }
+ }
+ } else {
+ cm=newCm.clone();
+ }
+ if(cm==null) return;
+ if(!hideChoice && !cbxTypeCritere.getSelectedItem().equals(cm)) {
+ cbxTypeCritere.removeActionListener(this);
+ cbxTypeCritere.setSelectedItem(cm);
+ cbxTypeCritere.addActionListener(this);
+ }
+ currentCritereModel = cm.clone();
+ replaceMe.removeAll();
+ if(hideChoice) {
+ defaultLabel.setText(cm.getLibelle());
+ }
+ if(currentCritereModel.hasBlank())
+ replaceMe.add(Box.createHorizontalGlue());
+ for (XmlMarshallable xm : cm.getInputs()) {
+ if (xm instanceof InputModel) {
+ final ArrayList<Component> al = new ArrayList<Component>();
+ final InputModel im = (InputModel)xm;
+ if (im.getLibelle() != null)
+ al.add(getLabel(im.getLibelle()));
+ String datatype = im.getDatatype();
+ Pair[] pairs = null;
+ if (datatype!=null && !im.hasToRemoveOperator()) {
+ try { pairs = DataLayerManager.getImplementation().getOperators(datatype); } catch(Throwable t) {}
+ if(pairs.length>0) {
+ final MComboBox opers = new MComboBox(pairs);
+ opers.setName("OPERATEUR:" + im.getId());
+ al.add(opers);
+ opers.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ Pair item = (Pair)opers.getSelectedItem();
+ InputData id = inputs.get("VALEUR:"+im.getId());
+ JButton pbHelp = null;
+ if(id!=null) {
+ // on cherche si il y a un helpButton
+ for(Component comp:al) {
+ if(comp instanceof JHelpButton) {
+ pbHelp = (JButton)comp;
+ break;
+ }
+ }
+ }
+ if(item.key.equals("xem:StringIsNull") || item.key.equals("xem:StringIsNotNull")) {
+ if(id!=null) {
+ if(id instanceof MTextField) {
+ MTextField mtf = (MTextField)id;
+ mtf.setText("--");
+ mtf.setEnabled(false);
+ if(pbHelp!=null) pbHelp.setEnabled(false);
+ }
+ }
+ } else {
+ if(id instanceof MTextField) {
+ MTextField mtf = (MTextField)id;
+ mtf.setText("");
+ mtf.setEnabled(true);
+ if(pbHelp!=null) pbHelp.setEnabled(true);
+ }
+ }
+ }
+ });
+ String opValue = MainWindow.getInstance().getCriteriaInputValue(im.getKeyName()+".OPERATEUR");
+ if(opValue!=null) {
+ int opIndex = -1;
+ try { opIndex = Integer.parseInt(opValue); } catch(Throwable t) {}
+ if(opIndex!=-1 && opIndex<opers.getItemCount()) opers.setSelectedIndex(opIndex);
+ }
+ }
+ }
+ InputData jf = null;
+// TODO : add JXDatePicker
+ if("date".equals(im.getDatatype())) {
+ jf = new MDateField(im);
+ ((MDateField)jf).setName("VALEUR:" + im.getId());
+ } else {
+ jf = new MTextField(im);
+ ((MTextField)jf).setName("VALEUR:" + im.getId());
+ ((MTextField)jf).setColumns(10);
+ // premier cas, un ... correspondant à un distinct-values(.../.../@V)
+ String helpPath = im.getHelpPath();
+ if(helpPath!=null) {
+ JHelpButton pbHelp = new JHelpButton((MTextField)jf,em,collectivite,budget, helpPath);
+ al.add(pbHelp);
+ }
+ // second cas, une recherche dans d'autres documents
+ if(im.getSearchHelper()!=null) {
+ SearchHelperModel shm = im.getSearchHelper();
+ JHelpButton pbHelp = new JHelpButton((MTextField)jf,em,collectivite, budget, shm);
+ al.add(pbHelp);
+ }
+ }
+ al.add((JComponent)jf);
+ // on regarde si il a une valeur par défaut
+ if(im.getValue()!=null) jf.setInputValue(im.getValue());
+ else if(MainWindow.getInstance().getCriteriaInputValue(im.getKeyName())!=null) {
+ jf.setInputValue(MainWindow.getInstance().getCriteriaInputValue(im.getKeyName()));
+ }
+ for (Component c : al) {
+ replaceMe.add(c);
+ if (c.getName() != null) {
+ inputs.put(c.getName(), (InputData)c);
+ orderedInputs.add((InputData)c);
+ }
+ }
+ } else if (xm instanceof SelectModel) {
+ SelectModel sm = (SelectModel)xm;
+ Collection<Pair> data = null;
+ ArrayList<FocusListener> focusListeners = new ArrayList<FocusListener>();
+ data = sm.getNewRecipient();
+ // 1 : est-ce que la liste dépend de la nomenclature
+ // si oui, regrarder si il faut mettre une liste comportant la liste des nomenclatures
+ if(sm.isDependantRepository()) {
+ try{
+ Vector<Pair> vRepository = DataLayerManager.getImplementation().getListeCodeLibelleRepository(dm,collectivite,parent.getUser());
+ if(vRepository.size()>1){
+ MComboBox mcb = new MComboBox(vRepository);
+ mcb.setName("ListRepository_"+sm.getId());
+ replaceMe.add(mcb);
+ // TODO : Foculistener des éléments de la combobox
+ MComboBox mcbListeCorresLibelle = remplirListe(sm,data,focusListeners);
+ mcb.addItemListener(new MComboBoxItemListener(this,sm,collectivite,mcb,mcbListeCorresLibelle));
+
+ }else{
+ remplirListe(sm,data,focusListeners);
+ }
+ } catch (Exception dbEx) {
+ Component comp2 = this;
+ while (comp2 != null && !(comp2 instanceof JFrame))
+ comp2 = comp2.getParent();
+ if (comp2 != null)
+ new DisplayExceptionDlg((JFrame)comp2, dbEx);
+ else dbEx.printStackTrace();
+ }
+ }else{
+ // 2 : mettre la liste
+ // debut de recherche des valeurs a mettre dans la liste
+ if (sm.getOptions() != null) {
+ for (OptionModel om : sm.getOptions()) {
+ data.add(new Pair(om.getValue(), om.getLibelle()));
+ }
+ }
+ for (RecherchePaireModel rpm : sm.getRecherches()) {
+ if (rpm.getPath() != null) {
+ // on fait une requete dans le referentiel pour
+ // remplir la liste
+ try {
+ Collection<Pair> localData = null;
+ localData = rpm.getNewRecipient();
+ localData.addAll(DataLayerManager.getImplementation().queryRepository(dm,collectivite,rpm,parent.getUser()));
+ data.addAll(localData);
+ } catch (Exception dbEx) {
+ Component comp2 = this;
+ while (comp2 != null && !(comp2 instanceof JFrame))
+ comp2 = comp2.getParent();
+ if (comp2 != null)
+ new DisplayExceptionDlg((JFrame)comp2, dbEx);
+ else dbEx.printStackTrace();
+ }
+ }
+ }
+ for(SpecialKeyEntryModel skem:sm.getSpecialKeys()) {
+ if(!skem.isDepends()) {
+ // si pas de dependance, on peut remplir maintenant
+ try {
+ data.addAll(DataLayerManager.getImplementation().getSpecialKeys1(dm,collectivite,budget,skem.isDistinct(),parent.getUser()));
+ } catch(DataAccessException daEx) {
+ new DisplayExceptionDlg(SwingUtilities.getWindowAncestor(this),daEx);
+ } catch(DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(SwingUtilities.getWindowAncestor(this),dcEx);
+ }
+ } else {
+ // il faut creer un FocusListener pour reinitialiser la liste a chaque fois
+ SpecialKeyFocusAdapter fl = new SpecialKeyFocusAdapter(this,skem,sm,collectivite,budget);
+ focusListeners.add(fl);
+ }
+ }
+ for(ResourceRefModel rrm:sm.getResources()) {
+ ResourceModel rm = dm.getResource(rrm.getRefId());
+ for(XmlMarshallable ob:rm.getData()) {
+ if(ob instanceof OptionModel) {
+ OptionModel om = (OptionModel)ob;
+ data.add(new Pair(om.getValue(), om.getLibelle()));
+ }
+ }
+ }
+ Vector<Pair> vData = new Vector<Pair>();
+ for (Pair p : data)
+ vData.add(p);
+ // fin de recherche des valeurs a mettre dans la liste
+ MComboBox cbxData = new MComboBox(vData,sm);
+ cbxData.setName("VALEUR:" + sm.getId());
+ if(!focusListeners.isEmpty()) {
+ for(FocusListener fl:focusListeners) cbxData.addFocusListener(fl);
+ }
+ if (sm.getLibelle() != null)
+ replaceMe.add(getLabel(sm.getLibelle()));
+ replaceMe.add(cbxData);
+ if(sm.getValue()!=null) {
+ Pair p = new Pair(sm.getValue(),"");
+ // les paires se compares uniquement par leurs clefs
+ cbxData.setSelectedItem(p);
+ }
+ inputs.put(cbxData.getName(), cbxData);
+ orderedInputs.add(cbxData);
+ }
+ } else {
+ logger.warn("classe non traitee: " + xm.getClass().getName());
+ }
+ }
+ // on regarde si il faut afficher le check box pour le champ optionnel
+ String idAffichage = cm.getIdAffichage();
+ if(idAffichage!=null && idAffichage.length()>0) {
+ chkDisplayOptionnal = new JCheckBox("Afficher le champ");
+ // if(option.isChecked()) chkDisplayOptionnal.setSelected(true);
+ if(cm.isDisplayOptional()) {
+ chkDisplayOptionnal.setSelected(true);
+ }
+ replaceMe.add(chkDisplayOptionnal);
+ } else {
+ chkDisplayOptionnal = null;
+ }
+
+ parent.repaintCriterias();
+ // on regarde si le critere a des valeurs
+ if(newCm.getValeurs()!=null) {
+ for(PropertyModel pm:newCm.getValeurs()) {
+ String key = pm.getName();
+ InputData id = inputs.get(key);
+ if(id==null) {
+ if(key.equals("AND_OR") && cbxAndOr!=null) {
+ Pair p = new Pair(pm.getValue(),"||".equals(pm.getValue())?"OU":"ET");
+ cbxAndOr.setSelectedItem(p);
+ } else {
+ logger.debug("id not found: "+key);
+ }
+ // id.setInputValue(pm.getValue());
+ } else {
+ if(id instanceof MComboBox) {
+ JComboBox cbx = (JComboBox)id;
+ if(cbx.isShowing()) {
+ cbx.dispatchEvent(new FocusEvent(cbx,FocusEvent.FOCUS_GAINED));
+ }
+ }
+ id.setInputValue(pm.getValue());
+ }
+ }
+ }
+ if(replaceMe.getComponentCount()==0) {
+ // c'est un titre, il faut le faire grandir au max
+ removeAll();
+ setLayout(new FlowLayout());
+ add(new JLabel(cm.getLibelle()));
+ }
+ } catch(UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(this,ex.getMessage(),"Droits insuffisants",JOptionPane.WARNING_MESSAGE);
+ }
+ }
+
+ private MComboBox remplirListe(SelectModel sm,Collection<Pair> data,ArrayList<FocusListener> focusListeners) {
+ try {
+ if (sm.getOptions() != null) {
+ for (OptionModel om : sm.getOptions()) {
+ data.add(new Pair(om.getValue(), om.getLibelle()));
+ }
+ }
+ for (RecherchePaireModel rpm : sm.getRecherches()) {
+ if (rpm.getPath() != null) {
+ // on fait une requete dans le referentiel pour
+ // remplir la liste
+ try {
+ Collection<Pair> localData = null;
+ localData = rpm.getNewRecipient();
+ localData.addAll(DataLayerManager.getImplementation().queryRepository(dm,collectivite,rpm,parent.getUser()));
+ data.addAll(localData);
+ } catch (Exception dbEx) {
+ Component comp2 = this;
+ while (comp2 != null && !(comp2 instanceof JFrame))
+ comp2 = comp2.getParent();
+ if (comp2 != null)
+ new DisplayExceptionDlg((JFrame)comp2, dbEx);
+ else dbEx.printStackTrace();
+ }
+ }
+ }
+ for(SpecialKeyEntryModel skem:sm.getSpecialKeys()) {
+ if (!skem.isDepends()) {
+ // si pas de dependance, on peut remplir maintenant
+ try {
+ data.addAll(DataLayerManager.getImplementation().getSpecialKeys1(dm, collectivite, budget,skem.isDistinct(),parent.getUser()));
+ } catch (DataAccessException daEx) {
+ new DisplayExceptionDlg(SwingUtilities.getWindowAncestor(this), daEx);
+ } catch (DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(SwingUtilities.getWindowAncestor(this), dcEx);
+ }
+ } else {
+ // il faut creer un FocusListener pour reinitialiser la liste a
+ // chaque fois
+ SpecialKeyFocusAdapter fl = new SpecialKeyFocusAdapter(this,
+ skem, sm, collectivite, budget);
+ focusListeners.add(fl);
+ }
+ }
+ for(ResourceRefModel rrm:sm.getResources()) {
+ ResourceModel rm = dm.getResource(rrm.getRefId());
+ for(XmlMarshallable ob:rm.getData()) {
+ if(ob instanceof OptionModel) {
+ OptionModel om = (OptionModel)ob;
+ data.add(new Pair(om.getValue(), om.getLibelle()));
+ }
+ }
+ }
+ Vector<Pair> vData = new Vector<Pair>();
+ for (Pair p : data)
+ vData.add(p);
+ // fin de recherche des valeurs a mettre dans la liste
+ MComboBox cbxData = new MComboBox(vData, sm);
+ cbxData.setName("VALEUR:" + sm.getId());
+ if (!focusListeners.isEmpty()) {
+ for (FocusListener fl : focusListeners)
+ cbxData.addFocusListener(fl);
+ }
+ if (sm.getLibelle() != null)
+ replaceMe.add(getLabel(sm.getLibelle()));
+ replaceMe.add(cbxData);
+ if (sm.getValue() != null) {
+ Pair p = new Pair(sm.getValue(), "");
+ // les paires se compares uniquement par leurs clefs
+ cbxData.setSelectedItem(p);
+ }
+ inputs.put(cbxData.getName(), cbxData);
+ orderedInputs.add(cbxData);
+ return cbxData;
+ } catch(UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(this,ex.getMessage(),"Droits insuffisants",JOptionPane.WARNING_MESSAGE);
+ return null;
+ }
+ }
+
+ private MComboBox refreshListe(SelectModel sm,Collection<Pair> data,ArrayList<FocusListener> focusListeners,Pair repository){
+ inputs.clear();
+ orderedInputs.clear();
+ for (RecherchePaireModel rpm : sm.getRecherches()) {
+ if (rpm.getPath() != null) {
+ // on fait une requete dans le referentiel pour
+ // remplir la liste
+ try {
+ Collection<Pair> localData = null;
+ localData = rpm.getNewRecipient();
+ localData.addAll(DataLayerManager.getImplementation().queryRepository(dm,collectivite,rpm,repository,parent.getUser()));
+ data.addAll(localData);
+ } catch (Exception dbEx) {
+ new DisplayExceptionDlg(SwingUtilities.getWindowAncestor(this), dbEx);
+ }
+ }
+ }
+ Vector<Pair> vData = new Vector<Pair>();
+ for (Pair p : data)
+ vData.add(p);
+ // fin de recherche des valeurs a mettre dans la liste
+ MComboBox cbxData = new MComboBox(vData, sm);
+ cbxData.setName("VALEUR:" + sm.getId());
+ if (!focusListeners.isEmpty()) {
+ for (FocusListener fl : focusListeners)
+ cbxData.addFocusListener(fl);
+ }
+ if (sm.getLibelle() != null)
+ replaceMe.add(getLabel(sm.getLibelle()));
+ replaceMe.add(cbxData);
+ if (sm.getValue() != null) {
+ Pair p = new Pair(sm.getValue(), "");
+ // les paires se compares uniquement par leurs clefs
+ cbxData.setSelectedItem(p);
+ }
+ inputs.put(cbxData.getName(), cbxData);
+ orderedInputs.add(cbxData);
+ return cbxData;
+ }
+
+
+ public static Component getLabel(String lbl) {
+ return iF.newLabel(lbl, "normal");
+ }
+
+ public boolean isOptionalDisplayChecked() {
+ boolean result = false;
+ if(chkDisplayOptionnal!=null) {
+ result = chkDisplayOptionnal.isSelected();
+ }
+ return result;
+ }
+
+ public String getXPathExpr() throws ToolException {
+ String expr = ((CritereModel)cbxTypeCritere.getSelectedItem()).getPath().getPath();
+ int ix = expr.indexOf("##");
+ while (ix >= 0) {
+ String sTmp = expr.substring(ix + 2);
+ int pos = sTmp.indexOf("##");
+ if (pos < 0)
+ throw new ToolException("Expression mal formee: " + expr, ToolException.ERROR_MALFORMED_XPATH_EXPR);
+ String middle = sTmp.substring(0, pos);
+ InputData id = inputs.get(middle);
+ if(id==null) {
+ throw new ToolException("input "+middle+" not found",ToolException.ERROR_MALFORMED_XPATH_EXPR);
+ }
+ if (id.getInputValue() == null || id.getInputValue().length() == 0) {
+ componentToFocus = (JComponent)id;
+ throw new ToolException("Le champ désigné par le curseur doit être rempli.", ToolException.ERROR_MISFILLED_CRITERIA);
+ }
+ if (id.getInputValue() != null && id.getInputValue().indexOf('"') >= 0) {
+ componentToFocus = (JComponent)id;
+ throw new ToolException("Le champ désigné par le curseur ne doit pas contenir de guillemets.", ToolException.ERROR_MISFILLED_CRITERIA);
+ }
+ if(id instanceof MTextField) {
+ MTextField df = (MTextField)id;
+ if("numeric".equals(df.getDatatype())) {
+ try { Float.parseFloat(df.getText()); } catch(NumberFormatException mfEx) {
+ throw new ToolException("Le champ désigné par le curseur doit contenir une valeur numérique.",ToolException.ERROR_MISFILLED_CRITERIA);
+ }
+ } else if("date".equals(df.getDatatype())) {
+ // verification de la valeur saisie : non vide, bien formattée, etc...
+ expr = expr.replace("##" + middle + "##", id.getXmlFormattedDate());
+ }
+ if(df.getMarshallModel() instanceof InputModel) {
+ InputModel im = (InputModel)df.getMarshallModel();
+ MainWindow.getInstance().setCriteriaInputValue(im.getKeyName(),df.isEditable()?id.getInputValue():null);
+ if(im.getDatatype()!=null && !im.hasToRemoveOperator()) {
+ InputData op = inputs.get("OPERATEUR:"+im.getId());
+ if(op instanceof MComboBox) {
+ MComboBox cbxOp = (MComboBox)op;
+ int selectedIx = cbxOp.getSelectedIndex();
+ MainWindow.getInstance().setCriteriaInputValue(im.getKeyName()+".OPERATEUR",Integer.toString(selectedIx));
+ }
+ }
+ }
+ } else if(id instanceof MDateField) {
+ expr = expr.replace("##"+middle+"##", id.getXmlFormattedDate());
+ }
+ expr = expr.replace("##" + middle + "##", id.getInputValue()); // .replaceAll("'","''")
+ ix = expr.indexOf("##");
+ }
+ expr = expr.replaceAll("\\{", "[").replaceAll("\\}", "]");
+ return expr;
+ }
+ public Hashtable<String,String> getParameters() throws ToolException {
+ Hashtable<String,String> ret = new Hashtable<String,String>();
+ for(Enumeration<InputData> enumer=inputs.elements();enumer.hasMoreElements();) {
+ InputData id = enumer.nextElement();
+ if (id.getInputValue() == null || id.getInputValue().length() == 0) {
+ componentToFocus = (JComponent)id;
+ throw new ToolException("Le champ désigné par le curseur doit être rempli.", ToolException.ERROR_MISFILLED_CRITERIA);
+ }
+ if (id.getInputValue() != null && id.getInputValue().indexOf('"') >= 0) {
+ componentToFocus = (JComponent)id;
+ throw new ToolException("Le champ désigné par le curseur ne doit pas contenir de guillemets.", ToolException.ERROR_MISFILLED_CRITERIA);
+ }
+ if(id instanceof MTextField) {
+ MTextField df = (MTextField)id;
+ if("numeric".equals(df.getDatatype())) {
+ try { Float.parseFloat(df.getText()); } catch(NumberFormatException mfEx) {
+ componentToFocus = df;
+ throw new ToolException("Le champ désigné par le curseur doit contenir une valeur numérique.",ToolException.ERROR_MISFILLED_CRITERIA);
+ }
+ } else if("date".equals(df.getDatatype())) {
+ try {
+ sdf.parse(df.getText());
+ } catch(ParseException pEx) {
+ componentToFocus=df;
+ throw new ToolException("Le champ désigné par le curseur doit contenir une date au format "+DATE_FORMAT,ToolException.ERROR_MISFILLED_CRITERIA);
+ }
+ }
+ }
+ String name = id.getName();
+ ret.put(name,id.getInputValue());
+ }
+ return ret;
+ }
+
+ public String getAndOrEr() {
+ if (hideRemoveIcon)
+ return "";
+ return ((Pair)(cbxAndOr.getSelectedItem())).key;
+ }
+
+ public void doFocusOnError() {
+ if (componentToFocus != null)
+ componentToFocus.grabFocus();
+ }
+ public XmlMarshallable getXmlMarshallable() {
+ currentCritereModel.getValeurs().removeAllElements();
+ currentCritereModel.removeAllProperties();
+ currentCritereModel.setDisplayOptional(isOptionalDisplayChecked());
+ if(cbxAndOr!=null && cbxAndOr.getSelectedItem()!=null) {
+ try {
+ currentCritereModel.addChild(new PropertyModel("AND_OR",((Pair)cbxAndOr.getSelectedItem()).key),PropertyModel.QN);
+ } catch(SAXException saxEx) { }
+ }
+ for(InputData id:orderedInputs) {
+ try {
+ currentCritereModel.addChild(new PropertyModel(id.getName(),id.getInputValue()),PropertyModel.QN);
+ } catch(SAXException saxEx) { }
+ }
+ return currentCritereModel;
+ }
+ public CritereModel getModel() {
+ return (CritereModel)getXmlMarshallable();
+ }
+ /**
+ * N'importe quoi dans lequel l'utilisateur peut saisir
+ */
+ public interface InputData {
+ public String getInputValue();
+ public void setInputValue(String data);
+ public XmlMarshallable getMarshallModel();
+ public String getName();
+ public String getXmlFormattedDate();
+ }
+// public abstract class InputField extends JComponent implements InputData { }
+ class MComboBox extends JComboBox implements InputData {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+ private SelectModel sm;
+ private Hashtable<String,Pair> innerData;
+
+ public MComboBox(Vector<Pair> data) { this(data,null); }
+ public MComboBox(Vector<Pair> data,SelectModel sm) {
+ super(data);
+ setEditable(false);
+ this.sm=sm;
+ if(sm!=null) addListener();
+ innerData = new Hashtable<String,Pair>();
+ for(Pair p:data) innerData.put(p.key,p);
+ }
+
+ public MComboBox(Pair[] data) { this(data,null); }
+ public MComboBox(Pair[] data,SelectModel sm) {
+ super(data);
+ setEditable(false);
+ this.sm=sm;
+ if(sm!=null) addListener();
+ innerData = new Hashtable<String,Pair>();
+ for(int i=0;i<data.length;i++) {
+ innerData.put(data[i].key,data[i]);
+ }
+ }
+ private void addListener() {
+ addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ if(getSelectedItem()!=null) {
+ MComboBox.this.sm.setValue(((Pair)getSelectedItem()).key);
+ }
+ }
+ });
+ }
+ @Override
+ public String getInputValue() {
+ Object item = getSelectedItem();
+ if (item == null)
+ return null;
+ if (item instanceof Pair) {
+ return ((Pair)item).key;
+ }
+ return item.toString();
+ }
+ @Override
+ public void setInputValue(String data) {
+ if(getItemCount()==0) grabFocus();
+ Pair p = innerData.get(data);
+ if(p==null) {
+ p = new Pair(data,data);
+ addItem(p);
+ }
+ if(p!=null) setSelectedItem(p);
+ }
+ @Override
+ public XmlMarshallable getMarshallModel() {
+ if(sm==null) return null;
+ sm.setValue(getInputValue());
+ return sm;
+ }
+ @Override
+ public String getXmlFormattedDate(){
+ return "";
+ }
+ public void setData(Vector<Pair> vpair){
+ removeAllItems();
+ for(int i=0;i<vpair.size();i++) {
+ addItem(vpair.get(i));
+ innerData.put(vpair.get(i).key,vpair.get(i));
+ }
+ }
+ }
+
+ class MTextField extends JTextField implements InputData {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+ private InputModel im;
+
+ public MTextField(InputModel im) {
+ super();
+ this.im=im;
+ if(im.isUppercase()) setDocument(new UppercaseFilteredField());
+ else if("date".equals(im.getDatatype())) {
+ setDocument(new DateFilteredField());
+ addFocusListener(new FocusListener() {
+ @Override
+ public void focusGained(FocusEvent e) {
+ }
+ @Override
+ public void focusLost(FocusEvent e) {
+ try {
+ Date d = sdf.parse(getText());
+ setText(sdf.format(d));
+ } catch(Throwable t) { }
+ }
+
+ });
+ }
+ if(im!=null) {
+ addCaretListener(new CaretListener() {
+ @Override
+ public void caretUpdate(CaretEvent e) {
+ MTextField.this.im.setValue(getText());
+ }
+ });
+ }
+ }
+ @Override
+ public String getXmlFormattedDate(){
+ SimpleDateFormat sdfxml = new SimpleDateFormat(im.getXmlDateFormat());
+ try {
+ Date d = sdf.parse(getText());
+ return sdfxml.format(d);
+ } catch (Throwable t) {
+
+ }
+ return null;
+ }
+ public String getDatatype() { return im.getDatatype(); }
+
+ @Override
+ public String getInputValue() {
+ return getText();
+ }
+ @Override
+ public void setInputValue(String data){
+ setText(data);
+ }
+ @Override
+ public XmlMarshallable getMarshallModel() {
+ im.setValue(getInputValue());
+ return im;
+ }
+ @SuppressWarnings("empty-statement")
+ public Date getDate() {
+ if(getDatatype().equals("date"))
+ try {
+ return sdf.parse(getText());
+ } catch(Throwable t) {};
+ return null;
+ }
+ }
+
+ class MDateField extends JXDatePicker implements InputData {
+ private InputModel im;
+ private Date currentDate;
+
+ public MDateField(InputModel im) {
+ super();
+ this.im=im;
+ ActionListener l = new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ if (JXDatePicker.COMMIT_KEY.equals(e.getActionCommand())) {
+ saveDate(getDate());
+ }
+ }
+ };
+ addActionListener(l);
+ PropertyChangeListener listener = new PropertyChangeListener() {
+ @Override
+ public void propertyChange(PropertyChangeEvent e) {
+ if ("date".equals(e.getPropertyName())) {
+ saveDate(getDate());
+ }
+ }
+ };
+ addPropertyChangeListener(listener);
+// TreeSet<String> formats = new TreeSet<String>();
+// formats.add(DATE_FORMAT);
+// formats.add("dd-MM-yyyy");
+// formats.add("EEE dd MMM yyyy");
+ setFormats(DATE_FORMAT, "dd-MM-yyyy", "EEE dd MMM yyyy");
+ }
+ private void saveDate(Date date) {
+ currentDate = date;
+ }
+ @Override
+ public String getInputValue() {
+ if(currentDate!=null) {
+ return sdf.format(getDate());
+ } else
+ return null;
+ }
+
+ @Override
+ public void setInputValue(String data) {
+ try {
+ Date date = sdf.parse(data);
+ setDate(date);
+ } catch(ParseException pEx) {
+ logger.info(data+" is not a valid date to format "+DATE_FORMAT);
+ }
+ }
+
+ @Override
+ public XmlMarshallable getMarshallModel() {
+ im.setValue(getInputValue());
+ return im;
+ }
+
+ @Override
+ public String getXmlFormattedDate() {
+ SimpleDateFormat sdfxml = new SimpleDateFormat(im.getXmlDateFormat());
+ try {
+ return sdfxml.format(currentDate);
+ } catch (Throwable t) {
+
+ }
+ return null;
+ }
+
+ }
+ private class UppercaseFilteredField extends PlainDocument {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
+ if (str == null)
+ return;
+
+ str = str.toUpperCase();
+
+ super.insertString(offset, str, attr);
+ }
+
+ }
+ private class DateFilteredField extends PlainDocument {
+ private static final long serialVersionUID = 2758758288192923608L;
+ private String format = null;
+ public DateFilteredField(String format) {
+ super();
+ this.format=format;
+ }
+ public DateFilteredField() {
+ this(DATE_FORMAT);
+ }
+ public String getFormat() { return format; }
+ @Override
+ public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
+ if (str == null) {
+ logger.debug("str is null");
+ return;
+ }
+ if (getFormat() == null || getFormat().length() == 0) {
+ logger.debug("format is null");
+ return;
+ }
+ if (offset >= getFormat().length()) {
+ logger.debug("length > format");
+ return;
+ }
+ char aChar = str.charAt(0);
+ char fChar = getFormat().charAt(offset);
+ if (Character.isDigit(aChar) == Character.isLetter(fChar)) {
+ if (!Character.isLetterOrDigit(fChar)) {
+ // if char is not a number
+ logger.debug(fChar+" is not a number");
+ } else {
+ super.insertString(offset, str, attr);
+ offset++;
+ if (offset < getFormat().length()) {
+ char bChar = getFormat().charAt(offset);
+ String sChar = Character.toString(bChar);
+ // if the next char in the format is not a digit append the sign.
+ if (!Character.isLetterOrDigit(bChar) && !sChar.equals(getText(offset, 1))) {
+ super.insertString(offset, sChar, attr);
+ }
+ }
+ }
+ }
+ }
+
+
+ /**
+ * This method was created in VisualAge.
+ * @param offset int
+ * @param len int
+ */
+ @Override
+ public void remove(int offset, int len) throws BadLocationException {
+ if (getFormat() == null || getFormat().length() == 0) {
+ return;
+ }
+ //
+ //
+ super.remove(offset, len);
+ char bChar = getFormat().charAt(offset);
+ // if the next char in the format is not a digit append the sign.
+ if (!Character.isLetterOrDigit(bChar)) {
+ super.remove(--offset, 1);
+ }
+ }
+ }
+ private class JHelpButton extends JButton {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+ private MTextField targetField;
+ private Pair collectivite,budget;
+ private ElementModel em;
+ private String path;
+ SearchHelperModel shm;
+
+ JHelpButton(MTextField targetField, ElementModel elementModel, Pair collectivite, Pair budget, String path) {
+ super("...");
+ this.targetField = targetField;
+ this.em=elementModel;
+ this.collectivite=collectivite;
+ this.budget=budget;
+ this.path = path;
+ __initialize();
+ }
+ JHelpButton(MTextField targetField, ElementModel elementModel, Pair collectivite, Pair budget, SearchHelperModel shm) {
+ super("...");
+ this.targetField = targetField;
+ this.em=elementModel;
+ this.collectivite=collectivite;
+ this.budget=budget;
+ this.shm = shm;
+ __initialize();
+ }
+
+ private void __initialize() {
+ Dimension fieldSize = targetField.getPreferredSize();
+ setPreferredSize(new Dimension((int)fieldSize.getHeight(),(int)fieldSize.getHeight()));
+ setToolTipText("Liste des éléments");
+ addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ JHelpButton.this.displayHelpBox();
+ }
+ });
+ }
+
+ protected void displayHelpBox() {
+ if(shm==null) {
+ TreeSet<String> values = new TreeSet<String>();
+ try {
+ setCursor(new Cursor(Cursor.WAIT_CURSOR));
+ values.addAll(DataLayerManager.getImplementation().getDistinctValues(em,collectivite,budget,path,parent.getUser()));
+ Container c = CriteriaViewer.this.parent;
+ while(c!=null && !(c instanceof JFrame)) {
+ c = c.getParent();
+ }
+ JFrame parent = (JFrame)c;
+ DlgSelectFromList dsfl = new DlgSelectFromList(parent,values);
+ if(dsfl.run()) {
+ targetField.setInputValue(dsfl.getSelectedValue());
+ }
+ } catch(Throwable t) {
+ Container c = CriteriaViewer.this.parent;
+ while(c!=null && !(c instanceof JFrame)) {
+ c = c.getParent();
+ }
+ new DisplayExceptionDlg((JFrame)c,t);
+ } finally {
+ setCursor(Cursor.getDefaultCursor());
+ }
+ } else {
+ SearchContext sCtx = parent.getSearchContext();
+ DlgSearchHelper dlg = new DlgSearchHelper(SwingUtilities.getWindowAncestor(this), targetField, shm, sCtx);
+ dlg.setVisible(true);
+ }
+ }
+ }
+ private class SpecialKeyFocusAdapter extends FocusAdapter {
+ private CriteriaViewer cv;
+ private SelectModel sm;
+ private SpecialKeyEntryModel skem;
+ private DocumentModel dm;
+ private Pair collectivite,budget;
+ public SpecialKeyFocusAdapter(CriteriaViewer cv, SpecialKeyEntryModel skem, SelectModel sm,Pair collectivite, Pair budget) {
+ super();
+ this.cv=cv;
+ this.skem=skem;
+ this.sm = sm;
+ this.collectivite=collectivite;
+ this.budget=budget;
+ dm = cv.dm;
+ }
+ @Override
+ public void focusGained(FocusEvent evt) {
+ JComboBox cbx = (JComboBox)evt.getSource();
+ cbx.removeFocusListener(this);
+ cbx.removeAllItems();
+ Vector<Pair> data=new Vector<Pair>();
+ try {
+ if (sm.getOptions() != null) {
+ for (OptionModel om : sm.getOptions()) {
+ data.add(new Pair(om.getValue(), om.getLibelle()));
+ }
+ }
+ for(ResourceRefModel rrm:sm.getResources()) {
+ ResourceModel rm = dm.getResource(rrm.getRefId());
+ for(XmlMarshallable ob:rm.getData()) {
+ if(ob instanceof OptionModel) {
+ OptionModel om = (OptionModel)ob;
+ data.add(new Pair(om.getValue(), om.getLibelle()));
+ }
+ }
+ }
+ for (RecherchePaireModel rpm : sm.getRecherches()) {
+ if (rpm.getPath() != null) {
+ // on fait une requete dans le referentiel pour
+ // remplir la liste
+ try {
+ data.addAll(DataLayerManager.getImplementation().queryRepository(dm,collectivite,rpm,parent.getUser()));
+ } catch (Exception dbEx) {
+ new DisplayExceptionDlg(SwingUtilities.getWindowAncestor(CriteriaViewer.this), dbEx);
+ }
+ }
+ }
+ // il y a des dependances, on recherche les ##VALEUR:id##
+ String key1=null, key2=null;
+ String path = skem.getKey1().getData();
+ String itemName = path.substring(2,path.length()-2);
+ InputData id = cv.inputs.get(itemName);
+ if (id.getInputValue() != null && id.getInputValue().length() > 0) {
+ key1 = id.getInputValue();
+ }
+ Collection<Pair> tmp = sm.getNewRecipient();
+ if(skem.getPos()==2) {
+ // we can search here
+ tmp.addAll(DataLayerManager.getImplementation().getSpecialKeys2(dm,collectivite,budget,new Pair(key1,key1),skem.isDistinct(),parent.getUser()));
+ } else {
+ path = skem.getKey1().getData();
+ itemName = path.substring(2,path.length()-2);
+ id = cv.inputs.get(itemName);
+ if (id.getInputValue() != null && id.getInputValue().length() > 0) {
+ key2 = id.getInputValue();
+ }
+ tmp.addAll(DataLayerManager.getImplementation().getSpecialKeys3(dm,collectivite,budget,new Pair(key1,key1),new Pair(key2,key2),skem.isDistinct(),parent.getUser()));
+ }
+ data.addAll(tmp);
+ for(Pair p:data) cbx.addItem(p);
+ cbx.setPopupVisible(true);
+ cbx.grabFocus();
+ cbx.addFocusListener(this);
+ } catch(UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(CriteriaViewer.this,ex.getMessage(),"Droits insuffisants",JOptionPane.WARNING_MESSAGE);
+ } catch(DataConfigurationException dcEx) {
+ // TODO : attention au probleme de focus en boucle
+ logger.error("dans focusGained",dcEx);
+ } catch(DataAccessException daEx) {
+ // TODO : attention au probleme de focus en boucle
+ logger.error("dans focusGained",daEx);
+ }
+ }
+ }
+
+ private class MComboBoxItemListener implements ItemListener {
+ private SelectModel sm;
+ private DocumentModel dm;
+ private Pair collectivite;
+ private MComboBox mcb,mcbListeCorresLib;
+
+ public MComboBoxItemListener(CriteriaViewer cv,SelectModel sm,Pair collectivite,MComboBox mcbox,MComboBox mcboxListeCorrsLib) {
+ super();
+ this.sm = sm;
+ this.collectivite=collectivite;
+ dm = cv.dm;
+ this.mcb=mcbox;
+ this.mcbListeCorresLib=mcboxListeCorrsLib;
+ }
+
+
+ @Override
+ public void itemStateChanged(ItemEvent evt){
+ try {
+ Pair repository = (Pair)mcb.getSelectedItem();
+ Vector<Pair> vRepository = (Vector<Pair>)DataLayerManager.getImplementation().queryRepository(dm,collectivite,sm.getRecherches().get(0),repository,parent.getUser());
+ mcbListeCorresLib.setData(vRepository);
+ } catch(UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(CriteriaViewer.this,ex.getMessage(),"Droits insuffisants",JOptionPane.WARNING_MESSAGE);
+ } catch (DataConfigurationException e) {
+ e.printStackTrace();
+ } catch (DataAccessException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ private class JFocusableLabel extends JLabel {
+
+ public JFocusableLabel(Icon icon, Action act) {
+ super(icon);
+ setFocusable(true);
+ setBorder(new EmptyBorder(2,2,2,2));
+ getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE,0), "CLICK");
+ getActionMap().put("CLICK", act);
+ addFocusListener(new FocusAdapter() {
+
+ @Override
+ public void focusGained(FocusEvent e) {
+ ((JFocusableLabel)e.getComponent()).paintFocus();
+ }
+
+ @Override
+ public void focusLost(FocusEvent e) {
+ ((JFocusableLabel)e.getComponent()).paintFocus();
+ }
+
+ });
+ addMouseListener(new MouseAdapter() {
+
+ @Override
+ public void mousePressed(MouseEvent e) {
+ requestFocus();
+ }
+
+ });
+ }
+ @Override
+ protected void paintComponent(Graphics g) {
+ super.paintComponent(g);
+ paintFocus(g);
+ }
+ protected void paintFocus(Graphics g) {
+ if(g==null) return;
+ if(isFocusOwner()) {
+ g.setColor(UIManager.getColor("Button.focus"));
+ } else {
+ g.setColor(UIManager.getColor("Label.background"));
+ }
+ g.drawRect(0, 0, getWidth()-1, getHeight()-1);
+ }
+ protected void paintFocus() { paintFocus(getGraphics()); }
+
+
+ @Override
+ protected void processFocusEvent(FocusEvent e) {
+ super.processFocusEvent(e);
+ invalidate();
+ }
+
+ }
+ public void setInputValue(String inputId,String value) {
+ InputData id = inputs.get(inputId);
+ if(id!=null) id.setInputValue(value);
+ }
+ public CritereModel getCurrentCritereModel() {
+ return currentCritereModel;
+ }
+ public boolean isHideRemoveIcon() {
+ return hideRemoveIcon;
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 N.Le Corre - nicolas.lecorre@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui;
+
+import fr.gouv.finances.dgfip.xemelios.data.*;
+import java.util.Vector;
+
+import javax.swing.event.TableModelEvent;
+
+import org.jdesktop.swingx.JXTable;
+import org.jdesktop.swingx.treetable.AbstractTreeTableModel;
+
+public class DatabaseTreeDataFichier extends AbstractTreeTableModel {
+ private JXTable table;
+ private String[] columnNames = new String [] { "", "" };
+ private ExportableData data = new ExportableData();
+ private boolean selectionMultiple = true;
+ private int mode;
+
+ public int getMode() {
+ return mode;
+ }
+ public void setMode(int mode) {
+ this.mode = mode;
+ }
+ public boolean isSelectionMultiple() {
+ return selectionMultiple;
+ }
+ public void setSelectionMultiple(boolean selectionMultiple) {
+ this.selectionMultiple = selectionMultiple;
+ }
+ public DatabaseTreeDataFichier (JXTable table) {
+ super();
+ this.table = table;
+ }
+ public DatabaseTreeDataFichier (Vector<ExportableData> d, JXTable table) {
+ super();
+ this.table=table;
+ if (d!=null && d.size()>0) {
+ data.setLibelle("Documents");
+ data.setChilds(d);
+ }
+ else {
+ data.setLibelle("Aucun fichier ne correspond aux critères de recherche.");
+ }
+ data.setSelected(false);
+ }
+
+ @Override
+ public boolean isLeaf(Object node) {
+ return (((ExportableData)node).getChilds().size()==0);
+ }
+
+ @Override
+ public Class getColumnClass(int i) {
+ if (i==0) return super.getColumnClass(i);
+ else if (i==1) return Boolean.class;
+ else return super.getColumnClass(i);
+ }
+
+ public Object getValueAt(Object object, int i) {
+ if (i==0) return ((ExportableData)object).getLibelle();
+ else if (i==1) return new Boolean(((ExportableData)object).isSelected());
+ else return "";
+ }
+
+ @Override
+ public void setValueAt(Object value, Object node, int column) {
+ if (column==1) {
+ if (selectionMultiple) {
+ ((ExportableData)node).setSelected(((Boolean)value).booleanValue());
+ }
+ else if (((Boolean)value).booleanValue()) {
+ resetValue(data);
+ ((ExportableData)node).setSelected(((Boolean)value).booleanValue());
+ if(table!=null) table.tableChanged(new TableModelEvent(table.getModel()));
+ }
+ }
+ }
+
+ private void resetValue(ExportableData data) {
+ data.setSelected(false);
+ for (ExportableData d:data.getChilds()) {
+ resetValue(d);
+ }
+ }
+
+ public int getChildCount(Object parent) {
+ return ((ExportableData)parent).getChilds().size();
+ }
+
+ public Object getChild(Object parent, int index) {
+ return ((ExportableData)parent).getChild(index);
+ }
+
+ @Override
+ public boolean isCellEditable(Object object, int i) {
+ if (mode==PanelChooseDatabaseFichier.MODE_EXPORT) {
+ if ((((ExportableData)object).getLevel()==ExportableData.LVL_BUD || ((ExportableData)object).getLevel()==ExportableData.LVL_FIC) && i==1)
+ return true;
+ else
+ return false;
+ } else {
+ if (object != getRoot() && i==1)
+ return true;
+ else
+ return false;
+ }
+ }
+
+ public int getIndexOfChild(Object parent, Object child) {
+ int i=0;
+ for (ExportableData c:((ExportableData)parent).getChilds()) {
+ if (c.getKey().equals(((ExportableData)child).getKey())) return i;
+ i++;
+ }
+ return -1;
+ }
+
+ @Override
+ public Object getRoot() {
+// return (datas.size()>0?datas.get(0):null);
+ return data;
+ }
+
+ public int getColumnCount() { return columnNames.length; }
+
+ @Override
+ public String getColumnName(int arg0) {
+ return columnNames[arg0];
+ }
+
+// public void addData(Data d) {
+// datas.add(d);
+// }
+
+// public static class Data {
+// }
+
+ public ExportableData getData() {
+ return data;
+ }
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.3" maxVersion="1.3" type="org.netbeans.modules.form.forminfo.JDialogFormInfo">
+ <Properties>
+ <Property name="defaultCloseOperation" type="int" value="2"/>
+ </Properties>
+ <SyntheticProperties>
+ <SyntheticProperty name="formSizePolicy" type="int" value="1"/>
+ </SyntheticProperties>
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="2"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="1" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="1" attributes="0">
+ <Component id="jTabbedPane1" alignment="1" pref="636" max="32767" attributes="0"/>
+ <Group type="102" alignment="1" attributes="0">
+ <Component id="bFermer" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="bAction" min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" attributes="0">
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Component id="jTabbedPane1" pref="456" max="32767" attributes="0"/>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="bAction" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="bFermer" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Container class="javax.swing.JTabbedPane" name="jTabbedPane1">
+ <AuxValues>
+ <AuxValue name="JavaCodeGenerator_CreateCodePost" type="java.lang.String" value="if(this.dialogType==DIALOG_TYPE.DATA || this.dialogType==DIALOG_TYPE.BOTH)
 jTabbedPane1.addTab("Par données", new PanelChooseDatabaseDonnees(this,dm,user,applicationConfiguration));
if(this.dialogType==DIALOG_TYPE.FILE || this.dialogType==DIALOG_TYPE.BOTH)
 jTabbedPane1.addTab("Par fichier", new PanelChooseDatabaseFichier(this,dm,false,user,applicationConfiguration));"/>
+ </AuxValues>
+
+ <Layout class="org.netbeans.modules.form.compat2.layouts.support.JTabbedPaneSupportLayout"/>
+ </Container>
+ <Component class="javax.swing.JButton" name="bFermer">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Fermer"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="bFermerActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="bAction">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Action"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="bActionActionPerformed"/>
+ </Events>
+ </Component>
+ </SubComponents>
+</Form>
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 N.Le Corre - nicolas.lecorre@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui;
+
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentsModel;
+import fr.gouv.finances.dgfip.xemelios.data.WaitableUI;
+import fr.gouv.finances.dgfip.xemelios.swing.InfiniteGlassPane;
+import java.awt.Cursor;
+
+/**
+ *
+ * @author nicolas.lecorre
+ */
+public abstract class DlgChooseDocuments extends javax.swing.JDialog implements WaitableUI {
+
+ public static enum DIALOG_TYPE { FILE, DATA, BOTH };
+ private DocumentsModel dm;
+ private boolean selectionMultiple = true;
+ private XemeliosUser user;
+ private PropertiesExpansion applicationConfiguration;
+ private DIALOG_TYPE dialogType;
+
+ public void setBActionLibelle(String actionLibelle) {
+ bAction.setText(actionLibelle);
+ }
+
+ /**
+ * La méthode appelée lors du click sur le bouton "action" en bas à droite.
+ * Cela peut être la suppression, l'export, ...
+ * @param evt
+ */
+ protected abstract void doAction(java.awt.event.ActionEvent evt);
+
+ /** Creates new form DlgChooseDocuments */
+ public DlgChooseDocuments(
+ java.awt.Frame parent,
+ boolean modal,
+ DocumentsModel _dm,
+ boolean selectionMultiple,
+ DIALOG_TYPE dialogType,
+ XemeliosUser user,
+ PropertiesExpansion applicationConfiguration) {
+ super(parent, modal);
+ this.user = user;
+ this.selectionMultiple = selectionMultiple;
+ this.dialogType = dialogType;
+ this.applicationConfiguration = applicationConfiguration;
+ this.setDm(_dm);
+ initComponents();
+ setLocationRelativeTo(getParent());
+ setGlassPane(new InfiniteGlassPane());
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ jTabbedPane1 = new javax.swing.JTabbedPane();
+ if(this.dialogType==DIALOG_TYPE.DATA || this.dialogType==DIALOG_TYPE.BOTH)
+ jTabbedPane1.addTab("Par données", new PanelChooseDatabaseDonnees(this,dm,user,applicationConfiguration));
+ if(this.dialogType==DIALOG_TYPE.FILE || this.dialogType==DIALOG_TYPE.BOTH)
+ jTabbedPane1.addTab("Par fichier", new PanelChooseDatabaseFichier(this,dm,false,user,applicationConfiguration));
+ bFermer = new javax.swing.JButton();
+ bAction = new javax.swing.JButton();
+
+ setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+
+ bFermer.setText("Fermer");
+ bFermer.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ bFermerActionPerformed(evt);
+ }
+ });
+
+ bAction.setText("Action");
+ bAction.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ bActionActionPerformed(evt);
+ }
+ });
+
+ org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
+ .addContainerGap()
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
+ .add(jTabbedPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 636, Short.MAX_VALUE)
+ .add(layout.createSequentialGroup()
+ .add(bFermer)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(bAction)))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(jTabbedPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 456, Short.MAX_VALUE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(bAction)
+ .add(bFermer))
+ .addContainerGap())
+ );
+
+ pack();
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void bActionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bActionActionPerformed
+ doAction(evt);
+ }//GEN-LAST:event_bActionActionPerformed
+
+ private void bFermerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bFermerActionPerformed
+ this.dispose();
+ }//GEN-LAST:event_bFermerActionPerformed
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JButton bAction;
+ private javax.swing.JButton bFermer;
+ private javax.swing.JTabbedPane jTabbedPane1;
+ // End of variables declaration//GEN-END:variables
+
+ public DocumentsModel getDm() {
+ return dm;
+ }
+
+ public void setDm(DocumentsModel dm) {
+ this.dm = dm;
+ }
+
+ public javax.swing.JTabbedPane getJTabbedPane1() {
+ return jTabbedPane1;
+ }
+
+ public void enableButtons(boolean enable) {
+ this.bAction.setEnabled(enable);
+ this.bFermer.setEnabled(enable);
+ }
+
+ @Override
+ public void startWait() {
+ setCursor(new Cursor(Cursor.WAIT_CURSOR));
+ }
+
+ @Override
+ public void stopWait() {
+ setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 N.Le Corre - nicolas.lecorre@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui;
+
+import java.awt.Cursor;
+import java.awt.event.ActionEvent;
+import java.util.HashMap;
+import java.util.StringTokenizer;
+
+import javax.swing.JOptionPane;
+import javax.swing.tree.TreePath;
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathConstants;
+import javax.xml.xpath.XPathExpressionException;
+import javax.xml.xpath.XPathFactory;
+
+import org.apache.log4j.Logger;
+import org.jdesktop.swingworker.SwingWorker;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+
+import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.dgfip.utils.XmlUtils;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
+import fr.gouv.finances.dgfip.xemelios.auth.UnauthorizedException;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentsModel;
+import fr.gouv.finances.dgfip.xemelios.data.DataAccessException;
+import fr.gouv.finances.dgfip.xemelios.data.DataConfigurationException;
+import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
+import fr.gouv.finances.dgfip.xemelios.data.DatabaseTreeDataDonnee;
+import fr.gouv.finances.dgfip.xemelios.data.DatabaseTreeDataDonnee.DataNode;
+import fr.gouv.finances.dgfip.xemelios.data.ExportableData;
+import fr.gouv.finances.dgfip.xemelios.data.WaitableUI;
+import fr.gouv.finances.dgfip.xemelios.importers.AbstractImportPatcherImpl;
+
+@SuppressWarnings("serial")
+public class DlgCleanDatabase extends DlgChooseDocuments implements WaitableUI {
+
+ private static Logger logger = Logger.getLogger(DlgCleanDatabase.class);
+ private XemeliosUser user;
+
+ public DlgCleanDatabase(java.awt.Frame parent, boolean modal, DocumentsModel _dm, DlgChooseDocuments.DIALOG_TYPE dialogType, XemeliosUser user) {
+ super(parent, modal, _dm, true, dialogType, user, MainWindow.getInstance().getEnvProperties());
+ this.user = user;
+ setTitle("Suppression");
+ setBActionLibelle("Supprimer");
+ setVisible(true);
+ }
+
+ @Override
+ protected void doAction(ActionEvent evt) {
+ if (getJTabbedPane1().getSelectedComponent() instanceof PanelChooseDatabaseDonnees) {
+ purge(((PanelChooseDatabaseDonnees) getJTabbedPane1().getSelectedComponent()).getJTree1().getSelectionPath());
+ }
+ if (getJTabbedPane1().getSelectedComponent() instanceof PanelChooseDatabaseFichier) {
+ purgeFichiers();
+ }
+ }
+
+ /**
+ * SUPPRESSION PAR FICHIER
+ */
+ protected void purgeFichiers() {
+ if (JOptionPane.showConfirmDialog(this, "Etes-vous sur de vouloir supprimer les informations définitivement ?\n\nCette opération peut prendre beaucoup de temps\nsi le nombre d'éléments à supprimer est important.", "Suppression", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
+ ExportableData datas = ((PanelChooseDatabaseFichier) getJTabbedPane1().getSelectedComponent()).getData().getData();
+ for (ExportableData d : datas.getChilds()) {
+// logger.debug("avant :\n"+d);
+ inspectSelectionOfChilds(d);
+// logger.debug("après:\n"+d);
+ purgeData(d);
+ }
+ }
+ }
+
+ protected boolean inspectSelectionOfChilds(ExportableData d) {
+ if (d.getChilds().size() == 0) {
+ return d.isSelected();
+ } else {
+ boolean hasAllChildsSelected = true;
+ for (ExportableData dd : d.getChilds()) {
+ hasAllChildsSelected &= inspectSelectionOfChilds(dd);
+ }
+ d.setSelected(d.isSelected() || hasAllChildsSelected);
+ return hasAllChildsSelected;
+ }
+ }
+
+ protected void purgeData(ExportableData datas) {
+ // Si l'on veux supprimer ce niveau
+ if (datas.isSelected()) {
+ doSuppressData(datas);
+ } else {
+ for (ExportableData d : datas.getChilds()) {
+ purgeData(d);
+ }
+ }
+ }
+
+ public void doSuppressData(ExportableData d) {
+ Runnable process = null;
+ // suppression selon le niveau
+ switch (d.getLevel()) {
+ case ExportableData.LVL_DOC: {
+ final DocumentModel dm = getDm().getDocumentById(d.getKey());
+ logger.debug("deleting DOC : " + dm.getId());
+ process = new Runnable() {
+
+ @Override
+ public void run() {
+ try {
+ getGlassPane().setVisible(true);
+ DataLayerManager.getImplementation().removeDocumentModel(dm, user);
+ } catch (UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(getParent(), ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (DataAccessException daEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, daEx);
+ } catch (DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, dcEx);
+ } finally {
+ getGlassPane().setVisible(false);
+ }
+ }
+ };
+ break;
+ }
+ case ExportableData.LVL_COL: {
+ StringTokenizer st = new StringTokenizer(d.getKey(), "|");
+ final DocumentModel dm = getDm().getDocumentById(st.nextToken());
+ final Pair collectivite = new Pair(st.nextToken(), "");
+ logger.debug("deleting COL : " + dm.getId() + ", " + collectivite.key);
+ process = new Runnable() {
+
+ @Override
+ public void run() {
+ try {
+ getGlassPane().setVisible(true);
+ DataLayerManager.getImplementation().removeCollectivite(dm, collectivite, user);
+ } catch (UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(getParent(), ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (DataAccessException daEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, daEx);
+ } catch (DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, dcEx);
+ } finally {
+ getGlassPane().setVisible(false);
+ }
+ }
+ };
+ break;
+ }
+ case ExportableData.LVL_BUD: {
+ StringTokenizer st = new StringTokenizer(d.getKey(), "|");
+ final DocumentModel dm = getDm().getDocumentById(st.nextToken());
+ final Pair collectivite = new Pair(st.nextToken(), "");
+ final Pair budget = new Pair(st.nextToken(), "");
+ logger.debug("deleting BUD : " + dm.getId() + ", " + collectivite.key + ", " + budget.key);
+ process = new Runnable() {
+
+ @Override
+ public void run() {
+ try {
+ getGlassPane().setVisible(true);
+ DataLayerManager.getImplementation().removeBudget(dm, collectivite, budget, user);
+ } catch (UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(getParent(), ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (DataAccessException daEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, daEx);
+ } catch (DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, dcEx);
+ } finally {
+ getGlassPane().setVisible(false);
+ }
+ }
+ };
+ break;
+ }
+ case ExportableData.LVL_FIC: {
+ StringTokenizer st = new StringTokenizer(d.getKey(), "|");
+ final DocumentModel dm = getDm().getDocumentById(st.nextToken());
+ final Pair collectivite = new Pair(st.nextToken(), "");
+ final Pair budget = new Pair(st.nextToken(), "");
+ final String fichier = st.nextToken();
+ logger.debug("deleting FIC : " + dm.getId() + ", " + collectivite.key + ", " + budget.key + ", " + fichier);
+ process = new Runnable() {
+
+ @Override
+ public void run() {
+ try {
+ getGlassPane().setVisible(true);
+ DataLayerManager.getImplementation().removeFichier(dm, fichier, user);
+ } catch (UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(getParent(), ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (DataAccessException daEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, daEx);
+ } catch (DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, dcEx);
+ } finally {
+ getGlassPane().setVisible(false);
+ }
+ }
+ };
+ break;
+ }
+ }
+ if (process != null) {
+ logger.debug("deleting");
+ SwingWorker deleter = new Deleter(process, this);
+ deleter.execute();
+ }
+ }
+
+ /**
+ * SUPPRESSION PAR DONNEES
+ */
+ /**
+ * Netoie la base a partir du chemin specifie
+ * @param tp Le chemin a nettoyer
+ * @return <tt>true</tt> s'il faut rafraichir l'arbre
+ */
+ protected void purge(TreePath tp) {
+ if (tp == null) {
+ return;
+ }
+ DatabaseTreeDataDonnee.DataNode node = (DatabaseTreeDataDonnee.DataNode) tp.getLastPathComponent();
+ if (node.getType() == DataNode.TYPE_ARCHIVE && JOptionPane.showConfirmDialog(this, "Etes-vous sur de vouloir supprimer toutes les données\nconcernant l'archive " + node + " définitivement ?\n\nCette opération peut prendre beaucoup de temps\nsi le nombre d'éléments à supprimer est important.", "Suppression", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
+ purge(node);
+ } else if (JOptionPane.showConfirmDialog(this, "Etes-vous sur de vouloir supprimer les informations\nconcernant " + node + " définitivement ?\n\nCette opération peut prendre beaucoup de temps\nsi le nombre d'éléments à supprimer est important.", "Suppression", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
+ purge(node);
+ }
+ }
+
+ /**
+ * Nettoie la base a partir du noeud specifie
+ * @param dn
+ * @return <tt>true</tt> s'il faut rafraichir l'arbre
+ */
+ protected void purge(DatabaseTreeDataDonnee.DataNode dn) {
+ int level = dn.getType();
+ Runnable process = null;
+ switch (level) {
+ case DatabaseTreeDataDonnee.DataNode.TYPE_DOCUMENT: {
+ final DocumentModel dm = (DocumentModel) dn.getData();
+ process = new Runnable() {
+
+ @Override
+ public void run() {
+ try {
+ getGlassPane().setVisible(true);
+ DataLayerManager.getImplementation().removeDocumentModel(dm, user);
+ } catch (UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(getParent(), ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (DataAccessException daEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, daEx);
+ } catch (DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, dcEx);
+ } finally {
+ getGlassPane().setVisible(false);
+ }
+ }
+ };
+ break;
+ }
+ case DatabaseTreeDataDonnee.DataNode.TYPE_ARCHIVE: {
+ final DatabaseTreeDataDonnee.DataNode node = dn;
+ process = new Runnable() {
+ @Override
+ public void run() {
+ try {
+ Document manifeste = DataLayerManager.getImplementation().getManifesteFromArchive(((Pair)node.getData()).libelle, user);
+ if (manifeste != null) {
+ XPathFactory xpf = FactoryProvider.getXPathFactory();
+ XPath xp = xpf.newXPath();
+ xp.setNamespaceContext(MainWindow.getInstance().getDocModels().getDocumentById("manifeste").getNamespaces());
+ NodeList documentIds = (NodeList) xp.evaluate("//n:document/@type", manifeste.getDocumentElement(), XPathConstants.NODESET);
+ HashMap<String, DocumentModel> docsModel = new HashMap<String, DocumentModel>();
+ for (int i = 0; i < documentIds.getLength(); i++) {
+ String docId = documentIds.item(i).getNodeValue();
+ if ("CGE".equals(docId)) {
+ docId = "cg-colloc";
+ } else if ("CGETAT".equals(docId)) {
+ docId = "cg-etat";
+ } else if ("PES".equals(docId)) {
+ docId = "pes-aller";
+ } else if ("EDMN".equals(docId)) {
+ docId = "edmn";
+ } else if ("ERTN".equals(docId)) {
+ docId = "ertn";
+ } else if ("PJ".equals(docId)) {
+ docId = null;
+ }
+ if (!docsModel.containsKey(docId)) {
+ docsModel.put(docId, MainWindow.getInstance().getDocModels().getDocumentById(docId));
+ }
+ }
+ DataLayerManager.getImplementation().removeArchive(docsModel, ((Pair)node.getData()).libelle, user);
+
+ // Mise à jour du manifeste de l'archive
+ DataLayerManager.getImplementation().updateManifeste(((Pair)node.getData()).libelle, user);
+
+ // Suppression dans le referentiel collectivite
+ XmlUtils.showDomInConsole(manifeste, "Manifeste de la base");
+ NodeList actionsOnDelete = (NodeList) xp.evaluate("//n:on-delete/n:action", manifeste.getDocumentElement(), XPathConstants.NODESET);
+ for (int compteurAction = 0; compteurAction < actionsOnDelete.getLength(); compteurAction++) {
+ Element action = (Element) actionsOnDelete.item(compteurAction);
+ String className = action.getAttribute("class");
+ Class clazz = Class.forName(className);
+ Object instance = clazz.newInstance();
+ if (!(instance instanceof AbstractImportPatcherImpl)) {
+ throw new Exception(className + " n'est pas un AbstractImportPatcherImpl");
+ }
+ AbstractImportPatcherImpl patcher = (AbstractImportPatcherImpl) instance;
+
+ Object o = xp.evaluate("n:parameter", action, XPathConstants.NODESET);
+ if (o instanceof NodeList) {
+ NodeList nl = (NodeList) o;
+ for (int i = 0; i < nl.getLength(); i++) {
+ Element param = (Element) nl.item(i);
+ String paramName = param.getAttribute("name");
+ String type = param.getAttribute("type");
+ if ("java.lang.String".equals(type)) {
+ String value = param.getAttribute("value");
+ if (value == null) {
+ value = (String) xp.evaluate("./text()", param, XPathConstants.STRING);
+ }
+ patcher.setParameter(paramName, value);
+ } else if ("java.lang.Integer".equals(type)) {
+ String value = param.getAttribute("value");
+ if (value == null) {
+ value = (String) xp.evaluate("./text()", param, XPathConstants.STRING);
+ }
+ patcher.setParameter(paramName, Integer.valueOf(value));
+ }
+ }
+ }
+ patcher.run();
+ }
+ } else {
+ JOptionPane.showMessageDialog(getParent(), "La base de donnée ne contient rien provennat de cette archive.", "Aucune donnée n'a été supprimée", JOptionPane.WARNING_MESSAGE);
+ }
+ } catch (UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(getParent(), ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (DataAccessException daEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, daEx);
+ } catch (DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, dcEx);
+ } catch (XPathExpressionException e) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, e);
+ } catch (ClassNotFoundException e) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, e);
+ } catch (InstantiationException e) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, e);
+ } catch (IllegalAccessException e) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, e);
+ } catch (Exception e) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, e);
+ } finally {
+ getGlassPane().setVisible(false);
+ }
+ }
+ };
+ break;
+ }
+ case DatabaseTreeDataDonnee.DataNode.TYPE_COLLECTIVITE: {
+ final DocumentModel dm = (DocumentModel) (dn.getParent().getData());
+ final Pair collectivite = (Pair) dn.getData();
+ process = new Runnable() {
+
+ @Override
+ public void run() {
+ try {
+ getGlassPane().setVisible(true);
+ DataLayerManager.getImplementation().removeCollectivite(dm, collectivite, user);
+ } catch (UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(getParent(), ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (DataAccessException daEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, daEx);
+ } catch (DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, dcEx);
+ } finally {
+ getGlassPane().setVisible(false);
+ }
+ }
+ };
+ break;
+ }
+ case DatabaseTreeDataDonnee.DataNode.TYPE_BUDGET: {
+ final Pair budget = (Pair) dn.getData();
+ final Pair collectivite = (Pair) dn.getParent().getData();
+ final DocumentModel dm = (DocumentModel) (dn.getParent().getParent().getData());
+ process = new Runnable() {
+
+ @Override
+ public void run() {
+ try {
+ getGlassPane().setVisible(true);
+ DataLayerManager.getImplementation().removeBudget(dm, collectivite, budget, user);
+ } catch (UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(getParent(), ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (DataAccessException daEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, daEx);
+ } catch (DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, dcEx);
+ } finally {
+ getGlassPane().setVisible(false);
+ }
+ }
+ };
+ break;
+ }
+ case ExportableData.TYPE_PERSO1: {
+ final Pair perso1 = (Pair) dn.getData();
+ final Pair budget = (Pair) dn.getParent().getData();
+ final Pair collectivite = (Pair) dn.getParent().getParent().getData();
+ final DocumentModel dm = (DocumentModel) (dn.getParent().getParent().getParent().getData());
+ process = new Runnable() {
+
+ @Override
+ public void run() {
+ try {
+ getGlassPane().setVisible(true);
+ DataLayerManager.getImplementation().removeSpecialKey1(dm, collectivite, budget, perso1, user);
+ } catch (UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(getParent(), ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (DataAccessException daEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, daEx);
+ } catch (DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, dcEx);
+ } finally {
+ getGlassPane().setVisible(false);
+ }
+ }
+ };
+ break;
+ }
+ case ExportableData.TYPE_PERSO2: {
+ final Pair perso2 = (Pair) dn.getData();
+ final Pair perso1 = (Pair) dn.getParent().getData();
+ final Pair budget = (Pair) dn.getParent().getParent().getData();
+ final Pair collectivite = (Pair) dn.getParent().getParent().getParent().getData();
+ final DocumentModel dm = (DocumentModel) (dn.getParent().getParent().getParent().getParent().getData());
+ process = new Runnable() {
+
+ @Override
+ public void run() {
+ try {
+ getGlassPane().setVisible(true);
+ DataLayerManager.getImplementation().removeSpecialKey2(dm, collectivite, budget, perso1, perso2, user);
+ } catch (UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(getParent(), ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (DataAccessException daEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, daEx);
+ } catch (DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, dcEx);
+ } finally {
+ getGlassPane().setVisible(false);
+ }
+ }
+ };
+ break;
+ }
+ }
+ if (process != null) {
+ logger.debug("deleting");
+ SwingWorker deleter = new Deleter(process, this);
+ deleter.execute();
+ }
+ }
+
+ private class Deleter extends SwingWorker {
+
+ private Runnable process = null;
+ private DlgCleanDatabase dlg = null;
+ private WaitableUI wui;
+
+ public Deleter(Runnable process, DlgCleanDatabase dlg) {
+ super();
+ this.process = process;
+ this.dlg = dlg;
+ }
+
+ @Override
+ public String doInBackground() {
+ dlg.enableButtons(false);
+ dlg.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
+ process.run();
+ return null;
+ }
+
+ @Override
+ public void done() {
+ try {
+ if (getJTabbedPane1().getSelectedComponent() instanceof PanelChooseDatabaseDonnees) {
+ ((PanelChooseDatabaseDonnees) dlg.getJTabbedPane1().getSelectedComponent()).getJTree1().setModel(new DatabaseTreeDataDonnee(getDm(), dlg, user, MainWindow.getInstance().getEnvProperties()));
+ }
+ if (getJTabbedPane1().getSelectedComponent() instanceof PanelChooseDatabaseFichier) {
+ ((PanelChooseDatabaseFichier) dlg.getJTabbedPane1().getSelectedComponent()).refresh();
+ }
+ } catch (UnauthorizedException ex) {
+ //
+ }
+ dlg.setCursor(Cursor.getDefaultCursor());
+ dlg.enableButtons(true);
+ }
+ }
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.3" maxVersion="1.3" type="org.netbeans.modules.form.forminfo.JDialogFormInfo">
+ <Properties>
+ <Property name="defaultCloseOperation" type="int" value="2"/>
+ </Properties>
+ <SyntheticProperties>
+ <SyntheticProperty name="formSizePolicy" type="int" value="1"/>
+ </SyntheticProperties>
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="2"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="jScrollPane1" alignment="1" pref="356" max="32767" attributes="0"/>
+ <Group type="102" alignment="1" attributes="0">
+ <Component id="pbSaveValues" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="pbOk" min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="1" attributes="0">
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Component id="jScrollPane1" pref="419" max="32767" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="pbOk" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="pbSaveValues" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Container class="javax.swing.JScrollPane" name="jScrollPane1">
+ <AuxValues>
+ <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
+ </AuxValues>
+
+ <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
+ <SubComponents>
+ <Component class="org.jdesktop.swingx.JXTreeTable" name="treeTable">
+ <Properties>
+ <Property name="autoResizeMode" type="int" value="3"/>
+ </Properties>
+ <AuxValues>
+ <AuxValue name="JavaCodeGenerator_CreateCodeCustom" type="java.lang.String" value="new JXTreeTablePropertyEditor(defaultConfiguration);"/>
+ </AuxValues>
+ </Component>
+ </SubComponents>
+ </Container>
+ <Component class="javax.swing.JButton" name="pbOk">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Fermer"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbOkClick"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="pbSaveValues">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Enregistrer"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbSaveValuesActionPerformed"/>
+ </Events>
+ </Component>
+ </SubComponents>
+</Form>
--- /dev/null
+/*
+ * Copyright
+ * 2008 axYus - www.axyus.com
+ * 2008 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui;
+
+import java.awt.Component;
+import java.awt.event.ActionEvent;
+import java.awt.event.MouseEvent;
+import java.util.Enumeration;
+
+import javax.swing.DefaultCellEditor;
+import javax.swing.JCheckBox;
+import javax.swing.JLabel;
+import javax.swing.JRootPane;
+import javax.swing.JTable;
+import javax.swing.JTextField;
+import javax.swing.event.TreeExpansionEvent;
+import javax.swing.event.TreeExpansionListener;
+import javax.swing.table.DefaultTableCellRenderer;
+import javax.swing.table.TableCellEditor;
+import javax.swing.table.TableCellRenderer;
+
+import org.apache.log4j.Logger;
+import org.jdesktop.swingx.JXTreeTable;
+import org.jdesktop.swingx.treetable.TreeTableModel;
+
+import fr.gouv.finances.dgfip.xemelios.common.config.EnvironmentDomain;
+import fr.gouv.finances.dgfip.xemelios.common.config.VariableModel;
+import fr.gouv.finances.dgfip.xemelios.data.DataConfigurationException;
+import fr.gouv.finances.cp.xemelios.ui.ia.core.DlgCore;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentsModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.Loader;
+import fr.gouv.finances.dgfip.xemelios.common.config.ReferenceModel;
+import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
+import java.awt.event.MouseListener;
+import java.util.ArrayList;
+import java.util.Hashtable;
+import javax.swing.AbstractAction;
+import javax.swing.Action;
+import javax.swing.JOptionPane;
+import javax.swing.JPopupMenu;
+import javax.swing.KeyStroke;
+import javax.swing.event.TableModelEvent;
+import org.jdesktop.swingx.treetable.AbstractTreeTableModel;
+
+/**
+ *
+ * @author chm
+ */
+public class DlgEditEnvironment extends javax.swing.JDialog {
+ private static final String TITLE = "Environnement";
+ private static Logger logger = Logger.getLogger(DlgEditEnvironment.class);
+ private boolean ret = false;
+ private EnvironmentDomain documents;
+ private TreeTableModel myModel;
+ private int domain;
+ private Action action;
+ private Hashtable<String,ValueToSave> valuesToSave;
+ private ArrayList<String> valuesToRemove;
+ private DocumentsModel defaultConfiguration;
+ private XemeliosUser user;
+
+ /** Creates new form DlgEditEnvironment */
+ public DlgEditEnvironment(java.awt.Frame parent,EnvironmentDomain documents, int domain, XemeliosUser user) {
+ super(parent, true);
+ setTitle(TITLE);
+ this.documents = documents;
+ this.domain=domain;
+ this.user=user;
+ myModel = createModel();
+ valuesToSave = new Hashtable<String, ValueToSave>();
+ valuesToRemove = new ArrayList<String>();
+ if(EnvironmentDomain.DOMAIN_DOCUMENTS==domain) {
+ try {
+ defaultConfiguration = Loader.getConfigurationFromLoadedFiles();
+ } catch(Exception e) {
+ // on peut ici l'ignorer
+ }
+ }
+ initComponents();
+ setLocationRelativeTo(getParent());
+ treeTable.setTreeTableModel(myModel);
+ if(EnvironmentDomain.DOMAIN_DOCUMENTS!=domain) {
+ pbSaveValues.setVisible(false);
+ }
+ treeTable.addTreeExpansionListener(new TreeExpansionListener() {
+ @Override
+ public void treeCollapsed(TreeExpansionEvent event) {
+ }
+ @Override
+ public void treeExpanded(TreeExpansionEvent event) {
+ treeTable.packAll();
+ }
+ });
+ }
+
+ @Override
+ protected JRootPane createRootPane() {
+ JRootPane rp = super.createRootPane();
+ action = new AbstractAction() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ DlgCore dlg = new DlgCore(MainWindow.instance);
+ dlg.setVisible(true);
+ setVisible(false); }
+ };
+ rp.getActionMap().put("SS",action);
+ rp.getInputMap().put(KeyStroke.getKeyStroke("control shift S"), "SS");
+ return rp;
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ jScrollPane1 = new javax.swing.JScrollPane();
+ treeTable = new JXTreeTablePropertyEditor(defaultConfiguration);
+ pbOk = new javax.swing.JButton();
+ pbSaveValues = new javax.swing.JButton();
+
+ setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+
+ treeTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_LAST_COLUMN);
+ jScrollPane1.setViewportView(treeTable);
+
+ pbOk.setText("Fermer");
+ pbOk.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbOkClick(evt);
+ }
+ });
+
+ pbSaveValues.setText("Enregistrer");
+ pbSaveValues.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbSaveValuesActionPerformed(evt);
+ }
+ });
+
+ org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 356, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
+ .add(pbSaveValues)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(pbOk)))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
+ .addContainerGap()
+ .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 419, Short.MAX_VALUE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(pbOk)
+ .add(pbSaveValues))
+ .addContainerGap())
+ );
+
+ pack();
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void pbOkClick(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbOkClick
+ if(treeTable.isEditing()) {
+ treeTable.getCellEditor(treeTable.getEditingRow(),treeTable.getEditingColumn()).stopCellEditing();
+ }
+ ret = true;
+ setVisible(false);
+ }//GEN-LAST:event_pbOkClick
+
+ private void pbSaveValuesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbSaveValuesActionPerformed
+ Hashtable<String,Object> values = new Hashtable<String, Object>();
+ for(String key:valuesToSave.keySet()) {
+ ValueToSave vts = valuesToSave.get(key);
+ values.put(key, vts.value);
+ }
+ try {
+ DataLayerManager.getImplementation().saveRedefinedValues(values, valuesToRemove, user);
+ } catch(Exception ex) {
+ logger.error("saving: ",ex);
+ }
+ }//GEN-LAST:event_pbSaveValuesActionPerformed
+
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JScrollPane jScrollPane1;
+ private javax.swing.JButton pbOk;
+ private javax.swing.JButton pbSaveValues;
+ private org.jdesktop.swingx.JXTreeTable treeTable;
+ // End of variables declaration//GEN-END:variables
+
+ private TreeTableModel createModel() {
+ return new EnvironmentTreeModel(documents, domain);
+ }
+ private class EnvironmentTreeModel extends AbstractTreeTableModel {
+ private EnvironmentDomain env;
+ private int domain;
+ public EnvironmentTreeModel(EnvironmentDomain env, int domain) {
+ super();
+ this.env=env;
+ this.domain = domain;
+ }
+
+ @Override
+ public boolean isLeaf(Object node) {
+ if(node instanceof EnvironmentDomain) {
+ EnvironmentDomain ed = (EnvironmentDomain)node;
+ return !(ed.hasEnvironment(domain) ||
+ ed.getChildCount(domain, MainWindow.getInstance().getEnvProperties())>0);
+ }
+ return true;
+ }
+
+ @Override
+ public int getChildCount(Object parent) {
+ if(parent instanceof EnvironmentDomain) {
+ EnvironmentDomain ed = (EnvironmentDomain)parent;
+ int ret = 0;
+ if(ed.hasEnvironment(domain)) {
+ Enumeration enumer = ed.getVariables(domain);
+ while(enumer.hasMoreElements()) { ret++; enumer.nextElement(); }
+ }
+ return ed.getChildCount(domain, MainWindow.getInstance().getEnvProperties()) + ret;
+ }
+ return 0;
+ }
+
+
+ @Override
+ public String getColumnName(int i) {
+ switch(i) {
+ case 0: return "Propriété";
+ case 1: return "Valeur";
+ }
+ return "";
+ }
+
+ @Override
+ public Class getColumnClass(int i) { if(i==1)return String.class; else return super.getColumnClass(i); }
+
+
+ @Override
+ public Object getValueAt(Object object, int i) {
+ if(i==0) {
+ return object.toString();
+ } else if(object instanceof VariableModel) {
+ VariableModel vm = (VariableModel)object;
+ try {
+ if(vm.getReference()!=null)
+ return vm.getReference().getValue(env);
+ else return "<unset>";
+ } catch(DataConfigurationException dcEx) {
+ logger.error(dcEx);
+ return dcEx.getMessage();
+ }
+ } else return "";
+ }
+
+ @Override
+ public void setValueAt(Object value, Object node, int column) {
+ if(node instanceof VariableModel) {
+ VariableModel vm = (VariableModel)node;
+ if(vm.getReference()!=null) {
+ try {
+ vm.getReference().setValue(env,value);
+ ReferenceModel rm = vm.getReference();
+ DlgEditEnvironment.this.valuesToSave.put(rm.getName(), new ValueToSave(rm, value));
+ DlgEditEnvironment.this.valuesToRemove.remove(rm.getName());
+ } catch(DataConfigurationException dcEx) {
+ logger.error(dcEx);
+ }
+ }
+ }
+ }
+
+ @Override
+ public Object getChild(Object parent, int index) {
+ if(parent instanceof EnvironmentDomain) {
+ EnvironmentDomain ed = (EnvironmentDomain)parent;
+ int childCount = ed.getChildCount(domain, MainWindow.getInstance().getEnvProperties());
+ if(index<childCount)
+ return ed.getChildAt(domain,index);
+ else {
+ int i2 = index - childCount;
+ Enumeration<VariableModel> enumer = ed.getVariables(domain);
+ int count = 0;
+ while(count<i2 && enumer.hasMoreElements()) {
+ enumer.nextElement();
+ count++;
+ }
+ return enumer.nextElement();
+ }
+ } else return null;
+ }
+
+ @Override
+ public boolean isCellEditable(Object object, int i) {
+ return (i==1 && object instanceof VariableModel);
+ }
+
+ @Override
+ public int getIndexOfChild(Object parent, Object child) { return 0; }
+
+ @Override
+ public Object getRoot() { return env; }
+
+ @Override
+ public int getColumnCount() { return 2; }
+ }
+ private class JXTreeTablePropertyEditor extends JXTreeTable {
+ private MyCellEditor booleanEditor, integerEditor;
+ private TableCellRenderer booleanRenderer, integerRenderer;
+ private EnvironmentDomain domain;
+ public JXTreeTablePropertyEditor(EnvironmentDomain domain) {
+ super();
+ this.domain=domain;
+ booleanEditor = new MyCellEditor(new JCheckBox()) {
+ @Override
+ public Component getTableCellEditorComponent(JTable table,Object value,boolean isSelected,int row,int column) {
+ Component c = super.getTableCellEditorComponent(table,value,isSelected,row,column);
+ JCheckBox chk = (JCheckBox)editorComponent;
+ chk.setSelected(((Boolean)value).booleanValue());
+ chk.setBackground(c.getBackground());
+ chk.addMouseListener(new MouseListener() {
+ @Override
+ public void mouseClicked(MouseEvent e) {
+ maybeShowPopup(e);
+ }
+ @Override
+ public void mousePressed(MouseEvent e) {
+ maybeShowPopup(e);
+ }
+ @Override
+ public void mouseReleased(MouseEvent e) {
+ maybeShowPopup(e);
+ }
+ private void maybeShowPopup(MouseEvent e) {
+ if(e.isPopupTrigger()) {
+ JPopupMenu popup = new JPopupMenu();
+ popup.add(new AbstractAction("Valeur par défaut") {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ JOptionPane.showMessageDialog(
+ DlgEditEnvironment.this,
+ "set default value of "+getVm().getReference().getName());
+ }
+ });
+ popup.show(e.getComponent(), e.getX(), e.getY());
+ }
+ }
+ @Override
+ public void mouseEntered(MouseEvent e) { }
+ @Override
+ public void mouseExited(MouseEvent e) { }
+ });
+ return chk;
+ }
+ };
+ integerEditor = new MyCellEditor(new JTextField()) {
+ @Override
+ public Component getTableCellEditorComponent(JTable table,Object value,boolean isSelected,int row,int column) {
+ JTextField txt = (JTextField)editorComponent;
+ final EnvironmentDomain defaultConfiguration = getDefaultConfiguration();
+ txt.setHorizontalAlignment(JTextField.RIGHT);
+ txt.setText(value.toString());
+ txt.addMouseListener(new MouseListener() {
+ @Override
+ public void mouseClicked(MouseEvent e) {
+ maybeShowPopup(e);
+ }
+ @Override
+ public void mousePressed(MouseEvent e) {
+ maybeShowPopup(e);
+ }
+ @Override
+ public void mouseReleased(MouseEvent e) {
+ maybeShowPopup(e);
+ }
+ private void maybeShowPopup(MouseEvent e) {
+ if(e.isPopupTrigger()) {
+ JPopupMenu popup = new JPopupMenu();
+ popup.add(new RestoreDefaultValueAction(defaultConfiguration,integerEditor));
+ popup.show(e.getComponent(), e.getX(), e.getY());
+ }
+ }
+ @Override
+ public void mouseEntered(MouseEvent e) { }
+ @Override
+ public void mouseExited(MouseEvent e) { }
+ });
+ return txt;
+ }
+ };
+ booleanRenderer = new DefaultTableCellRenderer() {
+ private JCheckBox chk = new JCheckBox();
+ @Override
+ public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column) {
+ JLabel lbl = (JLabel)super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
+ chk.setSelected(((Boolean)value).booleanValue());
+ chk.setBackground(lbl.getBackground());
+ chk.setBorder(lbl.getBorder());
+ return chk;
+ }
+ };
+ integerRenderer = new DefaultTableCellRenderer() {
+ @Override
+ public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column) {
+ JLabel txt = (JLabel)super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
+ txt.setHorizontalAlignment(JTextField.RIGHT);
+ txt.setText(value.toString());
+ return txt;
+ }
+ };
+ }
+ private EnvironmentDomain getDefaultConfiguration() { return domain; }
+ @Override
+ public TableCellEditor getCellEditor(int row, int column) {
+ if(column==1 && getTreeTableModel() instanceof EnvironmentTreeModel) {
+ EnvironmentTreeModel model = (EnvironmentTreeModel)getTreeTableModel();
+ Object node = getPathForRow(row).getLastPathComponent();
+ if(node instanceof VariableModel) {
+ VariableModel vm = (VariableModel)node;
+ String type = vm.getType();
+ if("integer".equals(type)) {
+ integerEditor.setVm(vm);
+ integerEditor.row=row;
+ return integerEditor;
+ } else if("boolean".equals(type)) {
+ booleanEditor.setVm(vm);
+ booleanEditor.row=row;
+ return booleanEditor;
+ }
+ }
+ return super.getCellEditor(row,column);
+ } else {
+ return super.getCellEditor(row,column);
+ }
+ }
+ @Override
+ public TableCellRenderer getCellRenderer(int row, int column) {
+ if(column==1 && getTreeTableModel() instanceof EnvironmentTreeModel) {
+ EnvironmentTreeModel model = (EnvironmentTreeModel)getTreeTableModel();
+ Object node = getPathForRow(row).getLastPathComponent();
+ if(node instanceof VariableModel) {
+ VariableModel vm = (VariableModel)node;
+ String type = vm.getType();
+ if("integer".equals(type)) {
+ return integerRenderer;
+ } else if("boolean".equals(type)) {
+ return booleanRenderer;
+ }
+ }
+ return super.getCellRenderer(row,column);
+ } else {
+ return super.getCellRenderer(row,column);
+ }
+ }
+ }
+ private class ValueToSave {
+ ReferenceModel reference;
+ Object value;
+ public ValueToSave(ReferenceModel ref, Object value) {
+ super();
+ this.reference=ref;
+ this.value=value;
+ }
+ }
+ private static class MyCellEditor extends DefaultCellEditor {
+ private VariableModel vm;
+ private int row;
+ public VariableModel getVm() {
+ return vm;
+ }
+ public int getRow() { return row; }
+ public void setVm(VariableModel vm) {
+ this.vm = vm;
+ }
+ public MyCellEditor(JCheckBox chk) {
+ super(chk);
+ }
+ public MyCellEditor(JTextField df) {
+ super(df);
+ }
+ }
+ private class RestoreDefaultValueAction extends AbstractAction {
+ private EnvironmentDomain defaultConfiguration;
+ private MyCellEditor cellEditor;
+ public RestoreDefaultValueAction(EnvironmentDomain defaultConfiguration, MyCellEditor cellEditor) {
+ super("Rétablir la valeur par défaut");
+ this.defaultConfiguration = defaultConfiguration;
+ this.cellEditor = cellEditor;
+ }
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ Object value = null;
+ String path = cellEditor.getVm().getReference().getName();
+ if(path.startsWith("/")) path = path.substring(1);
+ logger.debug(path);
+ try {
+ value = cellEditor.getVm().getReference().getValue(defaultConfiguration);
+ if(value!=null) {
+ cellEditor.getVm().getReference().setValue(documents, value);
+ cellEditor.cancelCellEditing();
+ DlgEditEnvironment.this.treeTable.tableChanged(new TableModelEvent(DlgEditEnvironment.this.treeTable.getModel(), cellEditor.getRow()));
+ valuesToRemove.add(cellEditor.getVm().getReference().getName());
+ valuesToSave.remove(cellEditor.getVm().getReference().getName());
+ }
+ } catch(Throwable t) {
+ logger.error("actionPreformed",t);
+ }
+
+ }
+
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 N.Le Corre - nicolas.lecorre@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui;
+
+import fr.gouv.finances.dgfip.xemelios.data.DatabaseTreeDataDonnee;
+import java.awt.event.ActionEvent;
+import java.awt.event.KeyEvent;
+import java.util.StringTokenizer;
+import javax.swing.AbstractAction;
+import javax.swing.Action;
+import javax.swing.JComponent;
+
+import javax.swing.JOptionPane;
+import javax.swing.JRootPane;
+import javax.swing.KeyStroke;
+import javax.swing.tree.TreePath;
+
+import org.apache.log4j.Logger;
+
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentsModel;
+import fr.gouv.finances.dgfip.xemelios.data.ExportableData;
+import fr.gouv.finances.cp.xemelios.ui.export.DlgSearchConfig;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+
+@SuppressWarnings("serial")
+public class DlgExportAll extends DlgChooseDocuments {
+ private static Logger logger = Logger.getLogger(DlgExportAll.class);
+ private Action escapeAction;
+ private XemeliosUser user;
+
+ public DlgExportAll(java.awt.Frame parent, boolean modal, DlgChooseDocuments.DIALOG_TYPE dialogType, DocumentsModel _dm,XemeliosUser user) {
+ super(parent, modal, _dm, false, dialogType, user, MainWindow.getInstance().getEnvProperties());
+ this.user=user;
+ setTitle("Exporter");
+ setBActionLibelle("Exporter");
+ Object o = getJTabbedPane1().getComponent(0);
+ if(o instanceof PanelChooseDatabaseFichier) {
+ ((PanelChooseDatabaseFichier)o).setMode(PanelChooseDatabaseFichier.MODE_EXPORT);
+ }
+ }
+
+ @Override
+ protected void doAction(ActionEvent evt) {
+ if (getJTabbedPane1().getSelectedComponent() instanceof PanelChooseDatabaseDonnees) {
+ export(((PanelChooseDatabaseDonnees)getJTabbedPane1().getSelectedComponent()).getJTree1().getSelectionPath());
+ }
+ if (getJTabbedPane1().getSelectedComponent() instanceof PanelChooseDatabaseFichier) {
+ exportFichiers();
+ }
+ }
+
+ /**
+ * EXPORT PAR FICHIER
+ */
+ protected void exportFichiers() {
+ ExportableData datas = ((PanelChooseDatabaseFichier)getJTabbedPane1().getSelectedComponent()).getData().getData();
+ for (ExportableData d:datas.getChilds()) {
+ exportData(d);
+ }
+ }
+
+ protected void exportData(ExportableData datas) {
+ // Si l'on veux exorter ce niveau
+ if (datas.isSelected()) {
+ doExportData(datas);
+ } else {
+ for (ExportableData d:datas.getChilds()) {
+ exportData(d);
+ }
+ }
+ }
+
+ public void doExportData(ExportableData d) {
+ DocumentModel dm = null;
+ Pair collectivite = null;
+ Pair budget = null;
+ String fichier = null;
+
+ // export selon le niveau
+ switch (d.getLevel()) {
+ case ExportableData.LVL_BUD : {
+ StringTokenizer st = new StringTokenizer(d.getKey(), "|");
+ dm = getDm().getDocumentById(st.nextToken());
+ collectivite = new Pair(st.nextToken(), "");
+ budget = new Pair(st.nextToken(), "");
+ logger.debug("exporting BUD : "+dm.getId()+", "+collectivite.key+", "+budget.key);
+ break;
+ }
+ case ExportableData.LVL_FIC : {
+ StringTokenizer st = new StringTokenizer(d.getKey(), "|");
+ dm = getDm().getDocumentById(st.nextToken());
+ collectivite = new Pair(st.nextToken(), "");
+ budget = new Pair(st.nextToken(), "");
+ fichier = st.nextToken();
+ logger.debug("exporting FIC : "+dm.getId()+", "+collectivite.key+", "+budget.key+", "+fichier);
+ break;
+ }
+ }
+
+ if (d.getLevel()==ExportableData.LVL_BUD || d.getLevel()==ExportableData.LVL_FIC) {
+ if(JOptionPane.showConfirmDialog(this,"Etes-vous sur de vouloir exporter ces informations ?\n\nCette opération peut prendre beaucoup de temps\nsi le nombre d'éléments à exporter est important.","Export",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION) {
+
+ DocumentsModel dmsTmp = new DocumentsModel(DocumentsModel.QN);
+ try { dmsTmp.addChild(dm, DocumentModel.QN); } catch (Throwable t) {}
+
+ DlgSearchConfig sc = new DlgSearchConfig(MainWindow.getInstance(), dmsTmp, DlgSearchConfig.EXEC_FROM_MENU,user);
+ sc.setDm(dm);
+ sc.setColl(collectivite);
+ sc.setBudg(budget);
+ sc.setFic(fichier);
+ sc.setWhatToExport(d.getLevel());
+ sc.setVisible(true);
+ }
+ }
+ }
+
+ /**
+ * EXPORT PAR DONNEES
+ */
+
+ /**
+ * Exporte a partir du chemin specifie
+ * @param tp Le chemin a exporter
+ * @return <tt>true</tt> s'il faut rafraichir l'arbre
+ */
+ protected void export(TreePath tp) {
+ if(tp==null) return;
+ DatabaseTreeDataDonnee.DataNode node = (DatabaseTreeDataDonnee.DataNode)tp.getLastPathComponent();
+ export(node);
+ }
+ /**
+ * Exporte a partir du noeud specifie
+ * @param dn
+ * @return <tt>true</tt> s'il faut rafraichir l'arbre
+ */
+ protected void export(DatabaseTreeDataDonnee.DataNode dn) {
+ DocumentModel dm = null;
+ Pair collectivite = null;
+ Pair budget = null;
+ String fichier = null;
+ Pair perso1 = null;
+ Pair perso2 = null;
+
+ int level = dn.getType();
+ switch(level) {
+ case ExportableData.LVL_BUD: {
+ budget = (Pair)dn.getData();
+ collectivite = (Pair)dn.getParent().getData();
+ dm = (DocumentModel)(dn.getParent().getParent().getData());
+ break;
+ }
+ case ExportableData.TYPE_PERSO1: {
+ perso1 = (Pair)dn.getData();
+ budget = (Pair)dn.getParent().getData();
+ collectivite = (Pair)dn.getParent().getParent().getData();
+ dm = (DocumentModel)(dn.getParent().getParent().getParent().getData());
+ break;
+ }
+ case ExportableData.TYPE_PERSO2: {
+ perso2 = (Pair)dn.getData();
+ perso1 = (Pair)dn.getParent().getData();
+ budget = (Pair)dn.getParent().getParent().getData();
+ collectivite = (Pair)dn.getParent().getParent().getParent().getData();
+ dm = (DocumentModel)(dn.getParent().getParent().getParent().getParent().getData());
+ }
+ }
+
+ if (level==ExportableData.LVL_BUD || level==ExportableData.TYPE_PERSO1 || level==ExportableData.TYPE_PERSO2) {
+ if(JOptionPane.showConfirmDialog(this,"Etes-vous sur de vouloir exporter ces informations ?\n\nCette opération peut prendre beaucoup de temps\nsi le nombre d'éléments à exporter est important.","Export",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION) {
+
+ DocumentsModel dmsTmp = new DocumentsModel(DocumentsModel.QN);
+ try { dmsTmp.addChild(dm, DocumentModel.QN); } catch (Throwable t) {}
+
+ DlgSearchConfig sc = new DlgSearchConfig(MainWindow.getInstance(), dmsTmp, DlgSearchConfig.EXEC_FROM_MENU,user);
+ sc.setDm(dm);
+ sc.setColl(collectivite);
+ sc.setBudg(budget);
+ sc.setFic(fichier);
+ sc.setSK1(perso1);
+ sc.setSK2(perso2);
+ sc.setWhatToExport(level);
+ sc.setVisible(true);
+ }
+ }
+ }
+ @Override
+ protected JRootPane createRootPane() {
+ KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0);
+ JRootPane rp = new JRootPane();
+ escapeAction = new AbstractAction("Fermer") {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+
+ public void actionPerformed(ActionEvent evt) {
+ setVisible(false);
+ }
+ };
+ rp.registerKeyboardAction(escapeAction,"TOTOTOTO",ks,JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui;
+
+import java.awt.Component;
+import java.awt.FlowLayout;
+import java.awt.Point;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.KeyEvent;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.util.Vector;
+
+import javax.swing.AbstractAction;
+import javax.swing.Action;
+import javax.swing.DefaultListCellRenderer;
+import javax.swing.ImageIcon;
+import javax.swing.JButton;
+import javax.swing.JComponent;
+import javax.swing.JDialog;
+import javax.swing.JLabel;
+import javax.swing.JList;
+import javax.swing.JMenuItem;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JPopupMenu;
+import javax.swing.JRootPane;
+import javax.swing.JScrollPane;
+import javax.swing.JTextArea;
+import javax.swing.KeyStroke;
+import javax.swing.ListSelectionModel;
+
+import org.apache.log4j.Logger;
+
+import com.jgoodies.forms.builder.PanelBuilder;
+import com.jgoodies.forms.layout.CellConstraints;
+import com.jgoodies.forms.layout.FormLayout;
+
+import fr.gouv.finances.cp.utils.ui.IhmFactory;
+import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.RechercheModel;
+import fr.gouv.finances.dgfip.xemelios.ui.ImageResources;
+import fr.gouv.finances.dgfip.xemelios.ui.ListDisplayable;
+
+/**
+ * Cette boite de dialogue affiche la structure de
+ * la base a l'utilisateur afin de lui permettre
+ * de selectionner les branches a supprimer.
+ * @author chm
+ */
+public class DlgSelectRequest extends JDialog {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 3256721779816151348L;
+ private static final Logger logger = Logger.getLogger((DlgSelectRequest.class));
+ private Action escapeAction;
+ private Vector<? extends Object> data;
+ private boolean ret = false;
+ private JList list = null;
+ private MainWindow parentFrame = null;
+ private ElementModel elementModel = null;
+
+ private static ImageIcon searchSaved, searchPlugin, exportPlugin/*, deleteIcon*/;
+ static {
+// IhmFactory iF = IhmFactory.newInstance();
+ exportPlugin = IhmFactory.getIconFromResource(ImageResources.LST_EXPORT_P);
+ searchPlugin = IhmFactory.getIconFromResource(ImageResources.LST_SEARCH_P);
+ searchSaved = IhmFactory.getIconFromResource(ImageResources.LST_SEARCH_SAV);
+// deleteIcon = iF.getIconFromResource(ImageResources.LST_DELETE_SEARCH);
+ }
+
+ public DlgSelectRequest(MainWindow parent,Vector<? extends ListDisplayable> data, ElementModel elementModel) {
+ super(parent,true);
+ this.data = data;
+ this.parentFrame=parent;
+ this.elementModel=elementModel;
+ initComponents();
+ }
+ protected void initComponents() {
+ int sepInfo = 2; // 2
+ int lineInfo = sepInfo + 2; // 4
+ int sepData = lineInfo + 2; // 6
+ int listLine = sepData + 2; // 8
+ int buttonLine1 = listLine + 2; // 10
+
+ JTextArea area = null;
+
+ FormLayout fl = new FormLayout(
+ // 1 2 3 4
+ "3dlu,20dlu,160dlu,3dlu",
+ "7dlu,"+ // 1
+ "pref,"+ // 2
+ "3dlu,"+ // 3
+ "pref,"+ // 4
+ "7dlu,"+ // 5
+ "pref,"+ // 6
+ "3dlu,"+ // 7
+ "90dlu,"+ // 8
+ "7dlu,"+ // 9
+ "pref,"+ // 10
+ "7dlu"); // 11
+ CellConstraints cc = new CellConstraints();
+ PanelBuilder pb = new PanelBuilder(fl);
+// IhmFactory iF=IhmFactory.newInstance();
+ //final JTree tree = new JTree(new DatabaseTreeData(dm,wrapper));
+ list = new JList(data);
+ JButton pbCancel;
+
+ pb.addSeparator("Informations", cc.xyw(2,sepInfo,2));
+ pb.add(area = new JTextArea(), cc.xy(3,lineInfo));
+
+ pb.addSeparator("Recherches", cc.xyw(2,sepData,2));
+ pb.add(new JScrollPane(list), cc.xy(3,listLine,"fill, fill"));
+
+ final JButton pbOk = new JButton("Ok");
+
+ JPanel bPane = new JPanel(new FlowLayout(FlowLayout.CENTER));
+ bPane.add(pbOk);
+ bPane.add(pbCancel = new JButton(escapeAction));
+
+ pb.add(bPane, cc.xyw(2,buttonLine1,2));
+
+ area.setEditable(false);
+ area.setLineWrap(true);
+ area.setRows(3);
+ area.setBackground(getBackground());
+ area.setText("Sélectionnez dans la liste ci-dessous\n" +
+ "la recherche que vous souhaitez réafficher.");
+
+ list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
+ list.setCellRenderer(new MyCellRenderer());
+ list.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(MouseEvent evt) {
+ if(evt.getClickCount()==2 && evt.getButton()==MouseEvent.BUTTON1) {
+ pbOk.doClick();
+ } else if(evt.getClickCount()==1 && (evt.getButton()==MouseEvent.BUTTON2||evt.getButton()==MouseEvent.BUTTON3)) {
+// } else if(evt.isPopupTrigger()) {
+ Point clickPos = evt.getPoint();
+ int index = list.locationToIndex(clickPos);
+ final ListDisplayable ld = (ListDisplayable)list.getModel().getElementAt(index);
+ if(ld.isDeletable()) {
+ JPopupMenu pm = new JPopupMenu();
+ JMenuItem mnu = new JMenuItem("Supprimer cette requête");
+ mnu.addActionListener(new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ if(JOptionPane.showConfirmDialog(DlgSelectRequest.this,"Voulez-vous vraiment supprimer cette requête :\n"+ld.getDisplayName()+" ?")==JOptionPane.YES_OPTION) {
+ logger.debug("suppression");
+ RechercheModel rm = (RechercheModel)ld;
+ parentFrame.getSavedRequest(elementModel).delete(rm);
+ data.remove(rm);
+ list.setListData(data);
+ }
+ }
+ });
+ pm.add(mnu);
+ pm.show(list,clickPos.x,clickPos.y);
+ }
+ }
+ }
+ });
+ getRootPane().setDefaultButton(pbCancel);
+
+ setContentPane(pb.getPanel());
+
+ pbOk.addActionListener(new ActionListener() {
+ public void actionPerformed(ActionEvent evt) {
+ if(list.getSelectedValue()!=null) {
+ ret = true;
+ setVisible(false);
+ }
+ }
+ });
+
+ pack();
+ setLocationRelativeTo(getParent());
+ }
+
+ public boolean run() {
+ setVisible(true);
+ return ret;
+ }
+ public Object getSelectedItem() {
+ return list.getSelectedValue();
+ }
+ @Override
+ protected JRootPane createRootPane() {
+ KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0);
+ JRootPane rp = new JRootPane();
+ escapeAction = new AbstractAction("Annuler") {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+
+ public void actionPerformed(ActionEvent evt) {
+ setVisible(false);
+ }
+ };
+ rp.registerKeyboardAction(escapeAction,"TOTOTOTO",ks,JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
+ }
+ private class MyCellRenderer extends DefaultListCellRenderer {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+ public MyCellRenderer() {
+ super();
+
+ }
+ @Override
+ public Component getListCellRendererComponent(JList list,Object value,int index,boolean isSelected,boolean cellHasFocus) {
+ JLabel ancestor = (JLabel)super.getListCellRendererComponent(list,value,index,isSelected,cellHasFocus);
+ ListDisplayable ld = (ListDisplayable)value;
+ ImageIcon ii=null;
+ JLabel ret = null;
+ if(ld.getResource()==null) {
+ ret = new JLabel(ld.getDisplayName());
+ } else if(ld.getResource().equals(ImageResources.LST_EXPORT_P)) ii=exportPlugin;
+ else if(ld.getResource().equals(ImageResources.LST_SEARCH_P)) ii=searchPlugin;
+ else if(ld.getResource().equals(ImageResources.LST_SEARCH_SAV)) ii=searchSaved;
+ ret = new JLabel(ld.getDisplayName(),ii,JLabel.LEFT);
+
+ ret.setBorder(ancestor.getBorder());
+ ret.setBackground(ancestor.getBackground());
+ ret.setForeground(ancestor.getForeground());
+
+// BorderLayout bl = new BorderLayout();
+// bl.setHgap(0); bl.setVgap(0);
+// JPanel pane = new JPanel(bl);
+// pane.setBackground(ancestor.getBackground());
+// pane.add(ret,BorderLayout.CENTER);
+
+// if(ld.isDeletable()) {
+// JLabel delete = new JLabel(deleteIcon);
+// delete.setToolTipText("Supprimer cette recherche");
+// delete.addMouseListener(new MouseAdapter() {
+// public void mouseClicked(MouseEvent e) {
+// logger.debug("delete clicked !");
+// if(e.getClickCount()==1) {
+// if(aValue instanceof RechercheModel) {
+// RechercheModel rm = (RechercheModel)aValue;
+// if(JOptionPane.showConfirmDialog(DlgSelectRequest.this,"Voulez-vous vraiment supprimer cette requête :\n"+rm.getName()+" ?")==JOptionPane.YES_OPTION) {
+// parentFrame.getSavedRequest(etatModel).delete(rm);
+// }
+// }
+// }
+// }
+// });
+// pane.add(delete,BorderLayout.EAST);
+// }
+ return ret;
+ }
+
+
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui;
+
+import com.lowagie.text.DocumentException;
+import fr.gouv.finances.dgfip.utils.Dest;
+import fr.gouv.finances.cp.xemelios.ui.xhtmlviewer.XemeliosUserAgent;
+import fr.gouv.finances.cp.xemelios.ui.xhtmlviewer.XemeliosXhtmlPanel;
+import java.awt.BorderLayout;
+import java.awt.Dimension;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.ItemEvent;
+import java.awt.event.ItemListener;
+import java.awt.event.MouseListener;
+import java.awt.event.MouseMotionListener;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+import java.util.HashSet;
+import java.util.Hashtable;
+import java.util.Set;
+import java.util.StringTokenizer;
+
+import javax.swing.JButton;
+import javax.swing.JComboBox;
+import javax.swing.JInternalFrame;
+import javax.swing.JTextField;
+import javax.swing.JToolBar;
+import javax.swing.text.html.FormSubmitEvent;
+
+import org.apache.log4j.Logger;
+import org.xhtmlrenderer.pdf.ITextRenderer;
+import org.xhtmlrenderer.simple.FSScrollPane;
+import org.xhtmlrenderer.swing.LinkListener;
+import org.xhtmlrenderer.swing.ScalableXHTMLPanel;
+import org.xhtmlrenderer.swing.ScaleChangeEvent;
+import org.xhtmlrenderer.swing.ScaleChangeListener;
+
+import fr.gouv.finances.dgfip.utils.NavigationContext;
+import fr.gouv.finances.cp.utils.StartUrl;
+import fr.gouv.finances.cp.utils.ui.IhmFactory;
+import fr.gouv.finances.dgfip.xemelios.common.ToolException;
+import fr.gouv.finances.dgfip.xemelios.ui.ImageResources;
+import fr.gouv.finances.dgfip.xemelios.utils.FileUtils;
+import fr.gouv.finances.dgfip.xemelios.utils.XmlUtils;
+import java.awt.Toolkit;
+import java.awt.datatransfer.StringSelection;
+import javax.swing.AbstractAction;
+import javax.swing.Action;
+import javax.swing.JComponent;
+import javax.swing.KeyStroke;
+import org.w3c.dom.DocumentFragment;
+import org.xhtmlrenderer.context.StyleReference;
+import org.xhtmlrenderer.pdf.ITextOutputDevice;
+import org.xhtmlrenderer.pdf.ITextUserAgent;
+import org.xhtmlrenderer.swing.SelectionHighlighter;
+
+/**
+ * Permet d'afficher du HTML
+ *
+ * @author chm
+ */
+public class HtmlViewer extends JInternalFrame implements UpdatableToolbar, ScaleChangeListener {
+
+ private static Logger logger = Logger.getLogger(HtmlViewer.class);
+ public static final String PARAM_DESTINATION = "browser-destination";
+ public static final String VALUE_DESTINATION_EXTERNAL = "external";
+ public static final String VALUE_DESTINATION_INTERNAL = "internal";
+ public static final boolean EXTERNAL_DESTINATION = true;
+ public static final boolean INTERNAL_DESTINATION = false;
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 3257008752400807221L;
+ private static final int LOCAL_WIDTH = 540;
+ private static final int LOCAL_HEIGHT = 320;
+ private URL documentUrl;
+ private final XemeliosXhtmlPanel xhtmlRenderer;
+ private JTextField dfUrl;
+ private MainWindow mainWindow;
+ private JButton pbPrint, pbPrevious, pbNext;
+ private XemeliosUserAgent userAgent = null;
+ private JComboBox cbxZoom;
+ private ScaleFactor[] availableScales;
+ private NavigationContext nc;
+ private SelectionHighlighter highlighter;
+ private JButton pbCopy;
+ private static final boolean IS_SELECTION_ENABLED = true;
+
+ /**
+ *
+ */
+ public HtmlViewer(URL documentToDisplay, String title, NavigationContext nc, MainWindow mw) {
+ this(documentToDisplay, title, mw);
+ this.nc = nc;
+ }
+
+ public HtmlViewer(URL documentToDisplay, String title, MainWindow mw) {
+ super(title, true, true, true, true);
+ documentUrl = documentToDisplay;
+ mainWindow = mw;
+ userAgent = new XemeliosUserAgent(mainWindow, this, this, mainWindow.getConnectedUser());
+ xhtmlRenderer = new XemeliosXhtmlPanel(userAgent, this);
+ initializeComponents();
+ setDefaultCloseOperation(DISPOSE_ON_CLOSE);
+ }
+
+ public HtmlViewer(String uri, String title, MainWindow mw) {
+ super(title, true, true, true, true);
+ mainWindow = mw;
+ userAgent = new XemeliosUserAgent(mainWindow, this, this, mainWindow.getConnectedUser());
+ xhtmlRenderer = new XemeliosXhtmlPanel(userAgent, this);
+ initializeComponents();
+ setDefaultCloseOperation(DISPOSE_ON_CLOSE);
+ Dest dest = userAgent.calculateQuery(uri);
+ try {
+ browseUrl(dest);
+ } catch (Throwable t) {
+ logger.error("in HtmlViewer(String,String,MainWindow)", t);
+ }
+ }
+
+ public static ScaleFactor[] initializeScales() {
+ ScaleFactor[] scales = new ScaleFactor[11];
+ int i = 0;
+ scales[i++] = new ScaleFactor(2.0d, "200%");
+ scales[i++] = new ScaleFactor(1.5d, "150%");
+ scales[i++] = new ScaleFactor(1.0d, "100%");
+ scales[i++] = new ScaleFactor(0.85d, "85%");
+ scales[i++] = new ScaleFactor(0.75d, "75%");
+ scales[i++] = new ScaleFactor(0.5d, "50%");
+ scales[i++] = new ScaleFactor(0.33d, "33%");
+ scales[i++] = new ScaleFactor(0.25d, "25%");
+ scales[i++] = new ScaleFactor(ScaleFactor.PAGE_WIDTH, "Largeur page");
+ scales[i++] = new ScaleFactor(ScaleFactor.PAGE_HEIGHT, "Hauteur page");
+ scales[i++] = new ScaleFactor(ScaleFactor.PAGE_WHOLE, "Page entière");
+ return scales;
+ }
+
+ @Override
+ public void scaleChanged(ScaleChangeEvent evt) {
+ if (evt.getComponent() == xhtmlRenderer) {
+ double scale = evt.getScale();
+ logger.debug("received scaleChanged with " + scale);
+ int ix = -1;
+ for (int i = 0; i < availableScales.length; i++) {
+ ScaleFactor sf = availableScales[i];
+ if (sf.getFactor() == scale) {
+ ix = i;
+ break;
+ }
+ }
+ ItemListener[] iListeners = cbxZoom.getItemListeners();
+ for (ItemListener il : iListeners) {
+ cbxZoom.removeItemListener(il);
+ }
+ if (ix == -1) {
+ //TODO
+ int scalePolicy = xhtmlRenderer.getScalePolicy();
+// int scalePolicy = ScalableXHTMLPanel.SCALE_POLICY_NONE;
+ switch (scalePolicy) {
+ case ScalableXHTMLPanel.SCALE_POLICY_FIT_WIDTH:
+ ix = 8;
+ break;
+ case ScalableXHTMLPanel.SCALE_POLICY_FIT_HEIGHT:
+ ix = 9;
+ break;
+ case ScalableXHTMLPanel.SCALE_POLICY_FIT_WHOLE:
+ ix = 10;
+ break;
+ }
+ }
+ cbxZoom.setSelectedIndex(ix);
+ for (ItemListener il : iListeners) {
+ cbxZoom.addItemListener(il);
+ }
+ }
+ }
+
+ protected void initializeComponents() {
+ ScaleFactor[] scales = initializeScales();
+ availableScales = scales;
+ IhmFactory iF = IhmFactory.newInstance();
+ MouseListener[] lls = xhtmlRenderer.getMouseListeners();
+ for (int i = 0; i < lls.length; i++) {
+ MouseListener ll = lls[i];
+ if (ll instanceof LinkListener) {
+ xhtmlRenderer.addMouseMotionListener((MouseMotionListener) ll);
+ }
+ }
+ if (IS_SELECTION_ENABLED) {
+ highlighter = new SelectionHighlighter();
+ highlighter.install(xhtmlRenderer);
+ xhtmlRenderer.addMouseListener(highlighter);
+ }
+ FSScrollPane scroller;
+ getContentPane().setLayout(new BorderLayout());
+ JToolBar tb = new JToolBar();
+ tb.add(pbPrevious = new JButton(IhmFactory.getIconFromResource(ImageResources.BRW_PREVIOUS)));
+ tb.add(pbNext = new JButton(IhmFactory.getIconFromResource(ImageResources.BRW_NEXT)));
+ tb.add(pbPrint = new JButton(IhmFactory.getIconFromResource(ImageResources.PRINT)));
+ if (IS_SELECTION_ENABLED) {
+ final Action copyAction = new AbstractAction(null, IhmFactory.getIconFromResource(ImageResources.EDIT_COPY)) {
+
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ DocumentFragment df = highlighter.getSelectionRange().extractContents();
+ StringSelection ss = new StringSelection(XmlUtils.getStringRepresentation(df));
+ Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, ss);
+ }
+ };
+ tb.add(pbCopy = new JButton(copyAction));
+ pbCopy.setToolTipText("Copier");
+
+ final Action selectAllAction = new AbstractAction(null, IhmFactory.getIconFromResource(ImageResources.EDIT_SELECT_ALL)) {
+
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ highlighter.selectAll();
+ }
+ };
+ JButton pbSelectAll = new JButton(selectAllAction);
+ pbSelectAll.setToolTipText("Tout sélectionner");
+ tb.add(pbSelectAll);
+
+ getRootPane().registerKeyboardAction(copyAction, "copy", KeyStroke.getKeyStroke("ctrl C"), JComponent.WHEN_IN_FOCUSED_WINDOW);
+ getRootPane().registerKeyboardAction(selectAllAction, "selectAll", KeyStroke.getKeyStroke("ctrl A"), JComponent.WHEN_IN_FOCUSED_WINDOW);
+ }
+ tb.addSeparator();
+ tb.add(iF.newLabel("URL ", "normal"));
+ tb.add(dfUrl = new JTextField());
+ dfUrl.setEditable(false);
+ Dimension dim = dfUrl.getMinimumSize();
+ dfUrl.setMinimumSize(new Dimension(100, (int) dim.getHeight()));
+ tb.addSeparator();
+ tb.add(iF.newLabel("Zoom ", "normal"));
+ cbxZoom = new JComboBox(scales);
+ // TODO
+ cbxZoom.addItemListener(new ItemListener() {
+
+ @Override
+ public void itemStateChanged(ItemEvent e) {
+ if (e.getStateChange() == ItemEvent.SELECTED) {
+ ScaleFactor factor = (ScaleFactor) e.getItem();
+ if (factor.getFactor() == ScaleFactor.PAGE_WIDTH) {
+ xhtmlRenderer.setScalePolicy(ScalableXHTMLPanel.SCALE_POLICY_FIT_WIDTH);
+ xhtmlRenderer.doLayout();
+ } else if (factor.getFactor() == ScaleFactor.PAGE_HEIGHT) {
+ xhtmlRenderer.setScalePolicy(ScalableXHTMLPanel.SCALE_POLICY_FIT_HEIGHT);
+ xhtmlRenderer.doLayout();
+ } else if (factor.getFactor() == ScaleFactor.PAGE_WHOLE) {
+ xhtmlRenderer.setScalePolicy(ScalableXHTMLPanel.SCALE_POLICY_FIT_WHOLE);
+ xhtmlRenderer.doLayout();
+ } else {
+ xhtmlRenderer.setScale(factor.getFactor());
+ }
+ }
+ }
+ });
+ cbxZoom.setSelectedIndex(2);
+ tb.add(cbxZoom);
+ getContentPane().add(tb, BorderLayout.PAGE_START);
+ getContentPane().add(scroller = new FSScrollPane(xhtmlRenderer), BorderLayout.CENTER);
+ scroller.setPreferredSize(new Dimension(LOCAL_WIDTH, LOCAL_HEIGHT));
+ scroller.setIgnoreRepaint(false);
+ pbPrint.addActionListener(new ActionListener() {
+
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ printToPDF();
+ }
+ });
+ pbPrint.setToolTipText("Imprimer");
+ pbPrevious.addActionListener(new ActionListener() {
+
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ goBack();
+ }
+ });
+ pbNext.addActionListener(new ActionListener() {
+
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ goForward();
+ }
+ });
+ pbPrevious.setEnabled(false);
+ pbNext.setEnabled(false);
+ if (documentUrl != null) {
+ try {
+ browseUrl(documentUrl, INTERNAL_DESTINATION);
+ } catch (Throwable t) {
+ }
+ }
+ pack();
+ }
+
+ protected void printToPDF() {
+ try {
+ File tmp = File.createTempFile("xemelios-data-", ".pdf", FileUtils.getTempDir());
+ OutputStream os = new FileOutputStream(tmp);
+ ITextRenderer renderer = new ITextRenderer();
+ CustomUserAgentCallback callback = new CustomUserAgentCallback(renderer.getOutputDevice());
+ callback.setSharedContext(renderer.getSharedContext());
+ renderer.getSharedContext().setUserAgentCallback(callback);
+ StyleReference css = new StyleReference(callback);
+ String url = dfUrl.getText();
+ if (url.indexOf("#") > 0) {
+ url = url.substring(0, url.indexOf("#"));
+ }
+ File fToPDFize = new File(new URL(url).toURI());
+ logger.debug("pdf'ising " + fToPDFize.toURI().toURL().toExternalForm());
+ if (fToPDFize.exists()) {
+ renderer.setDocument(fToPDFize);
+ renderer.layout();
+ renderer.createPDF(os, true);
+// renderer.finishPDF();
+ os.flush(); os.close();
+ StartUrl.startUrl(tmp.toURI().toURL().toExternalForm());
+ }
+ } catch (IOException ioEx) {
+ logger.error("while printing to PDF: ", ioEx);
+ } catch (ToolException tEx) {
+ logger.error("while printing to PDF: ", tEx);
+ } catch (URISyntaxException uriEx) {
+ logger.error("while printing to PDF: ", uriEx);
+ } catch (DocumentException docEx) {
+ logger.error("while printing to PDF: ", docEx);
+ }
+ }
+
+ protected void browseUri(URI uri) throws ToolException {
+ String query = uri.getQuery();
+ Dest dest = userAgent.calculateQuery(query);
+ browseUrl(dest);
+ }
+
+ protected void browseUrl(Dest dest) throws ToolException {
+ browseUrl(dest.url, dest.toExternal);
+ }
+
+ protected void browseUrl(URL url, boolean toExternalDestination) throws ToolException {
+ try {
+ if(toExternalDestination) {
+ StartUrl.startUrl(url.toExternalForm());
+ } else {
+ String eForm = url.toExternalForm();
+ dfUrl.setText(eForm);
+ xhtmlRenderer.setDocument(eForm);
+ }
+ } catch (Exception ioEx) {
+ throw new ToolException(ioEx, ToolException.ERROR_INVALID_XHTML);
+ }
+ }
+
+ protected Dest browseFormSubmission(FormSubmitEvent fse) throws UnsupportedEncodingException {
+ StringTokenizer st = new StringTokenizer(fse.getData(), "&");
+ Hashtable<String, String> params = new Hashtable<String, String>();
+ while (st.hasMoreTokens()) {
+ String token = st.nextToken();
+ int pos = token.indexOf('=');
+ String paramName = token.substring(0, pos);
+ String value = URLDecoder.decode(token.substring(pos + 1), "UTF-8");
+ // at this point, only one value per param is allowed
+ params.put(paramName, value);
+ }
+ String path = params.get("path");
+ if (path != null) {
+ Set<String> keys = params.keySet();
+ Set<String> toRemove = new HashSet<String>();
+ for (String key : keys) {
+ if (key.equals("path")) {
+ continue;
+ }
+ if (path.indexOf("%" + key + "%") >= 0) {
+ path = path.replaceAll("%" + key + "%", params.get(key));
+ toRemove.add(key);
+ }
+ }
+ if (!toRemove.isEmpty()) {
+ keys.removeAll(toRemove);
+ }
+ params.put("path", URLEncoder.encode(path, "UTF-8"));
+ }
+ path = "";
+ for (String key : params.keySet()) {
+ path = path + key + "=" + params.get(key) + "&";
+ }
+ path = path.substring(0, path.length() - 1);
+ return userAgent.calculateQuery(path);
+ }
+
+ /**
+ * Opens designed page in external browser by filtering it through outputter.xsl
+ * @param page The page to open
+ */
+ protected void output(NavigationContext ctx) {
+ Hashtable<String, Object> params = new Hashtable<String, Object>();
+ params.put(PARAM_DESTINATION, VALUE_DESTINATION_EXTERNAL);
+ Dest dest = userAgent.generateDestContext(ctx, params, EXTERNAL_DESTINATION);
+ try {
+ browseUrl(dest.url, EXTERNAL_DESTINATION);
+ } catch (ToolException tEx) {
+ // on se fout que le xhtml ne soit pas bon, c'est le probleme du browser
+ }
+ }
+
+ protected void goBack() {
+ if (userAgent.hasBack()) {
+ xhtmlRenderer.setDocument(userAgent.getBack());
+ } else {
+ updateToolbarButtons();
+ }
+ }
+
+ protected void goForward() {
+ if (userAgent.hasForward()) {
+ xhtmlRenderer.setDocument(userAgent.getForward());
+ } else {
+ updateToolbarButtons();
+ }
+ }
+
+ @Override
+ public void updateToolbarButtons() {
+ pbPrevious.setEnabled(userAgent.hasBack());
+ pbNext.setEnabled(userAgent.hasForward());
+ }
+
+ @Override
+ public void setBaseUrl(String url) {
+ dfUrl.setText(url);
+ }
+
+ class CustomUserAgentCallback extends ITextUserAgent {
+
+ public CustomUserAgentCallback(ITextOutputDevice outputDevice) {
+ super(outputDevice);
+ }
+
+ @Override
+ public String resolveURI(String uri) {
+ if (uri.startsWith("xemelios:")) {
+ String servlet = null;
+ String sTmp = uri;
+ int start = uri.indexOf('?');
+ if (start >= 0) {
+ servlet = uri.substring(uri.indexOf("/") + 1, start);
+ sTmp = uri.substring(start + 1);
+ }
+ if ("resource".equals(servlet)) {
+ String ret = null;
+ try {
+ File resourceDir = new File(mainWindow.getEnvProperties().getProperty("xemelios.resources.location"));
+ File res = new File(resourceDir, sTmp);
+ ret = res.toURI().toURL().toExternalForm();
+ } catch (Throwable t) {
+ }
+ return ret;
+ } else {
+ return super.resolveURI(uri);
+ }
+ } else {
+ return super.resolveURI(uri);
+ }
+ }
+ }
+
+ public static class ScaleFactor {
+
+ public static final double PAGE_WIDTH = -2.0d;
+ public static final double PAGE_HEIGHT = -3.0d;
+ public static final double PAGE_WHOLE = -4.0d;
+ private Double factor;
+ private String libelle;
+
+ public ScaleFactor(double factor, String libelle) {
+ super();
+ this.factor = new Double(factor);
+ this.libelle = libelle;
+ }
+
+ public double getFactor() {
+ return factor.doubleValue();
+ }
+
+ public String getLibelle() {
+ return libelle;
+ }
+
+ @Override
+ public String toString() {
+ return getLibelle();
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui;
+
+import fr.gouv.finances.dgfip.xemelios.common.config.Loader;
+import fr.gouv.finances.dgfip.xemelios.importers.XemeliosArchiveImporter.Errors;
+import fr.gouv.finances.dgfip.xemelios.tools.AbstractTool;
+import java.awt.BorderLayout;
+import java.awt.Component;
+import java.awt.Cursor;
+import java.awt.Dimension;
+import java.awt.DisplayMode;
+import java.awt.Frame;
+import java.awt.GraphicsConfiguration;
+import java.awt.GraphicsDevice;
+import java.awt.GraphicsEnvironment;
+import java.awt.Rectangle;
+import java.awt.Toolkit;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.ComponentAdapter;
+import java.awt.event.ComponentEvent;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.reflect.Constructor;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Properties;
+import java.util.StringTokenizer;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipException;
+import java.util.zip.ZipFile;
+
+import javax.swing.AbstractAction;
+import javax.swing.Action;
+import javax.swing.Box;
+import javax.swing.Icon;
+import javax.swing.ImageIcon;
+import javax.swing.JDesktopPane;
+import javax.swing.JFileChooser;
+import javax.swing.JFrame;
+import javax.swing.JInternalFrame;
+import javax.swing.JLabel;
+import javax.swing.JLayeredPane;
+import javax.swing.JMenu;
+import javax.swing.JMenuBar;
+import javax.swing.JMenuItem;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JTextField;
+import javax.swing.SwingUtilities;
+import javax.swing.border.EmptyBorder;
+import javax.swing.border.EtchedBorder;
+import javax.swing.filechooser.FileFilter;
+import javax.swing.filechooser.FileSystemView;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathConstants;
+import javax.xml.xpath.XPathFactory;
+
+import org.apache.log4j.Logger;
+import org.apache.log4j.xml.DOMConfigurator;
+import org.jdesktop.swingworker.SwingWorker;
+import org.netbeans.spi.wizard.WizardException;
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+
+import fr.gouv.finances.dgfip.utils.NavigationContext;
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import fr.gouv.finances.cp.utils.StartUrl;
+import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
+import fr.gouv.finances.cp.utils.ui.IhmFactory;
+import fr.gouv.finances.cp.utils.ui.JWaiter;
+import fr.gouv.finances.cp.utils.ui.RamViewer;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import fr.gouv.finances.cp.xemelios.Splash;
+import fr.gouv.finances.cp.xemelios.auth.LoginDialog;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import fr.gouv.finances.dgfip.xemelios.common.PJRef;
+import fr.gouv.finances.dgfip.xemelios.common.ToolException;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentsModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.EnvironmentDomain;
+import fr.gouv.finances.dgfip.xemelios.common.config.EtatModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.PersonnalConfigParser;
+import fr.gouv.finances.dgfip.xemelios.common.config.PersonnalConfigurationModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.SavedRequestsModel;
+import fr.gouv.finances.dgfip.xemelios.common.listeners.StartListener;
+import fr.gouv.finances.cp.xemelios.controls.DlgControl;
+import fr.gouv.finances.dgfip.xemelios.controls.core.MainControl;
+import fr.gouv.finances.cp.xemelios.controls.MainControlWrapper;
+import fr.gouv.finances.dgfip.xemelios.data.DataAccessException;
+import fr.gouv.finances.dgfip.xemelios.data.DataConfigurationException;
+import fr.gouv.finances.dgfip.xemelios.data.DataImpl;
+import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
+import fr.gouv.finances.dgfip.xemelios.importers.EtatImporteur;
+import fr.gouv.finances.cp.xemelios.importers.ImportServiceSwingProvider;
+import fr.gouv.finances.cp.xemelios.starter.Bootstrap;
+import fr.gouv.finances.cp.xemelios.ui.admin.DlgSystemConfiguration;
+import fr.gouv.finances.cp.xemelios.ui.collectivites.DlgSelectNavigationTarget;
+import fr.gouv.finances.cp.xemelios.ui.export.DlgSearchConfig;
+import fr.gouv.finances.cp.xemelios.ui.firststart.PnlFirstAbo;
+import fr.gouv.finances.cp.xemelios.ui.firststart.PnlFirstConfigProxy;
+import fr.gouv.finances.cp.xemelios.ui.firststart.PnlPresentation;
+import fr.gouv.finances.cp.xemelios.ui.importDialog.ImportDialog;
+import fr.gouv.finances.cp.xemelios.ui.importDialog.ImportFile;
+import fr.gouv.finances.cp.xemelios.ui.navigate.Navigable;
+import fr.gouv.finances.cp.xemelios.updater.AbstractConfigurator;
+import fr.gouv.finances.cp.xemelios.updater.DlgConfirmDownloadUpdate;
+import fr.gouv.finances.cp.xemelios.updater.GeneratorHelpIndex;
+import fr.gouv.finances.cp.xemelios.updater.PnlUpdaterProgress;
+import fr.gouv.finances.cp.xemelios.updater.UpdateUtil;
+import fr.gouv.finances.dgfip.utils.ClassPathUtils;
+import fr.gouv.finances.dgfip.utils.IoUtils;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
+import fr.gouv.finances.dgfip.utils.xml.transform.CustomURIResolver;
+import fr.gouv.finances.dgfip.xemelios.auth.AuthEngine;
+import fr.gouv.finances.dgfip.xemelios.auth.UnauthorizedException;
+import fr.gouv.finances.dgfip.xemelios.auth.impl.std.db.ui.DlgConfigAuthentication;
+import fr.gouv.finances.dgfip.xemelios.auth.impl.std.db.ui.PnlConfigAuthentication;
+import fr.gouv.finances.dgfip.xemelios.data.impl.pool.Pool;
+import fr.gouv.finances.dgfip.xemelios.data.impl.pool.PoolManager;
+import fr.gouv.finances.dgfip.xemelios.importers.XemeliosArchiveImporter;
+import fr.gouv.finances.dgfip.xemelios.tools.MenuTitle;
+import fr.gouv.finances.dgfip.xemelios.tools.ToolConstants;
+import fr.gouv.finances.dgfip.xemelios.ui.ImageResources;
+import fr.gouv.finances.dgfip.xemelios.utils.FileUtils;
+import java.awt.FlowLayout;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.FilenameFilter;
+import java.io.OutputStreamWriter;
+import java.io.PrintWriter;
+import java.net.UnknownHostException;
+import java.nio.charset.Charset;
+import java.sql.Connection;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.Map;
+import java.util.jar.JarFile;
+import java.util.jar.Manifest;
+import java.util.zip.GZIPInputStream;
+import javax.swing.Timer;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.transform.stream.StreamSource;
+import org.netbeans.api.wizard.WizardDisplayer;
+import org.netbeans.spi.wizard.Wizard;
+import org.netbeans.spi.wizard.WizardPage;
+import org.w3c.dom.NodeList;
+
+/**
+ * Main Xemelios window
+ *
+ * @author christophe.marchand Date: 15 aout 2004 Time: 11:46:18
+ */
+public class MainWindow extends JFrame {
+
+ private static Logger logger = null;
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 3977304325938558517L;
+ public static final transient String MAIN_WINDOW_POSITION = "main.window.last.location";
+ public static final int DEFAULT_WIDTH = 800;
+ public static final int DEFAULT_HEIGHT = 600;
+ private Action actQuitter;
+ private JDesktopPane desk;
+ private JTextField statusField;
+ private StartListener startListener;
+ private DocumentsModel docModels;
+ protected File lastInputDirectory = null;
+ private JMenu searchMenu;
+ private JMenu windowMenu;
+ private JMenu browseMenu;
+ private JMenu importerMenu = null;
+ private JMenu controlerMenu = null;
+ private JMenuItem mnuClean = null;
+ private JMenuItem mnuExporterFichier = null;
+ private JMenuItem mnuSupprimer = null;
+ private JMenu mnuConfigExports = null;
+ private JLabel backImage;
+ private JWaiter waiter;
+ private PersonnalConfigurationModel config;
+ private XemeliosUser connectedUser = null;
+ // Ne pas renommer, utilise sans lien dans AbstractTool
+ public static MainWindow instance = null;
+ public XPathFactory xpf;
+ private Properties criteriasInputValues;
+ private String updateUrl; // componentsModelFileName,
+ private PropertiesExpansion applicationProperties;
+ private PnlUpdaterProgress pup;
+ // le panel dans lequel on vient mettre tout ce qui doit être à droite
+ private JPanel indicatorPanel;
+ /**
+ * Separateur par defaut pour le CSV
+ */
+ public static String fieldSeparator = ";";
+
+ public MainWindow(PropertiesExpansion applicationProperties, String title, StartListener sl, String[] args) {
+ super(title);
+ this.applicationProperties = applicationProperties;
+ if (instance != null) {
+ throw new RuntimeException("Only one instance of MainWindow can exists");
+ }
+ instance = this;
+ this.startListener = sl;
+ startListener.pushProgress();
+ xpf = FactoryProvider.getXPathFactory();
+ try {
+ loadConfig();
+ startListener.pushProgress();
+ checkUpdateScript();
+ startListener.pushProgress();
+ initComponents();
+ startListener.pushProgress();
+ Properties homeProperties = getHomeProperties();
+ if(lastInputDirectory==null && homeProperties.getProperty(Constants.SYS_PROP_LAST_INPUT_DIRECTORY)!=null && homeProperties.getProperty(Constants.SYS_PROP_LAST_INPUT_DIRECTORY).length() > 0){
+ lastInputDirectory=new File(homeProperties.getProperty(Constants.SYS_PROP_LAST_INPUT_DIRECTORY));
+ }
+ try {
+ if (!checkPassword()) {
+ startListener.completeProgress();
+ runExit();
+ }
+ } catch (Throwable t) {
+ new DisplayExceptionDlg(this, t);
+ runExit();
+ }
+ initMenus2();
+ setMenusAccess();
+ startListener.pushProgress();
+ // on regarde si c'est le premier démarrage.
+ if (!"true".equals(getEnvProperties().getProperty(Constants.SYS_PROP_FIRST_START))) {
+ doFirstStartConfiguration();
+ }
+ if (!"true".equals(applicationProperties.getProperty(Constants.SYS_PROP_SKIP_UPDATE_CHECK))) {
+ if(!Constants.MAJ_NONE.equals(applicationProperties.getProperty(Constants.SYS_PROP_MAJ_STRATEGY))) {
+ checkUpdateAvailability();
+ }
+ }
+ startListener.completeProgress();
+ if (args.length > 0) {
+ starterImport(args);
+ }
+ } catch (DataConfigurationException dcEx) {
+ Throwable ex = dcEx;
+ while (ex.getCause() != null) {
+ ex = ex.getCause();
+ }
+ ex.printStackTrace();
+ logger.error("<init>",dcEx);
+ System.exit(1);
+ }
+ }
+
+ /**
+ * Cette methode charge la configuration depuis le fichier de conf
+ * @throws DataConfigurationException
+ */
+ protected void loadConfig() throws DataConfigurationException {
+ if (applicationProperties.getProperty(Constants.SYS_PROP_LOG4J) != null) {
+ String log4jConfFile = applicationProperties.getProperty(Constants.SYS_PROP_LOG4J);
+ DOMConfigurator.configure(log4jConfFile);
+ logger = Logger.getLogger(this.getClass());
+ logger.info("log4J initialise");
+ }
+// componentsModelFileName = applicationProperties.getProperty(Constants.SYS_PROP_COMPONENTS_FILENAME);
+ updateUrl = applicationProperties.getProperty(Constants.SYS_PROP_UPDATE_SOURCE);
+ docModels = getDocumentsInfos(applicationProperties.getProperty(Constants.SYS_PROP_DOC_DEF_DIR));
+ initDataLayer();
+ applyPatches();
+logger.debug("Starting auth engine");
+ if (DataLayerManager.getImplementation().getParameterValue(AuthEngine.Holder.DEFAULT_AUTH_ENGINE_SWING_CLASS_NAME_PROPERTY) == null) {
+ logger.debug("we must configure first auth-engine");
+ Connection con = null;
+ try {
+ con = PoolManager.getInstance().getConnection();
+ if (PnlConfigAuthentication.isLocalComputerServer(con)) {
+ logger.debug("we are on server");
+ // on est dans le cas où on démarre pour le première fois sur le serveur
+ try {
+ DlgConfigAuthentication dlgAuthConfig = new DlgConfigAuthentication(null, true, null);
+ logger.debug("DlgConfigAuthentication instanciated");
+ boolean ret = dlgAuthConfig.run();
+ if (!ret) {
+ throw new DataConfigurationException("Refus de la configuration de l'authentification");
+ }
+ logger.debug("DlgConfigAuthentication.run terminated");
+ } catch(Throwable t) {
+ logger.error("paramétrage authentification", t);
+ }
+ } else {
+ logger.debug("we are on client");
+ JOptionPane.showMessageDialog(null, "<html>L'administrateur de XeMeLios n'a pas encore configuré le serveur.<br/>Veuillez vous reconnecter lorsqu'il aura terminé le paramétrage.</html>", "XéMéLios non prêt", JOptionPane.ERROR_MESSAGE);
+ throw new DataConfigurationException("XeMeLios authentification non configurée");
+ }
+ } finally {
+ if (con != null) {
+ PoolManager.getInstance().releaseConnection(con);
+ }
+ }
+ }
+ try {
+ AuthEngine.Holder.init(applicationProperties);
+ } catch(RuntimeException re) {
+ JOptionPane.showMessageDialog(null, re.getMessage(), "Erreur de démarrage de l'authentification", JOptionPane.ERROR_MESSAGE);
+ throw re;
+ }
+ logger.debug("Loading personnal config");
+ loadPersonnalConfig();
+ }
+
+ protected void initComponents() {
+ criteriasInputValues = loadCriteriasInputValues();
+ IhmFactory iF = IhmFactory.newInstance();
+ initActions();
+ startListener.pushProgress();
+ desk = new JDesktopPane();
+ desk.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
+// desk.setBackground(new Color(0xF4, 0xF5, 0xF0)); // fond 1
+// desk.setBackground(new Color(0xE8, 0xE7, 0xF7)); // fond 2
+// ImageIcon image = IhmFactory.getIconFromResource(ImageResources.LOGO_PETIT); // fond 0
+// desk.setBackground(new Color(0xF2, 0xF2, 0xF0));
+ ImageIcon image = IhmFactory.getIconFromResource(ImageResources.SPLASH); // fond 3
+ backImage = new JLabel(image);
+ backImage.setBounds(0, 0, image.getIconWidth(), image.getIconHeight());
+ desk.add(backImage, JLayeredPane.FRAME_CONTENT_LAYER);
+ initMenus1();
+ startListener.pushProgress();
+ addWindowListener(new WindowAdapter() {
+
+ @Override
+ public void windowClosed(WindowEvent e) {
+ }
+
+ @Override
+ public void windowClosing(WindowEvent e) {
+ runExit();
+ logger.debug("closing");
+ }
+ });
+ desk.addComponentListener(new ComponentAdapter() {
+
+ @Override
+ public void componentResized(ComponentEvent evt) {
+ Dimension dim = evt.getComponent().getSize();
+ Dimension imgSize = backImage.getSize();
+ backImage.setLocation((int) (dim.getWidth() - imgSize.getWidth()) / 2, (int) (dim.getHeight() - imgSize.getHeight()) / 2);
+ }
+ });
+ startListener.pushProgress();
+ JPanel inner = new JPanel(new BorderLayout());
+ JPanel status = new JPanel(new BorderLayout());
+ startListener.pushProgress();
+ status.add(statusField = new JTextField(30), BorderLayout.WEST);
+ startListener.pushProgress();
+ statusField.setEditable(false);
+ statusField.setBorder(new EmptyBorder(0, 0, 0, 0));
+ startListener.pushProgress();
+ indicatorPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
+ indicatorPanel.add(waiter = new JWaiter());
+ status.add(indicatorPanel, BorderLayout.EAST);
+ if ("true".equals(applicationProperties.getProperty(Constants.SYS_PROP_ADMIN_MENU_GC))) {
+ indicatorPanel.add(new RamViewer());
+ }
+ if ("true".equals(applicationProperties.getProperty(Constants.SYS_PROP_SHOW_POOL_STATUS))) {
+ indicatorPanel.add(new PoolStatDisplayer());
+ }
+ startListener.pushProgress();
+ pup = new PnlUpdaterProgress();
+ pup.setVisible(false);
+ indicatorPanel.add(pup);
+ status.setBorder(new EtchedBorder(EtchedBorder.LOWERED));
+ inner.add(status, BorderLayout.SOUTH);
+ startListener.pushProgress();
+ inner.add(desk, BorderLayout.CENTER);
+ setContentPane(inner);
+ startListener.pushProgress();
+
+ // dimensionnement de la fenetre
+
+ Properties props = getHomeProperties();
+
+ Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
+ GraphicsConfiguration gc = getGraphicsConfiguration();
+ GraphicsDevice gd = gc.getDevice();
+ DisplayMode dm = gd.getDisplayMode();
+ GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
+ Rectangle rect = ge.getMaximumWindowBounds();
+
+ Rectangle lastLocation = null;
+ if (props.getProperty(MAIN_WINDOW_POSITION) != null) {
+ // syntax is "(x,y,width,height)"
+ String s = props.getProperty(MAIN_WINDOW_POSITION);
+ s = s.substring(1, s.length() - 1);
+ String[] sa = s.split(",");
+ try {
+ int x = Integer.parseInt(sa[0]);
+ int y = Integer.parseInt(sa[1]);
+ int width = Integer.parseInt(sa[2]);
+ int height = Integer.parseInt(sa[3]);
+ lastLocation = new Rectangle(x, y, width, height);
+ // si le rectangle enregistré est plus grand que l'ecran, on ne restaure pas la position
+ if (lastLocation.getWidth() > rect.getWidth() || lastLocation.getHeight() > rect.getHeight()) {
+ lastLocation = null;
+ }
+ } catch (Exception ex) {
+ // on ignre, on initialise pas
+ }
+ }
+ if (lastLocation != null) {
+ setBounds(lastLocation);
+ } else {
+ if (rect != null && (rect.getWidth() != dm.getWidth() || rect.getHeight() != dm.getHeight())) {
+ setBounds(rect);
+ } else {
+ setLocation((int) ((screenSize.getWidth() - DEFAULT_WIDTH) / 2),
+ (int) ((screenSize.getHeight() - DEFAULT_HEIGHT) / 2));
+ pack();
+ setSize(new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT));
+ setExtendedState(MAXIMIZED_BOTH);
+ }
+ }
+// if(props.getProperty("export.type")!=null) {
+// if("xls".equals(props.getProperty("export.type")))
+// exportType = EXPORT_TYPES.XLS;
+// else
+// exportType = EXPORT_TYPES.CSV;
+// }
+ startListener.pushProgress();
+ setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
+ startListener.pushProgress();
+ setVisible(true);
+ startListener.pushProgress();
+ }
+
+ protected void initActions() {
+ startListener.pushProgress();
+ startListener.pushProgress();
+ actQuitter = new AbstractAction("Quitter") {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ runExit();
+ }
+ };
+ startListener.pushProgress();
+ }
+
+ private void initMenus1() {
+ JMenuBar mBar = new JMenuBar();
+ JMenu fileMenu = new JMenu("Fichier");
+
+ importerMenu = new JMenu("Importer");
+ controlerMenu = new JMenu("Analyser");
+ fileMenu.add(importerMenu);
+ fileMenu.add(controlerMenu);
+ fileMenu.addSeparator();
+ JMenu mnuExports = new JMenu("Exports");
+// mnuConfigExports = new JMenu("Configurer mes exports");
+// JMenuItem exportMenuConfig = new JMenuItem("Modèles d'exports avancés...");
+// exportMenuConfig.addActionListener(new ActionListener() {
+//
+// @Override
+// public void actionPerformed(ActionEvent evt) {
+// configExport();
+// }
+// });
+// JMenu mnuChooseExportType = new JMenu("Type d'export...");
+// ButtonGroup bgExportType = new ButtonGroup();
+// JRadioButtonMenuItem rbmExpCsv = new JRadioButtonMenuItem("Exports CSV");
+// rbmExpCsv.addActionListener(new ActionListener() {
+// @Override
+// public void actionPerformed(ActionEvent e) {
+// MainWindow.getInstance().exportType = EXPORT_TYPES.CSV;
+// }
+// });
+// JRadioButtonMenuItem rbmExpAvance = new JRadioButtonMenuItem("Exports avancés");
+// rbmExpAvance.addActionListener(new ActionListener() {
+// @Override
+// public void actionPerformed(ActionEvent e) {
+// MainWindow.getInstance().exportType = EXPORT_TYPES.XLS;
+// }
+// });
+// bgExportType.add(rbmExpCsv);
+// bgExportType.add(rbmExpAvance);
+// mnuChooseExportType.add(rbmExpCsv);
+// mnuChooseExportType.add(rbmExpAvance);
+// if(exportType==EXPORT_TYPES.CSV)
+// bgExportType.setSelected(rbmExpCsv.getModel(), true);
+// else
+// bgExportType.setSelected(rbmExpAvance.getModel(), true);
+// mnuConfigExports.add(mnuChooseExportType);
+// mnuConfigExports.add(exportMenuConfig);
+// mnuExports.add(mnuConfigExports);
+ mnuExporterFichier = new JMenuItem("Exporter des fichiers...");
+ mnuExporterFichier.addActionListener(new ActionListener() {
+
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ exporterFichier();
+ }
+ });
+ mnuExports.add(mnuExporterFichier);
+ fileMenu.add(mnuExports);
+
+ // TODO: une entrée pour supprimer tout
+ mnuSupprimer = new JMenuItem("Supprimer...");
+ fileMenu.add(mnuSupprimer);
+ mnuSupprimer.addActionListener(new ActionListener() {
+
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ new DlgCleanDatabase(MainWindow.this, true, docModels, DlgChooseDocuments.DIALOG_TYPE.BOTH, getConnectedUser());
+ }
+ });
+
+ fileMenu.addSeparator();
+ boolean reAddSeparator = false;
+ if ("true".equals(applicationProperties.getProperty(Constants.SYS_PROP_RESET_CONFIG))) {
+ JMenuItem mnuReset = new JMenuItem("Reset config ...");
+ fileMenu.add(mnuReset);
+ reAddSeparator = true;
+ mnuReset.addActionListener(new ActionListener() {
+
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ reloadConfiguration();
+ }
+ });
+ }
+ if ("true".equals(applicationProperties.getProperty(Constants.SYS_PROP_ADMIN_MENU_GC))) {
+ mnuClean = new JMenuItem("Garbage collector");
+ fileMenu.add(mnuClean);
+ reAddSeparator = true;
+ mnuClean.addActionListener(new ActionListener() {
+
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ System.gc();
+ }
+ });
+ mnuClean.setEnabled(false);
+ }
+ if(reAddSeparator)
+ fileMenu.addSeparator();
+ JMenuItem mnuEnv;
+ fileMenu.add(mnuEnv = new JMenuItem("Environnement..."));
+ mnuEnv.addActionListener(new ActionListener() {
+
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ DlgEditEnvironment dee = new DlgEditEnvironment(MainWindow.this, docModels, EnvironmentDomain.DOMAIN_DOCUMENTS, getConnectedUser());
+ dee.setVisible(true);
+ }
+ });
+ fileMenu.addSeparator();
+
+ JMenuItem mnuConfig = new JMenuItem("Configuration...");
+ mnuConfig.addActionListener(new ActionListener() {
+
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ DlgSystemConfiguration dlg = new DlgSystemConfiguration(MainWindow.this, true);
+ dlg.setVisible(true);
+ }
+ });
+ fileMenu.add(mnuConfig);
+
+ JMenuItem mnuMAJ = new JMenuItem("Mise à jour...");
+ mnuMAJ.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+// ForceUpdate fu = new ForceUpdate();
+// fu.execute();
+ UpdateChecker uc = new UpdateChecker();
+ uc.execute();
+ }
+ });
+ fileMenu.add(mnuMAJ);
+
+ fileMenu.addSeparator();
+
+ fileMenu.add(new JMenuItem(actQuitter));
+ mBar.add(fileMenu);
+
+ searchMenu = new JMenu("Recherche");
+ browseMenu = new JMenu("Navigation");
+
+ searchMenu.setEnabled(false);
+ browseMenu.setEnabled(false);
+ mBar.add(searchMenu);
+ mBar.add(browseMenu);
+
+
+ JMenu toolMenu = loadToolMenu();
+ if (toolMenu != null) {
+ mBar.add(toolMenu);
+ }
+
+ windowMenu = new WindowMenu("Fenêtres", desk);
+
+ mBar.add(windowMenu);
+
+ mBar.add(Box.createHorizontalGlue());
+
+ JMenu helper = new JMenu("?");
+ Action aboutAction = new AbstractAction("A Propos") {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ new AboutBox(MainWindow.this);
+ }
+ };
+ helper.add(new JMenuItem(aboutAction));
+ Action helpAction = new AbstractAction("Aide en ligne") {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ try {
+ StartUrl.startUrl(applicationProperties.getProperty(Constants.SYS_PROP_HELP_URL));
+ } catch (Throwable t) {
+ }
+ }
+ };
+ helper.add(helpAction);
+ Action releaseNotesAction = new AbstractAction("Notes de version...") {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ String url = "http://xemelios.org/updatesV5/release-notes-"+getEnvProperties().getProperty(Constants.SYS_PROP_MAJ_CONFIG)+".html";
+ try {
+ StartUrl.startUrl(url);
+ } catch(Exception ex) {
+ logger.error("while openning release-notes", ex);
+ }
+ }
+ };
+ helper.add(releaseNotesAction);
+ Action dlInfos = new AbstractAction("Rapport de configuration...") {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ try {
+ MainWindow.getInstance().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
+ StringBuilder sb = new StringBuilder();
+ sb.append("Jar Files\n");
+ sb.append(ClassPathUtils.displayClassPathInfos());
+ sb.append("xemelios.properties\n-------------------\n");
+ try {
+ File f = new File(getEnvProperties().replace("${xemelios.prg}/root/xemelios.properties"));
+ sb.append(FileUtils.readTextFile(f, "ISO-8859-1")).append("\n");
+ } catch (Exception ex) {
+ sb.append(" -- not readable : ").append(ex.getMessage()).append("\n");
+ }
+
+ sb.append("mysql.properties\n----------------\n");
+ try {
+ File f = new File(getEnvProperties().replace("${xemelios.mysql.config.filename}"));
+ sb.append(FileUtils.readTextFile(f, "ISO-8859-1")).append("\n");
+ } catch (Exception ex) {
+ sb.append(" -- not readable : ").append(ex.getMessage()).append("\n");
+ logger.error("reading mysql.properties", ex);
+ }
+
+ sb.append(DataLayerManager.getImplementation().getDatalayerConfiguration());
+
+ sb.append("xemelios.log\n----------------\n");
+ try {
+ File f = new File(getEnvProperties().replace("${xemelios.prg}/root/xemelios.log"));
+ sb.append(FileUtils.readTextFile(f, "ISO-8859-1")).append("\n");
+ } catch (Exception ex) {
+ sb.append(" -- not readable : ").append(ex.getMessage()).append("\n");
+ logger.error("reading xemelios.log", ex);
+ }
+
+ sb.append("installed-components.xml\n------------------------\n");
+ try {
+ File f = new File(getEnvProperties().getProperty(Constants.SYS_PROP_INSTALLED_FILENAME));
+ sb.append(FileUtils.readTextFile(f, "UTF-8"));
+ } catch(Exception ex) {
+ sb.append(" -- not readable : ").append(ex.getMessage()).append("\n");
+ logger.error("reading installed-components.xml", ex);
+ }
+
+ JFileChooser fc = new JFileChooser();
+ fc.setDialogTitle("Enregistrer le rapport de configuration sous...");
+ fc.addChoosableFileFilter(new FileFilter() {
+
+ @Override
+ public boolean accept(File f) {
+ return f.getName().toLowerCase().endsWith(".txt");
+ }
+
+ @Override
+ public String getDescription() {
+ return "Fichier texte (.txt)";
+ }
+ });
+ MainWindow.getInstance().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
+ if (fc.showSaveDialog(MainWindow.getInstance()) == JFileChooser.APPROVE_OPTION) {
+ File f = fc.getSelectedFile();
+ PrintWriter pw = new PrintWriter(f);
+ pw.write(sb.toString());
+ pw.flush();
+ pw.close();
+ }
+// logger.info(sb.toString());
+ } catch (Throwable t) {
+ } finally {
+ MainWindow.getInstance().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
+ }
+ }
+ };
+ helper.add(dlInfos);
+ mBar.add(helper);
+ setJMenuBar(mBar);
+ }
+ // appelé après le login
+
+ private void initMenus2() {
+ // on commence par récupérer les valeurs modifiées de la configuration et les appliquer
+ try {
+ Hashtable<String, Object> values = DataLayerManager.getImplementation().getRedefinedConfigValues(connectedUser);
+ for (String key : values.keySet()) {
+ String path = key.startsWith("/") ? key.substring(1) : key;
+ docModels.setValue(path, values.get(key));
+ }
+ } catch (Exception ex) {
+ logger.error("while applying overriden documents configration", ex);
+ }
+ // Ajout des items du menu importer
+ ActionImport aiArch = new ActionImport("Archive XeMeLios", Constants.XEMELIOS_ARCHIVE_SIGN);
+ importerMenu.add(new JMenuItem(aiArch));
+ for (DocumentModel dm : docModels.getDocuments()) {
+ if (!getConnectedUser().hasDocument(dm.getId())) {
+ logger.debug(getConnectedUser().getId() + " is not allowed on " + dm.getId());
+ continue;
+ }
+ if (dm.getDisplayInMenuIf() != null && !"true".equals(applicationProperties.getProperty(dm.getDisplayInMenuIf()))) {
+ continue;
+ }
+ ActionImport ai = new ActionImport(dm.getTitre(), dm.getId());
+ if (dm.isControlable()) {
+ ActionControl ac = new ActionControl(dm.getTitre(), dm.getId());
+ controlerMenu.add(new JMenuItem(ac));
+ }
+ if (dm.isImportable()) {
+ importerMenu.add(new JMenuItem(ai));
+ }
+ JMenu searchEntry = new JMenu(dm.getTitre());
+ JMenuItem browseEntry = null;
+ if (dm.isBrowsable()) {
+ final DocumentModel dm2 = dm;
+ browseEntry = new JMenuItem(new AbstractAction(dm.getTitre()) {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ if (dm2.getNavigateToDocumentSwingClassName() == null) {
+ // comportement par défaut
+ DlgSelectNavigationTarget dlg = new DlgSelectNavigationTarget(dm2, getConnectedUser(), instance);
+ if (dlg.run()) {
+ switch (dlg.getSpecialKeys().size()) {
+ case 0: {
+ browse(dm2, dm2.getDefaultBrowsableEtat(), dlg.getCollectivite().key, dlg.getBudget().key, null, null);
+ break;
+ }
+ case 1: {
+ browse(dm2, dm2.getDefaultBrowsableEtat(), dlg.getCollectivite().key, dlg.getBudget().key, dlg.getSpecialKeys().get(0).key, null);
+ break;
+ }
+ default:
+ browse(dm2, dm2.getDefaultBrowsableEtat(), dlg.getCollectivite().key, dlg.getBudget().key, dlg.getSpecialKeys().get(0).key, dlg.getSpecialKeys().get(1).key);
+ }
+ }
+ } else {
+ try {
+ Class clazz = Class.forName(dm2.getNavigateToDocumentSwingClassName());
+ Constructor<Navigable> cc = clazz.getConstructor(new Class[]{DocumentModel.class, XemeliosUser.class, MainWindow.class});
+ Navigable obj = cc.newInstance(dm2, getConnectedUser(), instance);
+ obj.run();
+ } catch (Exception ex) {
+ throw new RuntimeException(ex);
+ }
+ }
+ }
+ });
+ }
+ int searchCount = 0;
+ for (Enumeration<EtatModel> enumer2 = dm.getEtats().elements(); enumer2.hasMoreElements();) {
+ EtatModel em = enumer2.nextElement();
+ if (em.getDisplayInMenuIf() != null && !"true".equals(applicationProperties.getProperty(em.getDisplayInMenuIf()))) {
+ continue;
+ }
+ JMenu tmpMnu = null;
+ if (!dm.isGroupMenuItem()) {
+ tmpMnu = new JMenu(em.getTitre());
+ } else {
+ tmpMnu = searchEntry;
+ }
+ for (ElementModel elm : em.getSearchableElements()) {
+ if (!elm.isDisplay()) {
+ continue;
+ }
+ ActionSearch as = new ActionSearch(elm.getTitre(), dm.getId(), em.getId(), elm.getId());
+ tmpMnu.add(new JMenuItem(as));
+ searchCount++;
+ }
+ if (tmpMnu != searchEntry) {
+ if (tmpMnu.getMenuComponentCount() > 0) {
+ searchEntry.add(tmpMnu);
+ }
+ }
+ }
+ if (searchCount > 0) {
+ searchMenu.add(searchEntry);
+ }
+ if (browseEntry != null) {
+ browseMenu.add(browseEntry);
+ }
+ }
+ }
+
+ protected void importer(String docId) {
+ if (Constants.XEMELIOS_ARCHIVE_SIGN.equals(docId)) {
+ importXemeliosArchive();
+ } else {
+ DocumentModel dm = docModels.getDocumentById(docId);
+ try {
+ if(!DataLayerManager.getImplementation().canImportDocument(docId, connectedUser)) {
+ String message =
+ "L'import de ce type de document est pour le moment impossible.\n" +
+ "La base de donnée doit être mise à jour avant.\n" +
+ "Prenez contact avec votre administrateur pour faire la mise à jour depuis le serveur.";
+ JOptionPane.showMessageDialog(this, message, "Import impossible", JOptionPane.INFORMATION_MESSAGE);
+ return;
+ }
+ Class clazz = Class.forName(dm.getImportClass());
+ Constructor cc = clazz.getConstructor(XemeliosUser.class);
+ Object obj = cc.newInstance(getConnectedUser());
+ if (!(obj instanceof EtatImporteur)) {
+ JOptionPane.showMessageDialog(this, "Cette classe n'est pas un importeur.\nLe fichier de configuration qui vous a été livré est certainement invalide.\nVeuillez contacter votre fournisseur.\n", "Erreur", JOptionPane.ERROR_MESSAGE);
+ return;
+ }
+ EtatImporteur ei = (EtatImporteur) obj;
+ ImportContent fToImport = getFilesToImport(dm.getExtension(), dm.getLibelleExtension());
+ if (fToImport.getImportCount() > 0) {
+ doImport(ei, fToImport, dm, false);
+ }
+ } catch (Exception ex) {
+ logger.error("importer", ex);
+ new DisplayExceptionDlg(this, ex);
+ } finally {
+ //waiter.stopProgress();
+ }
+ }
+ }
+
+ protected void importXemeliosArchive() {
+ FileSystemView fsv = FileSystemView.getFileSystemView();
+ if (lastInputDirectory == null) {
+ lastInputDirectory = fsv.getHomeDirectory();
+ }
+ JFileChooser fc = new JFileChooser(lastInputDirectory, fsv);
+ FileFilter defaultFileFilter = null;
+ fc.addChoosableFileFilter(defaultFileFilter = new FileFilter() {
+
+ @Override
+ public boolean accept(File arg0) {
+ return arg0.isDirectory()
+ || arg0.getName().toUpperCase().endsWith(".XAR");
+ }
+
+ @Override
+ public String getDescription() {
+ return "Archives XeMeLios (.xar)";
+ }
+ });
+ fc.setFileFilter(defaultFileFilter);
+ fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
+ fc.setMultiSelectionEnabled(false);
+ fc.setDialogTitle("Choisissez le premier fichier d'une archive XeMeLios");
+ fc.setApproveButtonText("Importer");
+ if(fc.showOpenDialog(this)==JFileChooser.APPROVE_OPTION) {
+ File firstArchive = fc.getSelectedFile();
+ lastInputDirectory = firstArchive.getParentFile();
+ ImportServiceSwingProvider isp = new ImportServiceSwingProvider(this, null, 0);
+ isp.setDisplayFeedback(false);
+ XemeliosArchiveImporter xai = new XemeliosArchiveImporter(docModels, firstArchive, isp, getEnvProperties());
+ xai.setUser(connectedUser);
+ XemeliosArchiveImporterWorker worker = new XemeliosArchiveImporterWorker(xai);
+ worker.execute();
+ }
+ }
+
+ public void doImport(EtatImporteur ei, ImportContent fToImport, DocumentModel dm, boolean synchronizeMe) {
+ ImportServiceSwingProvider issp = new ImportServiceSwingProvider(this, ei, fToImport.filesToImport.size() + fToImport.pjs.size());
+ if (synchronizeMe) {
+ issp.setDisplayFeedback(false);
+ }
+ ei.setImpSvcProvider(issp);
+ ei.setDocument(dm);
+ ei.setApplicationConfiguration(getEnvProperties());
+ waiter.startProgress();
+ try {
+ ei.setFilesToImport(fToImport.filesToImport);
+ ei.setPjs(fToImport.pjs);
+ if (synchronizeMe) {
+ ei.run();
+ } else {
+ ei.execute();
+ }
+ } catch (Exception ex) {
+ logger.error("doImport", ex);
+ new DisplayExceptionDlg(this, ex);
+ } finally {
+ waiter.stopProgress();
+ }
+ }
+
+ public void doImport(EtatImporteur ei, ImportContent fToImport, DocumentModel dm, DlgControl parentController, MainControl.Triplet triplet, boolean synchronizeMe) {
+ ImportServiceSwingProvider issp = new ImportServiceSwingProvider(this, ei, fToImport.filesToImport.size() + fToImport.pjs.size());
+ if (synchronizeMe) {
+ issp.setDisplayFeedback(false);
+ }
+ ei.setImpSvcProvider(issp);
+ ei.setDocument(dm);
+ waiter.startProgress();
+ try {
+ ei.setFilesToImport(fToImport.filesToImport);
+ ei.setPjs(fToImport.pjs);
+ if (synchronizeMe) {
+ ei.run();
+ } else {
+ ei.execute();
+ }
+
+ } catch (Exception ex) {
+ logger.error("doImport", ex);
+ new DisplayExceptionDlg(this, ex);
+ } finally {
+ waiter.stopProgress();
+ }
+ try {
+ ei.get();
+ } catch (Throwable t) {
+ t.printStackTrace();
+ parentController.notifyImportFailed();
+ } finally {
+ parentController.notifyImportFinished(triplet);
+ }
+ }
+
+ protected void controller(String docId) {
+ MainControlWrapper mc = new MainControlWrapper(docModels.getDocumentById(docId), docModels, getConnectedUser());
+ DlgControl dc = new DlgControl(this, docModels.getDocumentById(docId), mc);
+ dc.setVisible(true);
+ }
+// protected void exporter() {
+// JInternalFrame f = desk.getSelectedFrame();
+// if(f!=null) {
+// SearchWindow s = (SearchWindow)f;
+// if(s.canExport()) {
+// s.exportXLS();
+// }
+// }
+// }
+// protected void exporterCSV() {
+// JInternalFrame f = desk.getSelectedFrame();
+// if(f!=null) {
+// SearchWindow s = (SearchWindow)f;
+// if(s.canExport()) {
+// s.exportCSV();
+// }
+// }
+// }
+
+ protected void runExit() {
+ this.setCursor(new Cursor(Cursor.WAIT_CURSOR));
+ try {
+ JInternalFrame[] childs = desk.getAllFrames();
+ for (int i = 0; i < childs.length; i++) {
+ desk.remove(childs[i]);
+ childs[i].dispose();
+ }
+ Rectangle location = getBounds();
+ StringBuilder propValue = new StringBuilder();
+ propValue.append("(").append(Integer.toString((int) location.getX())).append(",").append(Integer.toString((int) location.getY())).append(",").append(Integer.toString((int) location.getWidth())).append(",").append(Integer.toString((int) location.getHeight())).append(")");
+ File propFile = new File(System.getProperty("user.home"), "xemelios.properties");
+ Properties props = new Properties();
+ if (propFile.exists()) {
+ try {
+ props.load(new FileInputStream(propFile));
+ } catch (IOException ioEx) {
+ }
+ }
+ props.setProperty(MAIN_WINDOW_POSITION, propValue.toString());
+ if(lastInputDirectory!=null) {
+ if(props.getProperty(Constants.SYS_PROP_LAST_INPUT_DIRECTORY) == null){
+ props.setProperty(Constants.SYS_PROP_LAST_INPUT_DIRECTORY,lastInputDirectory.getAbsolutePath());
+ } else {
+ props.put(Constants.SYS_PROP_LAST_INPUT_DIRECTORY,lastInputDirectory.getAbsolutePath());
+ }
+ }
+ try {
+ props.store(new FileOutputStream(propFile), "");
+ } catch (Throwable t) {
+ }
+ try {
+ File[] files = FileUtils.getTempDir().listFiles();
+ for (File f : files) {
+ f.delete();
+ }
+ FileUtils.getTempDir().delete();
+ } catch (Throwable t) {
+ }
+ } catch(Exception ex) {
+ logger.error("in runExit()",ex);
+ }
+ savePersonnalConfig();
+ saveCriteriasInputValues();
+ System.exit(0);
+ }
+
+ public SearchWindow displaySearchWindow(ElementModel element) {
+ ElementModel elm = element.clone();
+ EtatModel em = element.getParent();
+ DocumentModel dm = em.getParent();
+ elm.setParent(em);
+ try {
+ if (DataLayerManager.getImplementation().canSearch(dm, em, getConnectedUser())) {
+ if (elm == null) {
+ JOptionPane.showMessageDialog(this, "L'état " + em.getTitre() + " n'a pas d'élément de recherche définit.", "Erreur de configuration", JOptionPane.ERROR_MESSAGE);
+ return null;
+ }
+ SearchWindow sw = new SearchWindow(this, dm, elm, getConnectedUser());
+ desk.add(sw);
+ desk.getDesktopManager().maximizeFrame(sw);
+ return sw;
+ } else {
+ throw new ToolException(ToolException.ERROR_NO_DATA);
+ }
+ } catch (ToolException tEx) {
+ if (tEx.getErrorCode() == ToolException.ERROR_NO_DATA) {
+ JOptionPane.showMessageDialog(this, "Aucun " + em.getTitre() + " n'a été importé.\nVous devez en importer au moins un avant d'effectuer une recherche.", "Erreur", JOptionPane.WARNING_MESSAGE);
+ } else {
+ new DisplayExceptionDlg(this, tEx);
+ }
+ } catch (UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(this, ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (DataAccessException daEx) {
+ new DisplayExceptionDlg(this, daEx);
+ } catch (DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(this, dcEx);
+ }
+ return null;
+ }
+
+ protected void search(String docId, String etatId, String elementId) {
+ DocumentModel dm = docModels.getDocumentById(docId).clone();
+ EtatModel em = dm.getEtatById(etatId);
+ try {
+ if (DataLayerManager.getImplementation().canSearch(dm, em, getConnectedUser())) {
+ ElementModel elm = em.getElementById(elementId);
+ if (elm == null) {
+ JOptionPane.showMessageDialog(this, "L'état " + em.getTitre() + " n'a pas d'élément de recherche définit.", "Erreur de configuration", JOptionPane.ERROR_MESSAGE);
+ return;
+ }
+ SearchWindow sw = new SearchWindow(this, dm, elm, getConnectedUser());
+ desk.add(sw);
+ desk.getDesktopManager().maximizeFrame(sw);
+ sw.show();
+ } else {
+ throw new ToolException(ToolException.ERROR_NO_DATA);
+ }
+ } catch (ToolException tEx) {
+ if (tEx.getErrorCode() == ToolException.ERROR_NO_DATA) {
+ JOptionPane.showMessageDialog(this, "Aucun " + em.getTitre() + " n'a été importé.\nVous devez en importer au moins un avant d'effectuer une recherche.", "Erreur", JOptionPane.WARNING_MESSAGE);
+ } else {
+ new DisplayExceptionDlg(this, tEx);
+ }
+ } catch (UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(this, ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (DataAccessException daEx) {
+ new DisplayExceptionDlg(this, daEx);
+ } catch (DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(this, dcEx);
+ }
+ }
+
+ protected boolean checkPassword() throws DataAccessException {
+ // Affichage de la fenêtre d'authentification :
+ AuthEngine authEngine = AuthEngine.Holder.getAuthEngine();
+ XemeliosUser user = null;
+ if (authEngine.isLoginRequired() || authEngine.isPasswordRequired()) {
+ if (startListener instanceof Splash) {
+ Splash sp = (Splash) startListener;
+ sp.setAlwaysOnTop(false);
+ sp.setVisible(false);
+ }
+ int attempt = 0;
+ while (user == null && attempt < 3) {
+ attempt++;
+ LoginDialog loginDialog = new LoginDialog(this, authEngine.isLoginRequired(), authEngine.isPasswordRequired());
+ if (loginDialog.run()) {
+ user = authEngine.createUser(loginDialog.getUserName(), loginDialog.getPassword());
+ if (user == null) {
+ JOptionPane.showMessageDialog(this, "Echec de l'authentification.", "Erreur", JOptionPane.ERROR_MESSAGE);
+ }
+ } else {
+ if (startListener instanceof Splash) {
+ Splash sp = (Splash) startListener;
+ sp.setAlwaysOnTop(true);
+ sp.setVisible(true);
+ }
+ return false;
+ }
+ }
+ if (startListener instanceof Splash) {
+ Splash sp = (Splash) startListener;
+ sp.setAlwaysOnTop(true);
+ sp.setVisible(true);
+ }
+ if (user != null) {
+ }
+ } else {
+ // Nous sommes dans le cas ou le moteur d'authentification n'a ni besoin du login ni du mot de passe.
+ // On n'affiche donc pas le fenêtre de login.
+ user = authEngine.createUser(null, null);
+ }
+ if (user != null) {
+ connectedUser = user;
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ protected DocumentsModel getDocumentsInfos(String repertoires) {
+ DocumentsModel ret = null;
+ try {
+ ret = Loader.getDocumentsInfos(repertoires);
+ } catch (Exception ex) {
+ logger.error(ex);
+ startListener.completeProgress();
+ if (startListener instanceof Splash) {
+ Splash sp = (Splash) startListener;
+ sp.setAlwaysOnTop(false);
+ sp.setVisible(false);
+ }
+ new DisplayExceptionDlg((JFrame) null, ex);
+ }
+ return ret;
+ }
+
+ protected ImportContent getFilesToImport(final String extension, final String titreEtat) {
+ ImportContent ic = new ImportContent();
+ FileSystemView fsv = FileSystemView.getFileSystemView();
+ if (lastInputDirectory == null) {
+ lastInputDirectory = fsv.getHomeDirectory();
+ }
+ JFileChooser fc = new JFileChooser(lastInputDirectory, fsv);
+ FileFilter defaultFileFilter = null;
+ fc.addChoosableFileFilter(defaultFileFilter = new FileFilter() {
+
+ @Override
+ public boolean accept(File arg0) {
+ return arg0.isDirectory()
+ || arg0.getName().toUpperCase().endsWith(
+ extension.toUpperCase());
+ }
+
+ @Override
+ public String getDescription() {
+ return "Fichiers " + titreEtat;
+ }
+ });
+ fc.addChoosableFileFilter(new FileFilter() {
+
+ @Override
+ public boolean accept(File arg0) {
+ return arg0.isDirectory()
+ || arg0.getName().toUpperCase().endsWith(".XML");
+ }
+
+ @Override
+ public String getDescription() {
+ return "Fichiers XML";
+ }
+ });
+ fc.addChoosableFileFilter(new FileFilter() {
+
+ @Override
+ public boolean accept(File arg0) {
+ return arg0.isDirectory()
+ || arg0.getName().toUpperCase().endsWith(".ZIP");
+ }
+
+ @Override
+ public String getDescription() {
+ return "Archives ZIP";
+ }
+ });
+ fc.addChoosableFileFilter(new FileFilter() {
+
+ @Override
+ public boolean accept(File f) {
+ return f.isDirectory() || f.getName().toUpperCase().endsWith(".GZ");
+ }
+
+ @Override
+ public String getDescription() {
+ return "Fichier compressé (GZip)";
+ }
+ });
+ fc.setFileFilter(defaultFileFilter);
+ fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
+ fc.setMultiSelectionEnabled(true);
+ fc.setDialogTitle("Choisissez un fichier ou répertoire à importer");
+ int selectedAction = fc.showOpenDialog(this);
+ if (selectedAction == JFileChooser.APPROVE_OPTION) {
+ File[] ret = null;
+ if (fc.getSelectedFile() != null && fc.getSelectedFile().isFile()) {
+ // si l'utilisateur a choisi un fichier
+ // ret = new File[1];
+ // ret[0] = fc.getSelectedFile();
+ ret = fc.getSelectedFiles();
+ lastInputDirectory = ret[0].getParentFile();
+ } else if (fc.getSelectedFile() != null && fc.getSelectedFile().isDirectory()) {
+ // si l'utilisateur a choisi un r?ertoire
+ logger.debug("path=" + fc.getSelectedFile().getAbsolutePath());
+ // on cr? le mod?e de donn?s pour l'affichage dans la boite de dialogue d'import
+ String[] extensions = {"xml", "zip", extension};
+
+ // on affiche les fichiers trouvés dans les répertoires à l'utilisateur, pour
+ // qu'il décide ceux qu'il veut exclure de l'import
+ ImportDialog test = new ImportDialog(this, "Sélectionnez les fichiers à importer");
+ List<ImportFile> resultats = test.startDialog(fc.getSelectedFile(), extensions);
+ ret = new File[resultats.size()];
+ int counter = 0;
+ for (Iterator iter = resultats.iterator(); iter.hasNext();) {
+ ret[counter++] = ((ImportFile) iter.next()).getFile();
+ }
+ lastInputDirectory = fc.getSelectedFile();
+ } else {
+ // l'utilisateur n'a rien choisi, appuy?sur "Annuler"
+ ret = new File[0];
+ }
+ // on regarde si l'un des fichiers a importer est un zip
+ //ArrayList<File> files = new ArrayList<File>();
+ File tmpDir = FileUtils.getTempDir();
+ for (int i = 0; i < ret.length; i++) {
+ if (ret[i].getName().toLowerCase().endsWith(".zip")) {
+ if (ret[i].exists()) {
+ ZipFile zf = null;
+ try {
+ zf = new ZipFile(ret[i]);
+ for (Enumeration<? extends ZipEntry> enumer = zf.entries(); enumer.hasMoreElements();) {
+ ZipEntry ze = enumer.nextElement();
+ if (!ze.isDirectory()) {
+ String fileName = ze.getName();
+ String entryName = fileName.toLowerCase();
+ fileName = fileName.replace(
+ File.pathSeparatorChar, '_').replace(
+ File.separatorChar, '_').replace(':',
+ '|').replace('\'', '_').replace('/',
+ '_');
+ logger.debug(entryName);
+ if (PJRef.isPJ(ze)) {
+ PJRef pj = new PJRef(ze);
+ pj.writeTmpFile(tmpDir, zf);
+ ic.pjs.add(pj);
+ } else if ((entryName.endsWith(extension.toLowerCase()) || entryName.endsWith(".xml")) && !fileName.startsWith("_")) {
+ // on decompresse le fichier dans le
+ // repertoire temporaire, comme ca il sera
+ // supprime en quittant
+ InputStream is = zf.getInputStream(ze);
+ BufferedInputStream bis = new BufferedInputStream(is);
+ File output = new File(tmpDir, fileName);
+ BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(output));
+ byte[] buffer = new byte[1024];
+ int read = bis.read(buffer);
+ while (read > 0) {
+ bos.write(buffer, 0, read);
+ read = bis.read(buffer);
+ }
+ bos.flush();
+ bos.close();
+ bis.close();
+ ic.filesToImport.add(output);
+ }
+ }
+ }
+ zf.close();
+ } catch (ZipException zEx) {
+ JOptionPane.showMessageDialog(this, "Le fichier "
+ + ret[i].getName()
+ + " n'est pas une archive ZIP valide",
+ "Erreur", JOptionPane.ERROR_MESSAGE);
+ } catch (IOException ioEx) {
+ JOptionPane.showMessageDialog(
+ this,
+ "Le fichier "
+ + ret[i].getName()
+ + " est illisible. Vérifiez que les noms des fichiers\ncontenus dans l'archive ne comportent pas de caractères spéciaux ou accentués.",
+ "Erreur", JOptionPane.ERROR_MESSAGE);
+ ioEx.printStackTrace();
+ } finally {
+ if (zf != null) {
+ try {
+ zf.close();
+ } catch (Throwable t) {
+ }
+ }
+ }
+ }
+ } else if (ret[i].getName().toLowerCase().endsWith(".gz")) {
+ try {
+ String fileName = ret[i].getName();
+ fileName = fileName.substring(0, fileName.length() - 3);
+ File output = new File(tmpDir, fileName);
+ GZIPInputStream gis = new GZIPInputStream(new FileInputStream(ret[i]));
+ BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(output));
+ byte[] buffer = new byte[1024];
+ int read = gis.read(buffer);
+ while (read > 0) {
+ bos.write(buffer, 0, read);
+ read = gis.read(buffer);
+ }
+ bos.flush();
+ bos.close();
+ gis.close();
+ ic.filesToImport.add(output);
+ } catch (IOException ioEx) {
+ // nothing to do
+ }
+ } else {
+ ic.filesToImport.add(ret[i]);
+ }
+ }
+ } else {
+ // TODO
+ }
+ return ic;
+ }
+
+ protected void checkUpdateAvailability() {
+ UpdateChecker uc = new UpdateChecker();
+ uc.execute();
+ }
+
+ public void innerWindowChanged() {
+ }
+
+ public void msg(String message) {
+ statusField.setText(message);
+ }
+
+ public static final void main(String[] args) {
+ PropertiesExpansion pe = new PropertiesExpansion(System.getProperties());
+ new MainWindow(pe, Constants.NOM_APP, new EmptyStartListener(), args);
+ }
+
+ public void startWaiter() {
+ waiter.startProgress();
+ }
+
+ public void stopWaiter() {
+ waiter.stopProgress();
+ }
+
+// private void supprimerParFichier() {
+// new DlgCleanDatabase(this, true, docModels, DlgChooseDocuments.DIALOG_TYPE.FILE, getConnectedUser());
+// }
+//
+// private void supprimerParDonnee() {
+// new DlgCleanDatabase(this, true, docModels, DlgChooseDocuments.DIALOG_TYPE.DATA, getConnectedUser());
+// }
+
+ private void starterImport(String[] args) {
+ if (startListener instanceof Splash) {
+ Splash splash = (Splash) startListener;
+ splash.setAlwaysOnTop(false);
+ splash.setVisible(false);
+ }
+ if (connectedUser.hasRole(XemeliosUser.ROLE_IMPORT)) {
+ for (String fName : args) {
+ File f = null;
+ try {
+ f = new File(fName);
+ } catch (Throwable t) {
+ }
+ if (f != null && f.exists()) {
+ // le fichier existe, il faut choisir le type de document
+ AskDocumentType adt = new AskDocumentType(this, fName, docModels, getEnvProperties());
+ adt.setVisible(true);
+ DocumentModel dm = adt.getDocumentType();
+ if (dm != null) {
+ try {
+ Class clazz = Class.forName(dm.getImportClass());
+ Constructor cc = clazz.getConstructor(XemeliosUser.class);
+ Object obj = cc.newInstance(getConnectedUser());
+ if (!(obj instanceof EtatImporteur)) {
+ JOptionPane.showMessageDialog(this,
+ "Cette classe n'est pas un importeur.\n"
+ + "Le fichier de configuration qui vous a été livré est certainement invalide.\n"
+ + "Veuillez contacter votre fournisseur.", "Erreur", JOptionPane.ERROR_MESSAGE);
+ return;
+ }
+ EtatImporteur ei = (EtatImporteur) obj;
+ File[] fToImport = new File[]{f};
+ ImportServiceSwingProvider issp = new ImportServiceSwingProvider(this, ei, fToImport.length);
+ ei.setImpSvcProvider(issp);
+ ei.setDocument(dm);
+ ei.setApplicationConfiguration(getEnvProperties());
+ //
+ waiter.startProgress();
+ ei.setFilesToImport(fToImport);
+ ei.setPjs(new ArrayList<PJRef>());
+ ei.execute();
+ waiter.stopProgress();
+ } catch (Exception ex) {
+ logger.error("starterImport", ex);
+ /*DisplayExceptionDlg dlg = */
+ new DisplayExceptionDlg(
+ this, ex);
+ } finally {
+ waiter.stopProgress();
+ }
+ }
+ }
+ }
+// } else {
+// JOptionPane.showMessageDialog(this,"Vous n'avez pas les droits suffisants pour importer ce fichier.","Erreur",JOptionPane.ERROR_MESSAGE);
+ }
+ if (startListener instanceof Splash) {
+ Splash splash = (Splash) startListener;
+ splash.setAlwaysOnTop(false);
+ splash.setVisible(false);
+ }
+ }
+
+ public SavedRequestsModel getSavedRequest(ElementModel el) {
+ return config.getSavedRequests(el);
+ }
+
+ protected void savePersonnalConfig() {
+ File f = new File(System.getProperty("user.home"));
+ File fProp = new File(f, Constants.PERSONNAL_CONFIG_FILENAME);
+ //FileOutputStream fw = null;
+ OutputStreamWriter w = null;
+ try {
+// XmlOutputter xo = new XmlOutputter(fw = new FileOutputStream(fProp), "ISO-8859-1");
+ Charset cs = Charset.forName("ISO-8859-1");
+ XmlOutputter xo = new XmlOutputter(w = new OutputStreamWriter(new FileOutputStream(fProp), cs), cs.name());
+ config.marshall(xo);
+ } catch (Throwable t) {
+ logger.error("savePersonnalConfig", t);
+ } finally {
+ if (w != null) {
+ try {
+ w.flush();
+ w.close();
+ } catch (Throwable t) {
+ }
+ }
+ }
+ }
+
+ public void reloadPersonnalConfig() {
+ loadPersonnalConfig();
+ }
+
+ protected void loadPersonnalConfig() {
+ File f = new File(System.getProperty("user.home"));
+ File fProp = new File(f, Constants.PERSONNAL_CONFIG_FILENAME);
+ config = new PersonnalConfigurationModel(PersonnalConfigurationModel.QN);
+ if (fProp.exists()) {
+ try {
+ PersonnalConfigParser parser = new PersonnalConfigParser();
+ parser.parse(fProp);
+ config = (PersonnalConfigurationModel) parser.getMarshallable();
+ } catch (Throwable t) {
+ logger.error("loadPersonnalConfig", t);
+ }
+ }
+
+ // looking for shared requests files
+ File[] sharedFiles = f.listFiles(new FilenameFilter() {
+
+ @Override
+ public boolean accept(File dir, String name) {
+ return name.startsWith(Constants.PERSONNAL_CONFIG_FILENAME.substring(0, Constants.PERSONNAL_CONFIG_FILENAME.indexOf('.')) + "-");
+ }
+ });
+ for (File share : sharedFiles) {
+ logger.debug("parsing "+share.getName());
+ try {
+ PersonnalConfigParser parser = new PersonnalConfigParser();
+ parser.parse(share);
+ PersonnalConfigurationModel sharedConfig = (PersonnalConfigurationModel) parser.getMarshallable();
+ String name = share.getName().substring(Constants.PERSONNAL_CONFIG_FILENAME.indexOf('.') + 1);
+ name = name.substring(0, name.indexOf('.'));
+ sharedConfig.setUnWritable(name);
+ config.merge(sharedConfig);
+ } catch (Throwable t) {
+ logger.error("loadPersonnalConfig", t);
+ }
+ }
+ logger.debug("personnal config loaded");
+ }
+
+ protected Properties loadCriteriasInputValues() {
+ Properties props = new Properties();
+ File f = new File(System.getProperty("user.home"));
+ File fProp = new File(f, Constants.CRITERIAS_INPUTS_FILENAME);
+ if (fProp.exists()) {
+ try {
+ FileInputStream fis = new FileInputStream(fProp);
+ props.load(fis);
+ fis.close();
+ } catch (IOException ioEx) {
+ }
+ }
+ return props;
+ }
+
+ protected void saveCriteriasInputValues() {
+ File f = new File(System.getProperty("user.home"));
+ File fProp = new File(f, Constants.CRITERIAS_INPUTS_FILENAME);
+ try {
+ FileOutputStream fos = new FileOutputStream(fProp);
+ criteriasInputValues.store(fos, null);
+ fos.close();
+ } catch (IOException ioEx) {
+ }
+ }
+
+ public void browse(DocumentModel dm, EtatModel emParam, String collectivite, String budget, String specialKey1, String specialKey2) {
+ EtatModel em = emParam == null ? dm.getDefaultBrowsableEtat() : emParam;
+ NavigationContext nc = new NavigationContext(dm.getId(), em.getId(), em.getBrowsableElement().getId(), collectivite, budget, specialKey1, specialKey2, null, null);
+ try {
+ if (em == null) {
+ throw new DataConfigurationException("No default browsable etat for " + dm.getId());
+ }
+ DataImpl impl = DataLayerManager.getImplementation();
+ ArrayList<String> documents = impl.getDocumentListFromSpecialKeys(em.getBrowsableElement(), collectivite, budget, specialKey1, specialKey2, null, getConnectedUser());
+ if (documents.isEmpty()) {
+ JOptionPane.showMessageDialog(this, "Le document est introuvable", "", JOptionPane.WARNING_MESSAGE);
+ } else if (documents.size() > 1) {
+ JOptionPane.showMessageDialog(this, "Plusieurs documents répondant à ces critères ont été trouvés.", "Erreur", JOptionPane.ERROR_MESSAGE);
+ } else {
+ String docName = documents.get(0);
+ File xslFile = new File(new File(new File(System.getProperty("user.home")), "xemelios/documents-def-ovrrd"), em.getXslt());
+ if (!xslFile.exists()) {
+ xslFile = new File(new File(em.getParent().getBaseDirectory()), em.getXslt());
+ }
+ Pair pCollectivite = new Pair(collectivite, null);
+ Document doc = impl.getDocumentAsDom(em, pCollectivite, new Pair(budget, null), docName, getConnectedUser());
+ InputStream is = IoUtils.getInputStream(xslFile.getPath());
+ TransformerFactory tFactory = FactoryProvider.getTransformerFactory();
+ tFactory.setURIResolver(new CustomURIResolver(tFactory.getURIResolver(), xslFile.toURI().toURL().toExternalForm()));
+ Transformer t = tFactory.newTransformer(new StreamSource(is));
+ t.setParameter(HtmlViewer.PARAM_DESTINATION, em.useExternalBrowser() ? HtmlViewer.VALUE_DESTINATION_EXTERNAL : HtmlViewer.VALUE_DESTINATION_INTERNAL);
+ // on passe la nomenclature en parametre
+ // on recupere l'ID de la nomenclature
+ XPath xp = xpf.newXPath();
+ xp.setNamespaceContext(dm.getNamespaces());
+ String idRepository = null;
+ if (dm.getReferenceNomenclaturePath() != null && dm.getReferenceNomenclaturePath().getCodePath() != null) {
+ idRepository = (String) xp.evaluate(dm.getReferenceNomenclaturePath().getCodePath().getPath(), doc.getDocumentElement(), XPathConstants.STRING);
+ }
+ if (idRepository != null && idRepository.length() == 0) {
+ idRepository = null;
+ }
+ Document repository = impl.getRepositoryAsDom(dm, pCollectivite, idRepository, getConnectedUser());
+ if (repository != null) {
+ t.setParameter("repository", repository);
+ }
+ // on passe la config
+ t.setParameter("config", getDocModels().getSmallDOM());
+ t.setParameter("collectivite", pCollectivite.key);
+ t.setParameter("budget", budget);
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ t.transform(new DOMSource(doc), new StreamResult(baos));
+ ByteArrayInputStream htmlStream = new ByteArrayInputStream(baos.toByteArray());
+ displayHtmlStream(htmlStream, em, desk, nc);
+ }
+ } catch (Throwable t) {
+ JOptionPane.showMessageDialog(this, t.getMessage(), "Erreur",
+ JOptionPane.ERROR_MESSAGE);
+ logger.error("browse(...)",t);
+ }
+ }
+
+ public void displayHtmlStream(InputStream is, EtatModel em, JDesktopPane desk) throws IOException {
+ displayHtmlStream(is, em, desk, null);
+ }
+
+ public void displayHtmlStream(File f, EtatModel em) {
+ try {
+ String prefix = applicationProperties.getProperty(Constants.SYS_PROP_NAVIGATOR_PREFIX);
+ if (prefix == null) {
+ prefix = "";
+ }
+// String url = f.getCanonicalPath();
+ if (em.useExternalBrowser()) {
+ StartUrl.startUrl(f.toURI().toURL().toExternalForm());
+ } else {
+ HtmlViewer viewer = new HtmlViewer(f.toURI().toURL(), "Détail " + em.getTitre(), null, this);
+ desk.add(viewer);
+ desk.getDesktopManager().maximizeFrame(viewer);
+ viewer.show();
+ }
+ } catch (Exception toEx) {
+ Component comp2 = desk;
+ while (comp2 != null && !(comp2 instanceof JFrame)) {
+ comp2 = comp2.getParent();
+ }
+ if (comp2 != null) {
+ new DisplayExceptionDlg((JFrame) comp2, toEx);
+ } else {
+ toEx.printStackTrace();
+ }
+ }
+
+ }
+
+ public void displayHtmlStream(InputStream is, EtatModel em, JDesktopPane desk, NavigationContext nc) throws IOException {
+ File tmp = File.createTempFile("xemelios-data-", ".html", FileUtils.getTempDir());
+ BufferedInputStream bis = new BufferedInputStream(is);
+ BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmp));
+ byte[] buff = new byte[1024];
+ int lengthRead = bis.read(buff);
+ while (lengthRead > 0) {
+ bos.write(buff, 0, lengthRead);
+ lengthRead = bis.read(buff);
+ }
+ bos.flush();
+ bos.close();
+ try {
+ String prefix = applicationProperties.getProperty(Constants.SYS_PROP_NAVIGATOR_PREFIX);
+ if (prefix == null) {
+ prefix = "";
+ }
+// String url = tmp.getCanonicalPath();
+ if (em.useExternalBrowser()) {
+ StartUrl.startUrl(tmp.toURI().toURL().toExternalForm());
+ } else {
+ HtmlViewer viewer = new HtmlViewer(tmp.toURI().toURL(), "Détail " + em.getTitre(), nc, this);
+ desk.add(viewer);
+ desk.getDesktopManager().maximizeFrame(viewer);
+ viewer.show();
+ }
+ } catch (Exception toEx) {
+ Component comp2 = desk;
+ while (comp2 != null && !(comp2 instanceof JFrame)) {
+ comp2 = comp2.getParent();
+ }
+ if (comp2 != null) {
+ new DisplayExceptionDlg((JFrame) comp2, toEx);
+ } else {
+ toEx.printStackTrace();
+ }
+ }
+ }
+
+ protected void initDataLayer() throws DataConfigurationException {
+ logger.debug("entering initDataLayer");
+//logger.debug(applicationProperties);
+ String availableLayers = applicationProperties.getProperty(Constants.SYS_PROP_AVAILABLE_LAYERS);
+ StringTokenizer tokenizer = new StringTokenizer(availableLayers, ",");
+ while (tokenizer.hasMoreTokens()) {
+ String className = tokenizer.nextToken();
+ logger.debug("instanciating " + className);
+ try {
+ Class.forName(className);
+ } catch (Throwable t) {
+ logger.error("error while initializing data layer class (" + className + ") :", t);
+ }
+ }
+ DataLayerManager.setApplicationProperties(applicationProperties);
+ logger.debug("setting dataImpl to " + applicationProperties.getProperty(Constants.SYS_PROP_DATA_IMPL));
+ try {
+ DataLayerManager.setDataImpl(applicationProperties.getProperty(Constants.SYS_PROP_DATA_IMPL));
+ } catch (DataConfigurationException dcEx) {
+ if (getStartListener() instanceof Splash) {
+ Splash splash = (Splash) startListener;
+ splash.setAlwaysOnTop(false);
+ splash.setVisible(false);
+ }
+ JOptionPane.showMessageDialog(null, dcEx.getMessage(), "Erreur de connexion au serveur XeMeLios", JOptionPane.ERROR_MESSAGE);
+ logger.error(dcEx);
+ if (getStartListener() instanceof Splash) {
+ Splash splash = (Splash) startListener;
+ splash.setVisible(true);
+ splash.setAlwaysOnTop(true);
+ }
+ throw dcEx;
+ }
+ logger.debug("exiting successfully initDataLayer");
+ }
+
+ private void reloadConfiguration() {
+ Loader.flushLoadedConfig();
+ docModels = getDocumentsInfos(applicationProperties.getProperty(Constants.SYS_PROP_DOC_DEF_DIR));
+ try {
+ DataLayerManager.getImplementation().reset();
+ } catch (DataConfigurationException e) {
+ e.printStackTrace();
+ new DisplayExceptionDlg(this, e);
+ }
+ }
+
+ public XemeliosUser getConnectedUser() {
+ return connectedUser;
+ }
+
+ /**
+ * Reads and execute update script if it is present
+ *
+ */
+ protected void checkUpdateScript() {
+ File f = new File(applicationProperties.getProperty(Constants.SYS_PROP_XEMELIOS_PRG), "update-script.xml");
+ if (f.exists()) {
+ try {
+ DocumentBuilder domBuilder = FactoryProvider.getDocumentBuilderFactory().newDocumentBuilder();
+ XPath xpath = xpf.newXPath();
+ Document dom = domBuilder.parse(f);
+ NodeList nl = (NodeList) xpath.evaluate("/update-script/*", dom, XPathConstants.NODESET);
+ for (int i=0;i<nl.getLength(); i++) {
+ Node node = nl.item(i);
+ if (node.getNodeType() == Node.ELEMENT_NODE) {
+ String nodeName = node.getNodeName();
+ if ("component".equals(nodeName)) {
+ String id = xpath.evaluate("./@id", node);
+ String version = xpath.evaluate("./@version", node);
+ String description = xpath.evaluate("./@description", node);
+ installComponent(id, version, description);
+ } else if ("configurator".equals(nodeName)) {
+ String className = xpath.evaluate("./@class", node);
+ PropertiesExpansion props = new PropertiesExpansion(applicationProperties);
+ NodeList params = (NodeList) xpath.evaluate("./param", node, XPathConstants.NODESET);
+ for (int j=0;j<params.getLength();j++) {
+ Node p = params.item(j);
+ String paramName = xpath.evaluate("./@name", p);
+ String paramValue = xpath.evaluate("./text()", p);
+ props.put(paramName, paramValue);
+ }
+ executeConfigurator(className, props);
+ } else if ("remove-component".equals(nodeName)) {
+ // TODO: implement this
+ } else {
+ logger.warn("update-script: unexpected element <" + nodeName + "/>");
+ }
+ }
+ }
+ } catch (Throwable t) {
+ new DisplayExceptionDlg((Frame) null, t);
+ }
+ f.delete();
+
+ String htmlindex = GeneratorHelpIndex.generateIndex();
+ String fileName = applicationProperties.replace("${xemelios.root}/help/documents/index.html");
+ //logger.debug("fileName="+fileName);
+ File findex = new File(fileName);
+ if(findex.exists()) {
+ try {
+ FileOutputStream fosindex = new FileOutputStream(findex);
+ fosindex.write(htmlindex.getBytes("ISO-8859-1"));
+ fosindex.flush();
+ fosindex.close();
+ logger.info("new "+findex.getPath()+" wrote.");
+ } catch (FileNotFoundException ex) {
+ logger.error(ex);
+ new DisplayExceptionDlg((Frame) null, ex);
+ } catch (IOException ex) {
+ logger.error(ex);
+ new DisplayExceptionDlg((Frame) null, ex);
+ }
+ }
+
+ // on recharge les propriétés au cas où le configurateur ait changé le xemelios.properties
+// File xemPropsFile = new File(pe.replace("${xemelios.prg}/root/xemelios.properties"));
+// PropertiesExpansion props = new PropertiesExpansion();
+// try {
+// props.load(new FileInputStream(xemPropsFile));
+// } catch(IOException ioEx) {
+// // on ne fait rien
+// }
+// for(Object key:props.keySet()) {
+// System.setProperty((String)key, props.replace((String)key));
+// }
+// pe = new PropertiesExpansion();
+// for(Object key:System.getProperties().keySet()) {
+// pe.setProperty((String)key,System.getProperty((String)key));
+// }
+// componentsModelFileName=pe.getProperty(Constants.SYS_PROP_COMPONENTS_FILENAME);
+// updateUrl=pe.getProperty(Constants.SYSPROP_UPDATE_SOURCE);
+// docModels = getDocumentsInfos(pe.getProperty(Constants.SYS_PROP_DOC_DEF_DIR));
+ }
+ }
+
+ protected void installComponent(String uri, String version, String description) throws Exception {
+ fr.gouv.finances.cp.xemelios.updater.profils.ComponentModel cm =
+ new fr.gouv.finances.cp.xemelios.updater.profils.ComponentModel(uri, version, description, false);
+ UpdateUtil.installComponent(applicationProperties, cm);
+ }
+
+ protected void executeConfigurator(String className, PropertiesExpansion props) throws Exception {
+ logger.info("executing configurator " + className);
+ Class clazz = Class.forName(className);
+ Constructor cons = clazz.getConstructor(new Class[0]);
+ Object o = cons.newInstance(new Object[0]);
+ if (o instanceof AbstractConfigurator) {
+ AbstractConfigurator ac = (AbstractConfigurator) o;
+ ac.setProperties(props);
+ ac.setMainWindow(this);
+ ac.doConfigure();
+ } else {
+ throw new Exception(className + " does not extends " + AbstractConfigurator.class.getName());
+ }
+ }
+
+ public String getCriteriaInputValue(String criteriaId) {
+ if (criteriaId == null) {
+ return null;
+ }
+ return (String) criteriasInputValues.get(criteriaId);
+ }
+
+ public synchronized void setCriteriaInputValue(String criteriaId, String value) {
+ if (criteriaId == null) {
+ return;
+ }
+ if (value != null && value.length() > 0) {
+ criteriasInputValues.put(criteriaId, value);
+ } else {
+ criteriasInputValues.remove(criteriaId);
+ }
+ }
+
+ private static class EmptyStartListener implements StartListener {
+
+ @Override
+ public void notifyMessage(String msg) {
+ }
+
+ @Override
+ public void notifyProgress(int progress) {
+ }
+
+ @Override
+ public void pushProgress() {
+ }
+
+ @Override
+ public void completeProgress() {
+ }
+
+ @Override
+ public void setVisible(boolean visible) {
+ }
+ }
+
+ private final class ActionImport extends AbstractAction {
+
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 3833182540793198128L;
+ String docId, etatId;
+
+ public ActionImport(String titre, String docId) {
+ super(titre);
+ this.docId = docId;
+ }
+
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ importer(docId);
+ }
+ }
+
+ private final class ActionControl extends AbstractAction {
+
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 3833182540793198128L;
+ String docId, etatId;
+
+ public ActionControl(String titre, String docId) {
+ super(titre);
+ this.docId = docId;
+ }
+
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ controller(docId);
+ }
+ }
+
+ private final class ActionSearch extends AbstractAction {
+
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 3617860763465560632L;
+ String docId, etatId, elementId;
+
+ public ActionSearch(String titre, String docId, String etatId, String elementId) {
+ super(titre);
+ this.docId = docId;
+ this.etatId = etatId;
+ this.elementId = elementId;
+ }
+
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ search(docId, etatId, elementId);
+ }
+ }
+
+ public DocumentsModel getDocModels() {
+ return docModels;
+ }
+
+ protected void setMenusAccess() {
+ final Runnable updater = new Runnable() {
+
+ @Override
+ public void run() {
+ searchMenu.setEnabled(getConnectedUser().hasRole(XemeliosUser.ROLE_SEARCH));
+ browseMenu.setEnabled(getConnectedUser().hasRole(XemeliosUser.ROLE_BROWSE));
+ if (importerMenu != null) {
+ importerMenu.setEnabled(getConnectedUser().hasRole(XemeliosUser.ROLE_IMPORT));
+ }
+ if (controlerMenu != null) {
+ controlerMenu.setEnabled(getConnectedUser().hasRole(XemeliosUser.ROLE_IMPORT));
+ }
+ if (mnuClean != null) {
+ mnuClean.setEnabled(getConnectedUser().hasRole(XemeliosUser.ROLE_CLEAN));
+ }
+ if (mnuSupprimer != null) {
+ mnuSupprimer.setEnabled(getConnectedUser().hasRole(XemeliosUser.ROLE_CLEAN));
+ }
+ if (mnuConfigExports != null) {
+ mnuConfigExports.setEnabled(getConnectedUser().hasRole(XemeliosUser.ROLE_EXPORT));
+ }
+ }
+ };
+ SwingUtilities.invokeLater(updater);
+ }
+
+ public StartListener getStartListener() {
+ return startListener;
+ }
+
+ public static MainWindow getInstance() {
+ return instance;
+ }
+
+ @Override
+ protected void finalize() {
+ instance = null;
+ try {
+ if (DataLayerManager.getImplementation() != null) {
+ DataLayerManager.getImplementation().shutdown();
+ }
+ } catch (DataConfigurationException dce) {
+ logger.error(dce, dce);
+ }
+ }
+
+ protected void applyPatches() {
+ AbstractConfigurator ac = null;
+ try {
+// Class clazz = Class.forName("fr.gouv.finances.cp.xemelios.patches.Core4000");
+// ac = (AbstractConfigurator)clazz.newInstance();
+ } catch (Throwable t) {
+ // ignore
+ }
+ if (ac != null) {
+ try {
+// PropertiesExpansion props = new PropertiesExpansion(System.getProperties());
+ ac.setProperties(applicationProperties);
+ ac.run();
+ } catch (Exception ex) {
+ logger.error("while applying patches", ex);
+ System.exit(2);
+ }
+ }
+
+ }
+
+ public static class ImportContent {
+
+ ArrayList<File> filesToImport;
+ ArrayList<PJRef> pjs;
+
+ public ImportContent() {
+ super();
+ filesToImport = new ArrayList<File>();
+ pjs = new ArrayList<PJRef>();
+ }
+
+ public void setFilesToImport(ArrayList<File> array) {
+ this.filesToImport = array;
+ }
+
+ public ArrayList<File> getFilesToImport() {
+ return filesToImport;
+ }
+
+ public ArrayList<PJRef> getPjs() {
+ return pjs;
+ }
+
+ public int getImportCount() {
+ return filesToImport.size() + pjs.size();
+ }
+ }
+
+ public JDesktopPane getDesk() {
+ return desk;
+ }
+
+ private void configExport() {
+ DlgSearchConfig sc = new DlgSearchConfig(this, docModels, DlgSearchConfig.EXEC_FROM_CONF, getConnectedUser());
+ sc.setVisible(true);
+ }
+
+ private void exporterFichier() {
+ DlgExportAll dga = new DlgExportAll(this, true, DlgChooseDocuments.DIALOG_TYPE.FILE, docModels, getConnectedUser());
+ dga.setVisible(true);
+ }
+// private void exporterDonnees() {
+// DlgExportAll dga = new DlgExportAll(this, true, DlgChooseDocuments.DIALOG_TYPE.DATA, docModels, getConnectedUser());
+// dga.setVisible(true);
+// }
+
+
+ public class ForceUpdate extends SwingWorker<Boolean, Object> {
+ UpdateUtil uu;
+ @Override
+ protected Boolean doInBackground() {
+ try {
+ uu = new UpdateUtil(applicationProperties);
+ uu.setCheckMethod(Constants.MAJ_CONFIRM); // on force pour avoir le MsgDialog de fin pour indiquer que c'est terminé
+ uu.checkForUpdates();
+ return uu.updateNeeded();
+ } catch (Exception ex) {
+ logger.error("while checking updates availability",ex);
+ return false;
+ }
+ }
+
+ @Override
+ protected void done() {
+ try {
+ uu.doUpdates();
+ } catch (Throwable t) {}
+ }
+ }
+
+
+ public class UpdateChecker extends SwingWorker<Boolean, Object> {
+ UpdateUtil uuu;
+ @Override
+ protected Boolean doInBackground() {
+
+ try {
+ uuu = new UpdateUtil(applicationProperties);
+ uuu.setCheckMethod(applicationProperties.getProperty(Constants.SYS_PROP_MAJ_STRATEGY));
+ uuu.checkForUpdates();
+ return uuu.updateNeeded();
+ } catch (UnknownHostException ioEx) {
+ logger.info("Impossible d'accéder à "+ioEx.getMessage());
+ return false;
+ } catch (Exception ex) {
+ // On ne fait plus rien : si on arrive pas à accéder, il n'y a pas de mises à jour à faire...
+// new DisplayExceptionDlg(MainWindow.instance, ex);
+ logger.error("while checking updates availability",ex);
+ //JOptionPane.showMessageDialog(MainWindow.instance, ex.getMessage(), "Erreur", JOptionPane.ERROR_MESSAGE);
+ return false;
+ }
+
+ /* OLD V4 CODE
+ UpdaterUtil uu = new UpdaterUtil(MainWindow.instance.updateUrl, MainWindow.instance.componentsModelFileName);
+ return new Boolean(uu.areThereUpdatesAvailable());
+ */
+ }
+
+ @Override
+ protected void done() {
+ try {
+ String checkMethod = applicationProperties.getProperty(Constants.SYS_PROP_MAJ_STRATEGY);
+ if(( checkMethod==null || checkMethod.isEmpty() || "false".equals(checkMethod) ))
+ checkMethod = Constants.MAJ_CONFIRM;
+ logger.debug("start done... checkMethod="+checkMethod);
+
+ if (get().booleanValue()) {
+ /* true si SILENT (et le reste), false sinon mais sera peut etre true si CONFIRM et YES */
+ boolean bDoUpdate = Constants.MAJ_SILENT.equals(checkMethod);
+ /* si aucune méthode de vérification indiqué, on suppose checkMethode = MAJ_CONFIRM */
+ if(Constants.MAJ_CONFIRM.equals(checkMethod)) {
+// String message = "<html>Des mises à jour sont disponibles.<br><br>Voulez-vous les installer ?</html>";
+ bDoUpdate = (JOptionPane.YES_OPTION == new DlgConfirmDownloadUpdate(MainWindow.this, uuu).run());
+ }
+ if(bDoUpdate) {
+ logger.debug("doUpdates()...");
+ uuu.doUpdates();
+ }
+ logger.debug("end done...");
+ }
+ } catch (Throwable t) {
+ }
+ }
+ }
+
+ protected JMenu loadToolMenu() {
+ JMenu ret = new JMenu("Outils");
+ // load components list
+// XemeliosComponentsModel components = null;
+// try {
+// XemeliosComponentsParser parser = new XemeliosComponentsParser();
+// parser.parse(new File(applicationProperties.getProperty(Constants.SYS_PROP_COMPONENTS_FILENAME)));
+// components = (XemeliosComponentsModel) parser.getMarshallable();
+// } catch (Throwable t) {
+// }
+// if (components == null) {
+// components = new XemeliosComponentsModel(XemeliosComponentsModel.QN);
+// }
+ String sDir = applicationProperties.getProperty(Constants.SYS_PROP_XEMELIOS_TOOLS_DIR);
+ if (sDir != null) {
+ String[] directories = sDir.split(",");
+ for (String currentDirectory : directories) {
+ // replacing ${....} variables
+ currentDirectory = applicationProperties.replace(currentDirectory);
+ File dir = new File(currentDirectory);
+ if (dir.exists() && dir.isDirectory()) {
+ File[] jars = dir.listFiles(new java.io.FileFilter() {
+
+ @Override
+ public boolean accept(File pathname) {
+ return (pathname.getName().toUpperCase().endsWith(".JAR"));
+ }
+ });
+ for (File jar : jars) {
+ try {
+ JarFile jf = new JarFile(jar);
+ Manifest mn = jf.getManifest();
+ System.out.println("***************************************************************************");
+ String toolClassName = mn.getMainAttributes().getValue(ToolConstants.TOOL_CLASS);
+ System.out.println(toolClassName);
+ String toolRequires = mn.getMainAttributes().getValue(ToolConstants.TOOL_REQUIRES);
+ String toolDescription = null;
+ String toolIcon = mn.getMainAttributes().getValue(ToolConstants.TOOL_ICON);
+ jf.close();
+ if (toolClassName != null && toolClassName.length() > 0) {
+ try {
+ /*if (toolRequires != null && toolRequires.length() > 3) {
+ String[] requiredComps = toolRequires.split(";");
+ for (String comp : requiredComps) {
+ String[] compDetails = comp.split(",");
+ if (compDetails.length == 2) {
+ fr.gouv.finances.dgfip.xemelios.common.components.ComponentModel installedComp = components.getComponent(compDetails[0]);
+ if (installedComp == null) {
+ throw new Exception("Component " + compDetails[0] + " (" + compDetails[1] + ") required");
+ }
+ if (!installedComp.isNewerOrEqualThan(compDetails[1])) {
+ throw new Exception(installedComp.getId() + " " + installedComp.getVersion() + ") to old: " + compDetails[1] + " required");
+ }
+ }
+ }
+ }*/
+ // tout est OK, on ajoute le jar au classpath
+ //if (!"true".equals(applicationProperties.getProperty(Constants.SYS_PROP_XEMELIOS_AVOID_TOOL_JAR_LOADING))) {
+ Bootstrap.addFile(jar);
+ //}
+ Class clazz = null;
+ try {
+ clazz = Class.forName(toolClassName);
+ @SuppressWarnings("unchecked")
+ MenuTitle mt = (MenuTitle) clazz.getAnnotation(MenuTitle.class);
+ if (mt != null) {
+ toolDescription = mt.value();
+ } else {
+ logger.error("Plugin Class " + toolClassName + " doesn't provide annotation @MenuTitle");
+ }
+ } catch (Exception ex) {
+ logger.error(ex.getMessage(), ex);
+ }
+ if (toolDescription != null && toolDescription.length() > 0) {
+ Action a = null;
+ if (toolIcon != null) {
+ ImageIcon img = IhmFactory.getIconFromResource(toolIcon);
+ if (img != null) {
+ a = new ActionPlugin(toolClassName, toolDescription, img);
+ } else {
+ a = new ActionPlugin(toolClassName, toolDescription);
+ }
+ } else {
+ a = new ActionPlugin(toolClassName, toolDescription);
+ }
+ JMenuItem mnuItem = new JMenuItem(a);
+ ret.add(mnuItem);
+ }
+ } catch (Exception ex) {
+ logger.info("can not install plugin " + toolClassName + ": " + ex.getMessage());
+ continue;
+ }
+ }
+ } catch (Throwable t) {
+ }
+ }
+ }
+ }
+ if (ret.getItemCount() > 0) {
+ return ret;
+ }
+ }
+ return null;
+ }
+
+ public PropertiesExpansion getEnvProperties() {
+ return applicationProperties;
+ }
+
+ private void doFirstStartConfiguration() {
+ getStartListener().setVisible(false);
+ try {
+ WizardPage.WizardResultProducer producer = new WizardPage.WizardResultProducer() {
+
+ @Override
+ public boolean cancel(Map map) {
+ return true;
+ }
+
+ @Override
+ public Object finish(Map map) throws WizardException {
+ // on charge le xemelios.properties
+ Properties props = new Properties();
+ File f = new File(new File(getEnvProperties().replace("${xemelios.prg}")), "/root/xemelios.properties");
+ try {
+ props.load(new FileInputStream(f));
+ } catch (IOException ioEx) {
+ logger.error("impossible de charger les propriétés depuis "+f.getAbsolutePath());
+ }
+ // on regarde d'abord le proxy
+ if (Boolean.TRUE.equals(map.get("in.tresor"))) {
+ logger.debug("on est dans le trésor");
+ props.setProperty(Constants.SYS_PROP_PROXY_SERVER, "proxy.bercy.cp");
+ getEnvProperties().setProperty(Constants.SYS_PROP_PROXY_SERVER, "proxy.bercy.cp");
+ props.setProperty(Constants.SYS_PROP_PROXY_PORT, "3128");
+ getEnvProperties().setProperty(Constants.SYS_PROP_PROXY_PORT, "3128");
+ props.remove(Constants.SYS_PROP_PROXY_DOMAIN);
+ props.remove(Constants.SYS_PROP_PROXY_PASSWD);
+ props.remove(Constants.SYS_PROP_PROXY_USER);
+ getEnvProperties().remove(Constants.SYS_PROP_PROXY_DOMAIN);
+ getEnvProperties().remove(Constants.SYS_PROP_PROXY_PASSWD);
+ getEnvProperties().remove(Constants.SYS_PROP_PROXY_USER);
+ } else {
+ logger.debug("on est pas dans le trésor");
+ if (Boolean.TRUE.equals(map.get("is.use.proxy"))) {
+ logger.debug("on utilise un proxy");
+ props.setProperty(Constants.SYS_PROP_PROXY_SERVER, map.get("proxy.server").toString());
+ getEnvProperties().setProperty(Constants.SYS_PROP_PROXY_SERVER, map.get("proxy.server").toString());
+ if (exists(map.get("proxy.port"))) {
+ props.setProperty(Constants.SYS_PROP_PROXY_PORT, map.get("proxy.port").toString());
+ getEnvProperties().setProperty(Constants.SYS_PROP_PROXY_PORT, map.get("proxy.port").toString());
+ } else {
+ props.remove(Constants.SYS_PROP_PROXY_PORT);
+ getEnvProperties().remove(Constants.SYS_PROP_PROXY_PORT);
+ }
+ if (exists(map.get("proxy.user"))) {
+ props.setProperty(Constants.SYS_PROP_PROXY_USER, map.get("proxy.user").toString());
+ getEnvProperties().setProperty(Constants.SYS_PROP_PROXY_USER, map.get("proxy.user").toString());
+ if (exists(map.get("proxy.password"))) {
+ props.setProperty(Constants.SYS_PROP_PROXY_PASSWD, map.get("proxy.password").toString());
+ getEnvProperties().setProperty(Constants.SYS_PROP_PROXY_PASSWD, map.get("proxy.password").toString());
+ } else {
+ props.remove(Constants.SYS_PROP_PROXY_PASSWD);
+ getEnvProperties().remove(Constants.SYS_PROP_PROXY_PASSWD);
+ }
+ if (exists(map.get("proxy.domain"))) {
+ props.setProperty(Constants.SYS_PROP_PROXY_DOMAIN, map.get("proxy.domain").toString());
+ getEnvProperties().setProperty(Constants.SYS_PROP_PROXY_DOMAIN, map.get("proxy.domain").toString());
+ } else {
+ props.remove(Constants.SYS_PROP_PROXY_DOMAIN);
+ getEnvProperties().remove(Constants.SYS_PROP_PROXY_DOMAIN);
+ }
+ } else {
+ props.remove(Constants.SYS_PROP_PROXY_USER);
+ props.remove(Constants.SYS_PROP_PROXY_PASSWD);
+ props.remove(Constants.SYS_PROP_PROXY_DOMAIN);
+ getEnvProperties().remove(Constants.SYS_PROP_PROXY_USER);
+ getEnvProperties().remove(Constants.SYS_PROP_PROXY_PASSWD);
+ getEnvProperties().remove(Constants.SYS_PROP_PROXY_DOMAIN);
+ }
+ } else {
+ logger.debug("on n'utilise pas de proxy");
+ props.remove(Constants.SYS_PROP_PROXY_SERVER);
+ props.remove(Constants.SYS_PROP_PROXY_PORT);
+ props.remove(Constants.SYS_PROP_PROXY_USER);
+ props.remove(Constants.SYS_PROP_PROXY_PASSWD);
+ props.remove(Constants.SYS_PROP_PROXY_DOMAIN);
+ getEnvProperties().remove(Constants.SYS_PROP_PROXY_SERVER);
+ getEnvProperties().remove(Constants.SYS_PROP_PROXY_PORT);
+ getEnvProperties().remove(Constants.SYS_PROP_PROXY_USER);
+ getEnvProperties().remove(Constants.SYS_PROP_PROXY_PASSWD);
+ getEnvProperties().remove(Constants.SYS_PROP_PROXY_DOMAIN);
+ }
+ }
+ props.setProperty(Constants.SYS_PROP_FIRST_START, "true");
+ getEnvProperties().setProperty(Constants.SYS_PROP_FIRST_START, "true");
+ try {
+ props.store(new FileOutputStream(f), null);
+ } catch (IOException ioEx) {
+ // meme pas j'y crois
+ }
+ try {
+ UpdateUtil uu = new UpdateUtil(getEnvProperties());
+ uu.checkForUpdates();
+ if(uu.updateNeeded()) {
+ uu.doUpdates();
+ }
+ } catch(Exception ex) {
+ logger.error("first update",ex);
+ }
+ return null;
+ }
+ };
+ Wizard wiz = WizardPage.createWizard(new Class[]{
+ PnlPresentation.class,
+ PnlFirstConfigProxy.class,
+ PnlFirstAbo.class
+ }, producer);
+ Map response = (Map) WizardDisplayer.showWizard(wiz);
+ } catch (Throwable t) {
+ t.printStackTrace();
+ }
+ getStartListener().setVisible(true);
+ }
+
+ private boolean exists(Object o) {
+ return o != null && o.toString().length() > 0;
+ }
+
+ private class ActionPlugin extends AbstractAction {
+
+ private static final long serialVersionUID = 1L;
+ private String className = null;
+
+ public ActionPlugin(String className, String desc) {
+ super(desc);
+ this.className = className;
+ }
+
+ public ActionPlugin(String className, String desc, Icon icon) {
+ super(desc, icon);
+ this.className = className;
+ }
+
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ try {
+ Class clazz = Class.forName(className);
+ Object o = clazz.newInstance();
+ if (o instanceof AbstractTool) {
+ AbstractTool at = (AbstractTool) o;
+ at.run();
+ } else {
+ throw new Exception(className + " does not extends " + AbstractTool.class.getName());
+ }
+ } catch (Exception ex) {
+ new DisplayExceptionDlg(MainWindow.instance, ex);
+ }
+ }
+ }
+
+ private class PoolStatDisplayer extends JPanel {
+
+ private static final long serialVersionUID = 1L;
+ private JLabel lblActive = null, lblIdle = null;
+
+ public PoolStatDisplayer() {
+ super();
+ add(new JLabel("Active(s): "));
+ add(lblActive = new JLabel("0"));
+ add(new JLabel(" Idle(s): "));
+ add(lblIdle = new JLabel("0"));
+ Timer timer = new Timer(500, new ActionListener() {
+
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ try {
+// DataImpl di = DataLayerManager.getImplementation();
+ if (PoolManager.getInstance() != null && PoolManager.getInstance().getPool() != null) {
+ Pool pool = PoolManager.getInstance().getPool();
+ lblActive.setText(Integer.toString(pool.getNumActive()));
+ lblIdle.setText(Integer.toString(pool.getNumIdle()));
+ }
+ } catch (Exception ex) {
+ // TODO
+ }
+ }
+ });
+ timer.start();
+ }
+ }
+
+ public static class XemeliosArchiveImporterWorker extends SwingWorker<XemeliosArchiveImporter.Errors, String> {
+
+ private XemeliosArchiveImporter importer;
+ private Errors errors;
+
+ public XemeliosArchiveImporterWorker(XemeliosArchiveImporter importer) {
+ super();
+ this.importer = importer;
+ }
+
+ @Override
+ protected Errors doInBackground() throws Exception {
+ errors = importer.doImport();
+ return errors;
+ }
+
+ @Override
+ protected void done() {
+ SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
+ logger.debug("Fin import archive a " + sdf.format(new Date()));
+ StringBuilder sb = new StringBuilder();
+ if (errors != null) {
+ for (XemeliosArchiveImporter.Error error : errors.getErrors()) {
+ sb.append("<").append(error.getSeverityMessage()).append("> ").append(error.getMessage()).append("\n");
+ }
+ }
+ if (sb.length() > 0) {
+ JOptionPane.showMessageDialog(MainWindow.getInstance(), sb.toString());
+ } else {
+ // pas d'erreur
+ JOptionPane.showMessageDialog(MainWindow.getInstance(), importer.getFileInfo().toString(importer.getDocumentsModel()));
+ }
+
+ }
+ }
+
+// public enum EXPORT_TYPES {
+//
+// CSV, XLS
+// };
+//
+// public EXPORT_TYPES getExportType() {
+// return exportType;
+// }
+ private Properties getHomeProperties(){
+ File f = new File(System.getProperty("user.home"), "xemelios.properties");
+ Properties props = new Properties();
+ if (f.exists()) {
+ try {
+ props.load(new FileInputStream(f));
+ } catch (IOException ioEx) {
+ }
+ }
+ return props;
+ }
+
+ public PnlUpdaterProgress getUpdaterProgress() { return pup; }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 N.Le Corre - nicolas.lecorre@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui;
+
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import fr.gouv.finances.dgfip.xemelios.auth.UnauthorizedException;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+import fr.gouv.finances.dgfip.xemelios.data.DatabaseTreeDataDonnee;
+import javax.swing.JDialog;
+import javax.swing.JTree;
+import javax.swing.ScrollPaneConstants;
+import javax.swing.tree.TreeSelectionModel;
+
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentsModel;
+import fr.gouv.finances.dgfip.xemelios.data.WaitableUI;
+import java.awt.Cursor;
+
+/**
+ *
+ * @author nicolas.lecorre
+ */
+@SuppressWarnings("serial")
+public class PanelChooseDatabaseDonnees extends javax.swing.JPanel implements WaitableUI {
+ DocumentsModel dms = null;
+ private XemeliosUser user;
+ private PropertiesExpansion applicationConfiguration;
+
+ /** Creates new form PanelCleanDatabaseDonnees */
+ public PanelChooseDatabaseDonnees(JDialog p, DocumentsModel d,XemeliosUser user, PropertiesExpansion applicationConfiguration) {
+ dms = d;
+ this.user=user;
+ this.applicationConfiguration = applicationConfiguration;
+ try {
+ initComponents();
+ } catch(UnauthorizedException ex) {
+ //
+ }
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ */
+ private void initComponents() throws UnauthorizedException {
+ jPanel2 = new javax.swing.JPanel();
+ jLabel1 = new javax.swing.JLabel();
+ jTree1 = new JTree(new DatabaseTreeDataDonnee(dms,(WaitableUI)this,user, applicationConfiguration));
+ jTree1.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
+ jTree1.setScrollsOnExpand(true);
+ jScrollPane1 = new javax.swing.JScrollPane(jTree1);
+ jScrollPane1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
+
+ jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Documents"));
+ jPanel2.setMinimumSize(new java.awt.Dimension(1100, 83));
+ jPanel2.setPreferredSize(new java.awt.Dimension(239, 384));
+ jLabel1.setText("S\u00e9lectionnez dans la liste ci-dessous le ou les \u00e9l\u00e9ment(s)");
+ jLabel1.setVerticalAlignment(javax.swing.SwingConstants.TOP);
+
+ jScrollPane1.setViewportView(jTree1);
+
+ org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
+ jPanel2.setLayout(jPanel2Layout);
+ jPanel2Layout.setHorizontalGroup(
+ jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(jPanel2Layout.createSequentialGroup()
+ .addContainerGap()
+ .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 642, Short.MAX_VALUE)
+ .add(jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 642, Short.MAX_VALUE))
+ .addContainerGap())
+ );
+ jPanel2Layout.setVerticalGroup(
+ jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(jPanel2Layout.createSequentialGroup()
+ .add(jLabel1)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 323, Short.MAX_VALUE)
+ .addContainerGap())
+ );
+
+ org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
+ this.setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 680, Short.MAX_VALUE)
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addContainerGap())
+ );
+ }
+
+
+ private javax.swing.JLabel jLabel1;
+ private javax.swing.JPanel jPanel2;
+ private javax.swing.JScrollPane jScrollPane1;
+ private javax.swing.JTree jTree1;
+
+ public javax.swing.JTree getJTree1() {
+ return jTree1;
+ }
+
+ public void startWait() {
+ setCursor(new Cursor(Cursor.WAIT_CURSOR));
+ }
+
+ public void stopWait() {
+ setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 N.Le Corre - nicolas.lecorre@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui;
+
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import java.awt.Component;
+import java.util.Vector;
+
+import javax.swing.DefaultCellEditor;
+import javax.swing.JCheckBox;
+import javax.swing.JDialog;
+import javax.swing.JLabel;
+import javax.swing.JRadioButton;
+import javax.swing.JTable;
+import javax.swing.table.DefaultTableCellRenderer;
+import javax.swing.table.TableCellEditor;
+import javax.swing.table.TableCellRenderer;
+import javax.swing.tree.TreeSelectionModel;
+
+import org.apache.log4j.Logger;
+import org.jdesktop.swingx.JXTreeTable;
+
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.dgfip.xemelios.auth.UnauthorizedException;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentsModel;
+import fr.gouv.finances.dgfip.xemelios.data.DataAccessException;
+import fr.gouv.finances.dgfip.xemelios.data.DataConfigurationException;
+import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
+import fr.gouv.finances.dgfip.xemelios.data.ExportableData;
+
+/**
+ *
+ * @author nicolas.lecorre
+ */
+@SuppressWarnings("serial")
+public class PanelChooseDatabaseFichier extends javax.swing.JPanel {
+ private static final Logger logger = Logger.getLogger(PanelChooseDatabaseFichier.class);
+ private DocumentsModel dms = null;
+ private DatabaseTreeDataFichier data = null;
+ private boolean selectionMultiple = true;
+ private int mode = MODE_SUPPRESSION;
+
+ public static final int MODE_SUPPRESSION = 0;
+ public static final int MODE_EXPORT = 1;
+
+ private XemeliosUser user;
+
+ private PropertiesExpansion applicationConfiguration;
+
+ public DatabaseTreeDataFichier getData() {
+ return data;
+ }
+
+ /** Creates new form PanelCleanDatabaseFichier */
+ public PanelChooseDatabaseFichier(JDialog p, DocumentsModel d, boolean selectionMultiple,XemeliosUser user, PropertiesExpansion applicationConfiguration) {
+ dms = d;
+ this.selectionMultiple = selectionMultiple;
+ this.user=user;
+ this.applicationConfiguration = applicationConfiguration;
+ initComponents();
+ try {
+ fillDocType();
+ } catch(UnauthorizedException ex) {
+ //
+ }
+ data = new DatabaseTreeDataFichier (listeFichiers);
+ data.setMode(getMode());
+ data.setSelectionMultiple(this.selectionMultiple);
+ listeFichiers.setTreeTableModel(data);
+ listeFichiers.setRootVisible(false);
+ }
+
+ private void fillDocType () throws UnauthorizedException {
+ Vector<Pair> v = new Vector<Pair>();
+ v.add(new Pair("RIEN", "Tous"));
+ cbTypeDoc.addItem(new Pair("RIEN", "Tous"));
+ for (DocumentModel d:dms.getDocuments()) {
+ if(d.getDisplayInMenuIf()==null || "true".equals(applicationConfiguration.getProperty(d.getDisplayInMenuIf())))
+ v.add (new Pair(d.getId(), d.getTitre()));
+ }
+ cbTypeDoc.setModel(new javax.swing.DefaultComboBoxModel(v));
+ fillColl ();
+ fillBudg ();
+ }
+
+ private void fillColl () throws UnauthorizedException {
+ String selectedDocId = ((Pair)cbTypeDoc.getSelectedItem()).key;
+ Vector<Pair> v = new Vector<Pair>();
+ v.add(new Pair("RIEN", "Toutes"));
+ if (!"RIEN".equals(selectedDocId)) {
+ DocumentModel selectedDocumentModel = dms.getDocumentById(selectedDocId);
+ Vector<Pair> collectivites = getCollectivitesFromDocumentModel(selectedDocumentModel);
+ v.addAll(collectivites);
+ }
+ this.cbCollectivite.setModel(new javax.swing.DefaultComboBoxModel(v));
+ fillBudg ();
+ }
+
+ private void fillBudg () {
+ String selectedDocId = ((Pair)cbTypeDoc.getSelectedItem()).key;
+ Pair selectedColl = (Pair)cbCollectivite.getSelectedItem();
+ Vector<Pair> v = new Vector<Pair>();
+ v.add(new Pair("RIEN", "Tous"));
+ if (!"RIEN".equals(selectedColl.key)) {
+ DocumentModel selectedDocumentModel = dms.getDocumentById(selectedDocId);
+ try {
+ Vector<Pair> budgets = DataLayerManager.getImplementation().getBudgets(selectedDocumentModel, selectedColl, user);
+ v.addAll(budgets);
+ } catch (Exception e) {
+// logger.debug("Ce n'est pas grave, on n'a juste pas reussi a trouver le budget", e);
+ }
+ }
+ this.cbBudget.setModel(new javax.swing.DefaultComboBoxModel(v));
+ }
+
+ protected Vector<Pair> getCollectivitesFromDocumentModel(DocumentModel dm) throws UnauthorizedException {
+ Vector<Pair> ret = null;
+ try {
+ // TODO: mettre la hierarchie de collectivites
+ ret = DataLayerManager.getImplementation().getCollectivites(dm,null,user);
+ } catch(DataAccessException daEx) {
+ logger.warn("",daEx);
+ ret = new Vector<Pair>();
+ } catch(DataConfigurationException dcEx) {
+ logger.error("",dcEx);
+ ret = new Vector<Pair>();
+ }
+ return ret;
+ }
+
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ private void initComponents() {
+ jPanel2 = new javax.swing.JPanel();
+ jScrollPane2 = new javax.swing.JScrollPane();
+ listeFichiers = new JXTreeTablePropertyEditor (this.selectionMultiple);
+ bSelectAll = new javax.swing.JButton();
+ bUnSelectAll = new javax.swing.JButton();
+ jPanel1 = new javax.swing.JPanel();
+ jLabel1 = new javax.swing.JLabel();
+ cbCollectivite = new javax.swing.JComboBox();
+ jLabel2 = new javax.swing.JLabel();
+ jLabel3 = new javax.swing.JLabel();
+ cbBudget = new javax.swing.JComboBox();
+ jLabel4 = new javax.swing.JLabel();
+ cbTypeDoc = new javax.swing.JComboBox();
+ bRechercher = new javax.swing.JButton();
+
+ jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Documents"));
+ jPanel2.setMinimumSize(new java.awt.Dimension(1031, 83));
+// listeFichiers.setMaximumSize(new java.awt.Dimension(32000, 32000));
+// listeFichiers.setPreferredSize(new java.awt.Dimension(0, 0));
+ if (!this.selectionMultiple)
+ listeFichiers.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
+ listeFichiers.setRootVisible(true);
+ listeFichiers.setShowHorizontalLines(true);
+ listeFichiers.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_LAST_COLUMN);
+ jScrollPane2.setViewportView(listeFichiers);
+
+ bSelectAll.setText("Tout s\u00e9lectionner");
+ bUnSelectAll.setText("Tout d\u00e9s\u00e9lectionner");
+
+ if(!selectionMultiple) {
+ bSelectAll.setEnabled(false);
+ bUnSelectAll.setEnabled(false);
+ }
+
+ org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
+ jPanel2.setLayout(jPanel2Layout);
+ jPanel2Layout.setHorizontalGroup(
+ jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(jPanel2Layout.createSequentialGroup()
+ .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(jPanel2Layout.createSequentialGroup()
+ .addContainerGap()
+ .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 642, Short.MAX_VALUE))
+ .add(jPanel2Layout.createSequentialGroup()
+ .add(204, 204, 204)
+ .add(bSelectAll)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(bUnSelectAll)))
+ .addContainerGap())
+ );
+ jPanel2Layout.setVerticalGroup(
+ jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(jPanel2Layout.createSequentialGroup()
+ .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(bSelectAll)
+ .add(bUnSelectAll))
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE)
+ .addContainerGap())
+ );
+
+ jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Recherche"));
+ jPanel1.setMinimumSize(new java.awt.Dimension(0, 0));
+ jPanel1.setPreferredSize(new java.awt.Dimension(0, 0));
+ jLabel1.setText("S\u00e9lectionnez dans la liste ci-dessous le type de document, la collectivit\u00e9 et le budget");
+ jLabel1.setVerticalAlignment(javax.swing.SwingConstants.TOP);
+
+ cbCollectivite.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
+ cbCollectivite.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ cbCollectiviteActionPerformed(evt);
+ }
+ });
+
+ jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
+ jLabel2.setText("Collectivit\u00e9");
+
+ jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
+ jLabel3.setText("Budget");
+
+ cbBudget.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
+ cbBudget.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ cbBudgetActionPerformed(evt);
+ }
+ });
+
+ jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
+ jLabel4.setText("Type de document");
+
+ cbTypeDoc.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
+ cbTypeDoc.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ cbTypeDocActionPerformed(evt);
+ }
+ });
+
+ bRechercher.setText("Rechercher");
+ bRechercher.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ bRechercherActionPerformed(evt);
+ }
+ });
+
+ bSelectAll.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ bSelectAllPerformed(evt);
+ }
+ });
+
+ bUnSelectAll.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ bUnSelectAllPerformed(evt);
+ }
+ });
+
+ org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
+ jPanel1.setLayout(jPanel1Layout);
+ jPanel1Layout.setHorizontalGroup(
+ jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(jPanel1Layout.createSequentialGroup()
+ .addContainerGap()
+ .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 642, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
+ .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
+ .add(jLabel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .add(jLabel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 136, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
+ .add(12, 12, 12)
+ .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
+ .add(cbBudget, 0, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .add(cbTypeDoc, 0, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .add(cbCollectivite, 0, 313, Short.MAX_VALUE))
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 94, Short.MAX_VALUE)
+ .add(bRechercher)))
+ .addContainerGap())
+ );
+
+ jPanel1Layout.linkSize(new java.awt.Component[] {jLabel2, jLabel3, jLabel4}, org.jdesktop.layout.GroupLayout.HORIZONTAL);
+
+ jPanel1Layout.setVerticalGroup(
+ jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(jPanel1Layout.createSequentialGroup()
+ .add(jLabel1)
+ .add(19, 19, 19)
+ .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(jLabel4)
+ .add(cbTypeDoc, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 22, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(jLabel2)
+ .add(cbCollectivite, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
+ .add(7, 7, 7)
+ .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(jLabel3)
+ .add(cbBudget, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .add(bRechercher, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ );
+
+ jPanel1Layout.linkSize(new java.awt.Component[] {cbBudget, cbCollectivite, cbTypeDoc}, org.jdesktop.layout.GroupLayout.VERTICAL);
+
+ org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
+ this.setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
+ .addContainerGap()
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
+ .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 680, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel2, 0, 680, Short.MAX_VALUE))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 154, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addContainerGap())
+ );
+ }
+
+ private void cbTypeDocActionPerformed(java.awt.event.ActionEvent evt) {
+ try {
+ fillColl();
+ } catch(UnauthorizedException ex) {
+
+ }
+ }
+
+ private void bSelectAllPerformed(java.awt.event.ActionEvent evt) {
+ selectAllChilds(data.getData(), true);
+ listeFichiers.repaint();
+ }
+ private void bUnSelectAllPerformed(java.awt.event.ActionEvent evt) {
+ selectAllChilds(data.getData(), false);
+ listeFichiers.repaint();
+ }
+ private void selectAllChilds (ExportableData d, boolean selected) {
+ for (ExportableData dd:d.getChilds()) {
+ dd.setSelected(selected);
+ selectAllChilds (dd, selected);
+ }
+ }
+
+ private void bRechercherActionPerformed(java.awt.event.ActionEvent evt) {
+ try {
+ String coll = ((Pair)cbCollectivite.getSelectedItem()).key;
+ if ("RIEN".equals(coll)) coll=null;
+ String budg = ((Pair)cbBudget.getSelectedItem()).key;
+ if ("RIEN".equals(budg)) budg=null;
+ if (cbTypeDoc.getSelectedIndex()==0) {
+ Vector<ExportableData> datas = DataLayerManager.getImplementation().searchFichiers(dms, coll, budg, user);
+ data = new DatabaseTreeDataFichier(datas, listeFichiers);
+ data.setMode(getMode());
+ data.setSelectionMultiple(this.selectionMultiple);
+ listeFichiers.setTreeTableModel(data);
+ listeFichiers.getColumnModel().getColumn(1).setMaxWidth(25);
+ listeFichiers.setRootVisible(true);
+ } else {
+ String selectedDocId = ((Pair)cbTypeDoc.getSelectedItem()).key;
+ Vector<ExportableData> datas = new Vector<ExportableData>();
+ ExportableData d = DataLayerManager.getImplementation().searchFichiers(dms.getDocumentById(selectedDocId), coll, budg, user);
+ if (d != null)
+ datas.add(d);
+ data = new DatabaseTreeDataFichier(datas, listeFichiers);
+ data.setMode(getMode());
+ data.setSelectionMultiple(this.selectionMultiple);
+ listeFichiers.setTreeTableModel(data);
+ listeFichiers.getColumnModel().getColumn(1).setMaxWidth(25);
+ listeFichiers.setRootVisible(true);
+ }
+ } catch (Exception e) {
+ logger.error("", e);
+ }
+ }
+
+ public void refresh () {
+ bRechercherActionPerformed (null);
+ }
+
+ private void cbBudgetActionPerformed(java.awt.event.ActionEvent evt) {
+// TODO add your handling code here:
+ }
+
+ private void cbCollectiviteActionPerformed(java.awt.event.ActionEvent evt) {
+ fillBudg();
+ }
+
+
+ // Variables declaration - do not modify
+ private javax.swing.JButton bRechercher;
+ private javax.swing.JComboBox cbBudget;
+ private javax.swing.JComboBox cbCollectivite;
+ private javax.swing.JComboBox cbTypeDoc;
+ private javax.swing.JButton bSelectAll;
+ private javax.swing.JButton bUnSelectAll;
+ private javax.swing.JLabel jLabel1;
+ private javax.swing.JLabel jLabel2;
+ private javax.swing.JLabel jLabel3;
+ private javax.swing.JLabel jLabel4;
+ private javax.swing.JPanel jPanel1;
+ private javax.swing.JPanel jPanel2;
+ private javax.swing.JScrollPane jScrollPane2;
+ private org.jdesktop.swingx.JXTreeTable listeFichiers;
+ // End of variables declaration
+
+ public org.jdesktop.swingx.JXTreeTable getListeFichiers() {
+ return listeFichiers;
+ }
+
+ private class JXTreeTablePropertyEditor extends JXTreeTable {
+ private TableCellEditor booleanEditor;
+ private TableCellRenderer booleanRenderer, booleanRendererExclusif, blankRenderer;
+ private boolean selectionMultiple = true;
+// private TreeTableModel model = null;
+ public JXTreeTablePropertyEditor(boolean selectionMultiple) {
+ super();
+ getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
+ this.selectionMultiple = selectionMultiple;
+ booleanEditor = new DefaultCellEditor(new JCheckBox()) {
+ @Override
+ public Component getTableCellEditorComponent(JTable table,Object value,boolean isSelected,int row,int column) {
+ Component c = super.getTableCellEditorComponent(table,value,isSelected,row,column);
+ JCheckBox chk = (JCheckBox)editorComponent;
+ chk.setSelected(((Boolean)value).booleanValue());
+ chk.setBackground(c.getBackground());
+ return chk;
+ }
+ };
+ booleanRendererExclusif = new DefaultTableCellRenderer() {
+ private JRadioButton rb = new JRadioButton();
+ @Override
+ public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column) {
+ JLabel lbl = (JLabel)super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
+ rb.setSelected(((Boolean)value).booleanValue());
+ rb.setBackground(lbl.getBackground());
+ rb.setBorder(lbl.getBorder());
+ return rb;
+ }
+ };
+ booleanRenderer = new DefaultTableCellRenderer() {
+ private JCheckBox chk = new JCheckBox();
+ @Override
+ public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column) {
+ JLabel lbl = (JLabel)super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
+ chk.setSelected(((Boolean)value).booleanValue());
+ chk.setBackground(lbl.getBackground());
+ chk.setBorder(lbl.getBorder());
+ return chk;
+ }
+ };
+ blankRenderer = new DefaultTableCellRenderer() {
+ @Override
+ public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column) {
+ JLabel lbl = (JLabel)super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
+ lbl.setText("");
+ return lbl;
+ }
+ };
+ }
+ @Override
+ public TableCellEditor getCellEditor (int row, int column) {
+ if (row>0 && column==1) {
+ if (selectionMultiple)
+ return booleanEditor;
+ else
+ return booleanEditor;//booleanEditorExclusif;
+ } else {
+ return super.getCellEditor(row, column);
+ }
+ }
+ @Override
+ public TableCellRenderer getCellRenderer(int row, int column) {
+ if (row==0 && column==1) {
+ return blankRenderer;
+ } else if(column==1) {
+ if (selectionMultiple)
+ return booleanRenderer;
+ else {
+ Object o = PanelChooseDatabaseFichier.this.listeFichiers.getPathForRow(row).getLastPathComponent();
+ if(PanelChooseDatabaseFichier.this.data.isCellEditable(o,column))
+ return booleanRendererExclusif;
+ else
+ return blankRenderer;
+ }
+ } else {
+ return super.getCellRenderer(row,column);
+ }
+ }
+ }
+
+ public DocumentModel getDMSelected () {
+ return dms.getDocumentById(((Pair)cbTypeDoc.getSelectedItem()).key);
+ }
+
+ public int getMode() {
+ return mode;
+ }
+
+ public void setMode(int mode) {
+ this.mode = mode;
+ }
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ * 2008 JP.Tessier - jean-philippe.tessier@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui;
+
+import java.awt.Rectangle;
+import java.awt.event.MouseEvent;
+import java.beans.PropertyChangeListener;
+import java.io.File;
+import java.util.Iterator;
+
+import javax.swing.JInternalFrame;
+import javax.swing.event.InternalFrameAdapter;
+import javax.swing.event.InternalFrameEvent;
+import javax.swing.event.InternalFrameListener;
+
+import org.apache.log4j.Logger;
+
+
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+import fr.gouv.finances.dgfip.xemelios.common.ToolException;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
+import fr.gouv.finances.cp.xemelios.ui.resulttable.EtatResultTableModel;
+import fr.gouv.finances.cp.xemelios.ui.search.PnlSearch;
+import fr.gouv.finances.dgfip.utils.XmlUtils;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
+import fr.gouv.finances.dgfip.utils.xml.transform.CustomURIResolver;
+import fr.gouv.finances.dgfip.xemelios.common.config.HiddenModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.Loader;
+import fr.gouv.finances.dgfip.xemelios.data.DataHandler;
+import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
+import fr.gouv.finances.dgfip.xemelios.swing.InfiniteGlassPane;
+import java.awt.event.KeyEvent;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.FileInputStream;
+import java.io.InputStream;
+import javax.swing.JComponent;
+import javax.swing.KeyStroke;
+import javax.swing.SwingUtilities;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.URIResolver;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathConstants;
+import org.jdesktop.swingx.JXTable;
+import org.w3c.dom.Document;
+
+
+/**
+ * Fenetre de recherche
+ * @author Christophe MARCHAND
+ */
+public class SearchWindow extends JInternalFrame {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 3257002159676469814L;
+ private static Logger logger = Logger.getLogger(SearchWindow.class);
+
+ public MainWindow parentFrame;
+
+ // others
+ private ElementModel em;
+ private static int frameCount = 1;
+ private int rank = 0;
+
+ private XemeliosUser user;
+
+ private PnlSearch pnlSearch;
+
+
+ public SearchWindow(MainWindow pf, DocumentModel dm, ElementModel em,XemeliosUser user) throws ToolException {
+ super("Recherche - "+em.getTitre()+" <"+frameCount +">",true,true,true);
+ this.user=user;
+ this.em=em;
+ rank = frameCount;
+ final String titre = "Recherche - "+em.getTitre()+" <"+frameCount++ +">";
+ PnlSearch.DisplayParameters dp = new PnlSearch.DisplayParameters();
+ pnlSearch = new PnlSearch(dm, em.getParent(), em, dp, user, MainWindow.getInstance().getEnvProperties()) {
+
+ @Override
+ public void resizeParent(Rectangle bounds) {
+ MainWindow.getInstance().getDesk().getDesktopManager().beginResizingFrame(this,0);
+ MainWindow.getInstance().getDesk().getDesktopManager().resizeFrame(this,bounds.x,bounds.y,bounds.width,bounds.height);
+ MainWindow.getInstance().getDesk().getDesktopManager().endResizingFrame(this);
+ }
+
+ @Override
+ public String getTitle() {
+ return titre;
+ }
+
+ @Override
+ public void notifyParentStateChanged() {
+ MainWindow.getInstance().innerWindowChanged();
+ System.gc();
+ }
+
+ @Override
+ public void iconify(boolean iconified) {
+ if(iconified)
+ MainWindow.getInstance().getDesk().getDesktopManager().iconifyFrame(SearchWindow.this);
+ else
+ MainWindow.getInstance().getDesk().getDesktopManager().deiconifyFrame(SearchWindow.this);
+ }
+
+ @Override
+ public void setTitle(String newTitle) {
+ SearchWindow.this.setTitle(newTitle);
+ }
+
+ @Override
+ public void redisplayTitle() {
+ SearchWindow.this.setTitle(titre);
+ }
+
+ @Override
+ public void startWaiter() {
+ getGlassPane().setVisible(true);
+ }
+
+ @Override
+ public void stopWaiter() {
+ getGlassPane().setVisible(false);
+ invalidate();
+ repaint();
+ }
+
+ @Override
+ public boolean canExport() {
+ return canExport && !(SearchWindow.this.isIcon());
+ }
+
+ @Override
+ public void actionOnRowPerformed(MouseEvent evt, int row) {
+ if(row>=0 && evt.getClickCount()==2 && evt.getButton()==MouseEvent.BUTTON1) {
+ if(getElementModel().getXslt()==null || getElementModel().getXslt().length()==0) return;
+ try {
+ row=((JXTable)getTable()).convertRowIndexToModel(row);
+ EtatResultTableModel etrm = (EtatResultTableModel)getTable().getModel();
+ DataHandler dh = etrm.getRowAt(row,0);
+ Document doc = dh.getDocument();
+ String docId = dh.getDocumentId();
+ XPath xp = FactoryProvider.getXPathFactory().newXPath();
+// Hashtable<String,Object> parameters = new Hashtable<String,Object>();
+ xp.setNamespaceContext(getDocumentModel().getNamespaces());
+ String idRepository = null;
+ if(getDocumentModel().getReferenceNomenclaturePath()!=null && getDocumentModel().getReferenceNomenclaturePath().getCodePath()!=null) {
+ idRepository = (String)xp.evaluate(getDocumentModel().getReferenceNomenclaturePath().getCodePath().getPath(),doc.getDocumentElement(),XPathConstants.STRING);
+ }
+ if(idRepository!=null && !(idRepository.length()>0)){
+ idRepository=null;
+ }
+
+ Document repository = DataLayerManager.getImplementation().getRepositoryAsDom(getDocumentModel(),getCurrentCollectivite(),idRepository,getUser());
+ File f = null;
+ f = new File(new File(new File(System.getProperty("user.home")),"xemelios/documents-def-ovrrd"),getElementModel().getXslt());
+ if(!f.exists())
+ f = new File(getDocumentModel().getBaseDirectory(),getElementModel().getXslt());
+ InputStream is = new FileInputStream(f);
+// InputStream htmlStream = DematTransform.transform(doc,is,parameters,f.getParentFile().toURI().toURL().toExternalForm());
+ TransformerFactory tFactory = FactoryProvider.getTransformerFactory();
+ URIResolver uriResolver = new CustomURIResolver(tFactory.getURIResolver(), f.getParentFile().toURI().toURL().toExternalForm());
+ tFactory.setURIResolver(uriResolver);
+ Transformer t = tFactory.newTransformer(new StreamSource(is));
+ t.setParameter(HtmlViewer.PARAM_DESTINATION,getElementModel().getParent().useExternalBrowser()?HtmlViewer.VALUE_DESTINATION_EXTERNAL:HtmlViewer.VALUE_DESTINATION_INTERNAL);
+ for(int pos=0;pos<etrm.getHiddens().size();pos++) {
+ HiddenModel hm = etrm.getHiddens().get(pos);
+ if(hm.getName().startsWith("xsl-param:")) {
+ String paramName = hm.getName().substring("xsl-param:".length());
+ Object paramValue = dh.getValueAtColumn(etrm.getListeChamps().size()+pos);
+ if(paramValue!=null)
+ t.setParameter(paramName,paramValue);
+ }
+ }
+ if(repository!=null) {
+// logger.debug("giving repository parameter to XSL");
+ t.setParameter("repository",repository);
+ }
+ t.setParameter("config",Loader.getDocumentsInfos(null).getSmallDOM());
+// XmlUtils.showDomInConsole(Loader.getDocumentsInfos(null).getSmallDOM(), "configuration");
+ t.setParameter("collectivite",getCurrentCollectivite().key);
+ t.setParameter("budget",getCurrentBudget().key);
+ t.setParameter("collectivite-lib",getCurrentCollectivite().libelle);
+ t.setParameter("budget-lib",getCurrentBudget().libelle);
+ t.setParameter("displayedDocId", docId);
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ t.transform(new DOMSource(doc), new StreamResult(baos));
+ MainWindow.getInstance().displayHtmlStream(new ByteArrayInputStream(baos.toByteArray()),getElementModel().getParent(),MainWindow.getInstance().getDesk());
+ } catch(Exception ex) {
+ new DisplayExceptionDlg(SwingUtilities.getWindowAncestor(this),ex);
+ }
+ }
+ }
+ };
+ InternalFrameListener adapter = new InternalFrameAdapter() {
+ @Override
+ public void internalFrameClosing(InternalFrameEvent e) {
+ pnlSearch.clearResources();
+ pnlSearch.notifyParentStateChanged();
+ }
+ @Override
+ public void internalFrameIconified(InternalFrameEvent e) {
+ setTitle(SearchWindow.this.em.getTitre()+" <"+rank+">");
+ pnlSearch.notifyParentStateChanged();
+ }
+ @Override
+ public void internalFrameDeiconified(InternalFrameEvent e) {
+ pnlSearch.redisplayTitle();
+ pnlSearch.notifyParentStateChanged();
+ }
+ @Override
+ public void internalFrameActivated(InternalFrameEvent e) {
+ moveToFront();
+ pnlSearch.notifyParentStateChanged();
+ }
+ };
+ addInternalFrameListener(adapter);
+ setContentPane(pnlSearch);
+ setGlassPane(new InfiniteGlassPane());
+ setIconifiable(true);
+ KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0);
+ getRootPane().registerKeyboardAction(pnlSearch.getActionSearch(),"CANCEL",ks,JComponent.WHEN_IN_FOCUSED_WINDOW);
+ }
+
+ /**
+ * Permet de supprimer tous les critères
+ */
+ public void clearAll() {
+ pnlSearch.clearAll();
+ }
+ /**
+ * Permet d'ajouter un critère
+ * @return
+ */
+ public CriteriaViewer addLine() {
+ return pnlSearch.addLine();
+ }
+ /**
+ * Permet de lancer la recherche
+ */
+ public void search() {
+ pnlSearch.search();
+ }
+ public boolean canExport() {
+ return pnlSearch.canExport();
+ }
+
+
+ @Override
+ public void setVisible(boolean visible) {
+ if(!visible && em!=null) {
+ Iterator<PropertyChangeListener> it = em.getPropertyListeners();
+ if(it!=null) {
+ while(it.hasNext()) {
+ it.next();
+ it.remove();
+ }
+ }
+ }
+ super.setVisible(visible);
+ }
+
+ public void setCollectivite(Pair collectivite) {
+ pnlSearch.setCollectivite(collectivite);
+ }
+ public void setBudget(Pair budget) {
+ pnlSearch.setBudget(budget);
+ }
+
+ public boolean isEtatExportable () {
+ return em.getParent().isExportable();
+ }
+ public XemeliosUser getUser() { return user; }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui;
+
+/**
+ * an interface to receive notifications from various components
+ * @author chm
+ *
+ */
+public interface UpdatableToolbar {
+ public void updateToolbarButtons();
+ public void setBaseUrl(String url);
+}
--- /dev/null
+/*
+ * Copyright
+ * 2008 axYus - www.axyus.com
+ * 2008 L.Meckert - laurent.meckert@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui;
+
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentsModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.Loader;
+import java.io.File;
+import java.util.Hashtable;
+
+import fr.gouv.finances.cp.xemelios.controls.editors.EditorHtmlViewer;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+import fr.gouv.finances.dgfip.xemelios.utils.FileUtils;
+import javax.swing.JFileChooser;
+import javax.swing.JOptionPane;
+import javax.swing.filechooser.FileFilter;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.transform.stream.StreamSource;
+
+/**
+ *
+ * @author lm (servilement copie sur StandaloneController.java)
+ */
+public class ViewXemeliosDocument {
+ private DocumentsModel config = null;
+ private PropertiesExpansion applicationConfiguration;
+
+ public static final transient String USAGE = "ViewXemeliosDocument [<fileToDisplay> [docId]]\n"+
+ "where\n"+
+ "\t<fileToDisplay> is the file to display\n"+
+ "\tdocId is the id of doc-type.\n";
+
+ private void init() throws Exception {
+ // ici, tout est passé dans les propriétés systèmes
+ applicationConfiguration = new PropertiesExpansion(System.getProperties());
+ config = Loader.getDocumentsInfos(applicationConfiguration.getProperty(Constants.SYS_PROP_DOC_DEF_DIR));
+ }
+ public ViewXemeliosDocument() throws Exception {
+ init();
+ JFileChooser jfc = new JFileChooser(System.getProperty("user.home"));
+ jfc.addChoosableFileFilter(new FileFilter() {
+ @Override
+ public boolean accept(File f) {
+ return f.getName().toLowerCase().endsWith(".xml");
+ }
+ @Override
+ public String getDescription() {
+ return "Fichiers XML";
+ }
+ });
+ jfc.addChoosableFileFilter(new FileFilter() {
+ @Override
+ public boolean accept(File f) {
+ return true;
+ }
+ @Override
+ public String getDescription() {
+ return "Tous les fichiers";
+ }
+ });
+ jfc.setMultiSelectionEnabled(false);
+ if(jfc.showOpenDialog(null)==JFileChooser.APPROVE_OPTION) {
+ File f = jfc.getSelectedFile();
+ // on est en mode super-dégradé, par de configuration d'execution
+ AskDocumentType adt = new AskDocumentType(null, f.getName(), config, new PropertiesExpansion());
+ adt.setVisible(true);
+ DocumentModel dm = adt.getDocumentType();
+ openFile(f.getAbsolutePath(),dm.getId());
+ }
+ }
+ public ViewXemeliosDocument(String inFileName) throws Exception {
+ init();
+ AskDocumentType adt = new AskDocumentType(null, inFileName, config, new PropertiesExpansion());
+ adt.setVisible(true);
+ DocumentModel dm = adt.getDocumentType();
+ openFile(inFileName,dm.getId());
+ }
+
+ public ViewXemeliosDocument(String inFileName, String docId) throws Exception {
+ init();
+ openFile(inFileName,docId);
+ }
+ protected void openFile(String inFileName, String docId) throws Exception {
+ DocumentModel docConfig = config.getDocumentById(docId);
+ if(docConfig==null) {
+ JOptionPane.showMessageDialog(null, docId+": configuration non trouvée.","Erreur",JOptionPane.ERROR_MESSAGE);
+ return;
+ }
+ Hashtable<String, File> documents = new Hashtable<String, File>();
+ StringBuffer uri = new StringBuffer();
+ File fileToRead = new File(inFileName);
+ File fichierEnrichi = null;
+
+ if(docConfig.getGlobalImportXsltFile()!=null) {
+ fichierEnrichi = new File(FileUtils.getTempDir(),"_"+fileToRead.getName()+"_");
+ TransformerFactory tFactory = FactoryProvider.getTransformerFactory();
+ Transformer tr = tFactory.newTransformer(new StreamSource(new File(docConfig.getBaseDirectory(),docConfig.getGlobalImportXsltFile())));
+ StreamResult result = new StreamResult(fichierEnrichi);
+ tr.transform(new StreamSource(fileToRead),result);
+ result.getOutputStream().flush(); result.getOutputStream().close();
+ } else {
+ fichierEnrichi = fileToRead;
+ }
+
+ documents.put(docId, fichierEnrichi);
+ uri.append("xemelios:/query?docId="+docId+"&etatId="+docConfig.getDefaultEtatGlobal());
+ EditorHtmlViewer ehv = new EditorHtmlViewer(documents, config, uri.toString(),new LocalUser(), applicationConfiguration);
+ ehv.setLocationRelativeTo(null);
+ ehv.setVisible(true);
+ }
+
+
+ public static void main(String[] args) {
+// String docId = "PES_Aller";
+// String strFile = "/home/chm/DGCP/magnus/PESALR1-21110429400015-011013-20070911122021704.xml";
+ try {
+ if(args.length> 1 && !(args[0].equals("")) && !(args[1].equals("")) ) {
+ new ViewXemeliosDocument(args[0],args[1]);
+ } else if(args.length>=1 && !(args[0].equals(""))) {
+ new ViewXemeliosDocument(args[0]);
+ } else {
+ new ViewXemeliosDocument();
+ }
+ } catch (Throwable t) {
+ t.printStackTrace();
+ System.exit(1);
+ }
+ }
+
+ /**
+ * @TODO : AUTHORISATIONS A GERER CORRECTEMENT
+ */
+ public static class LocalUser implements XemeliosUser {
+
+ @Override
+ public String getId() {
+ return "local";
+ }
+
+ @Override
+ public String getDisplayName() {
+ return getId();
+ }
+
+ @Override
+ public boolean hasRole(String arg0) {
+ return true;
+ }
+
+ @Override
+ public boolean hasDocument(String arg0) {
+ return true;
+ }
+
+ @Override
+ public boolean hasCollectivite(String arg0, DocumentModel dm) {
+ return true;
+ }
+
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui;
+
+import java.awt.Rectangle;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+
+import javax.swing.AbstractAction;
+import javax.swing.Action;
+import javax.swing.Icon;
+import javax.swing.JDesktopPane;
+import javax.swing.JInternalFrame;
+import javax.swing.JMenu;
+import javax.swing.JMenuItem;
+
+import org.apache.log4j.Logger;
+
+import fr.gouv.finances.cp.utils.ui.IhmFactory;
+import fr.gouv.finances.dgfip.xemelios.ui.ImageResources;
+
+/**
+ * Un menu "Fenetre" a la windows
+ * @author chm
+ */
+public class WindowMenu extends JMenu {
+ private static Logger logger = Logger.getLogger(WindowMenu.class);
+ private JMenuItem[] cstMenus=null;
+ private static Icon flagIcon = IhmFactory.getIconFromResource(ImageResources.FLAG_MENU);
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 3257572810372100920L;
+ /**
+ * Le desktop pour lequel on cree le menu
+ */
+ private JDesktopPane desk = null;
+
+ /**
+ *
+ */
+ public WindowMenu(JDesktopPane desk) {
+ super();
+ this.desk = desk;
+ initialize();
+ }
+ /**
+ * @param s
+ */
+ public WindowMenu(String s, JDesktopPane desk) {
+ super(s);
+ this.desk = desk;
+ initialize();
+ }
+ /**
+ * @param a
+ */
+ public WindowMenu(Action a, JDesktopPane desk) {
+ super(a);
+ this.desk = desk;
+ initialize();
+ }
+ /**
+ * @param s
+ * @param b
+ */
+ public WindowMenu(String s, boolean b, JDesktopPane desk) {
+ super(s, b);
+ this.desk = desk;
+ initialize();
+ }
+
+ private void initialize() {
+ cstMenus = new JMenuItem[3];
+ cstMenus[0] = new JMenuItem("Cascade");
+ cstMenus[0].addActionListener(new ActionListener() {
+ public void actionPerformed(ActionEvent evt) {
+ cascade(desk);
+ }
+ });
+ cstMenus[1] = new JMenuItem("Mosaïque");
+ cstMenus[1].addActionListener(new ActionListener() {
+ public void actionPerformed(ActionEvent evt) {
+ tile(desk);
+ }
+ });
+ cstMenus[2] = new JMenuItem("Tout réduire");
+ cstMenus[2].addActionListener(new ActionListener() {
+ public void actionPerformed(ActionEvent evt) {
+// DesktopManager dm = desk.getDesktopManager();
+ for(JInternalFrame frame:desk.getAllFrames()) {
+ try {
+ frame.setIcon(true);
+ } catch(Throwable t) {}
+ }
+ }
+ });
+ }
+ @Override
+ public void menuSelectionChanged(boolean isIncluded) {
+ if(isIncluded) {
+ showWindowMenu();
+ }
+ super.menuSelectionChanged(isIncluded);
+ }
+ private void showWindowMenu() {
+ if(desk==null) {
+ logger.error("desk is null !");
+ return;
+ }
+ JInternalFrame[] frames = desk.getAllFrames();
+ removeAll();
+ reAddMenus(frames);
+ for(JInternalFrame frame:frames) {
+ JMenuItem item = new JMenuItem(new ToFrontAction(frame));
+ if(desk.getSelectedFrame()==frame) {
+ item.setIcon(flagIcon);
+ }
+ add(item);
+ }
+ }
+ private void reAddMenus(JInternalFrame[] frames) {
+ for(JMenuItem it:cstMenus) add(it);
+ if(frames!=null && frames.length>0) addSeparator();
+ }
+ public static void cascade( JDesktopPane desktopPane, int layer ) {
+ JInternalFrame[] frames = desktopPane.getAllFramesInLayer( layer );
+ if ( frames.length == 0) return;
+
+ cascade( frames, desktopPane.getBounds(), 24 );
+ }
+ public static void cascade( JDesktopPane desktopPane ) {
+ JInternalFrame[] frames = desktopPane.getAllFrames();
+ if ( frames.length == 0) return;
+
+ cascade( frames, desktopPane.getBounds(), 24 );
+ }
+ private static void cascade( JInternalFrame[] frames, Rectangle dBounds, int separation ) {
+ int margin = frames.length*separation + separation;
+ int width = dBounds.width - margin;
+ int height = dBounds.height - margin;
+ for ( int i = frames.length-1; i >=0 ; i--) {
+ frames[i].setBounds( dBounds.x + (frames.length-i-1)*separation,
+ dBounds.y + (frames.length-i-1)*separation,
+ width, height );
+ try {
+ frames[i].setIcon(false);
+ } catch(Throwable t) {}
+ frames[i].toFront();
+ if(i==0) {
+ frames[i].getDesktopPane().getDesktopManager().activateFrame(frames[i]);
+ try {
+ frames[i].setSelected(true);
+ } catch(Throwable t) {}
+ }
+ }
+ }
+ public static void tile( JDesktopPane desktopPane, int layer ) {
+ JInternalFrame[] frames = desktopPane.getAllFramesInLayer( layer );
+ if ( frames.length == 0) return;
+
+ tile( frames, desktopPane.getBounds() );
+ }
+ public static void tile( JDesktopPane desktopPane ) {
+ JInternalFrame[] frames = desktopPane.getAllFrames();
+ if ( frames.length == 0) return;
+
+ tile( frames, desktopPane.getBounds() );
+ }
+ private static void tile( JInternalFrame[] frames, Rectangle dBounds ) {
+ int cols = (int)Math.sqrt(frames.length);
+ int rows = (int)(Math.ceil( ((double)frames.length) / cols));
+ int lastRow = frames.length - cols*(rows-1);
+ int width, height;
+
+ if ( lastRow == 0 ) {
+ rows--;
+ height = dBounds.height / rows;
+ }
+ else {
+ height = dBounds.height / rows;
+ if ( lastRow < cols ) {
+ rows--;
+ width = dBounds.width / lastRow;
+ for (int i = 0; i < lastRow; i++ ) {
+ frames[cols*rows+i].setBounds( i*width, rows*height,width, height );
+ try {
+ frames[cols*rows+i].setIcon(false);
+ } catch(Throwable t) {}
+ }
+ }
+ }
+
+ width = dBounds.width/cols;
+ for (int j = 0; j < rows; j++ ) {
+ for (int i = 0; i < cols; i++ ) {
+ frames[i+j*cols].setBounds( i*width, j*height,width, height );
+ try {
+ frames[i+j*cols].setIcon(false);
+ } catch(Throwable t) {}
+ }
+ }
+ }
+
+ public class ToFrontAction extends AbstractAction {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+ private JInternalFrame frame = null;
+ public ToFrontAction(JInternalFrame frame) {
+ super(frame.getTitle());
+ this.frame = frame;
+ }
+ public void actionPerformed(ActionEvent evt) {
+ if(!frame.isSelected()) {
+ frame.getDesktopPane().getDesktopManager().activateFrame(frame);
+ try {
+ frame.setIcon(false);
+ frame.setSelected(true);
+ } catch(Throwable t) {}
+ } else {
+ if(frame.isIcon()) {
+ frame.getDesktopPane().getDesktopManager().activateFrame(frame);
+ try {
+ frame.setIcon(false);
+ frame.setSelected(true);
+ } catch(Throwable t) {}
+ } else {
+ try {
+ frame.setIcon(true);
+ } catch(Throwable t) {}
+ }
+ }
+ }
+ }
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.3" maxVersion="1.3" type="org.netbeans.modules.form.forminfo.JDialogFormInfo">
+ <Properties>
+ <Property name="defaultCloseOperation" type="int" value="2"/>
+ <Property name="title" type="java.lang.String" value="Paramétrage de XéMéLios"/>
+ </Properties>
+ <SyntheticProperties>
+ <SyntheticProperty name="formSizePolicy" type="int" value="1"/>
+ </SyntheticProperties>
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="2"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="1" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="1" attributes="0">
+ <Component id="tabs" alignment="0" pref="567" max="32767" attributes="0"/>
+ <Group type="102" alignment="1" attributes="0">
+ <Component id="pbSave" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="pbClose" min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="1" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="tabs" pref="425" max="32767" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="pbClose" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="pbSave" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Component class="javax.swing.JButton" name="pbClose">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Fermer"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbCloseActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="pbSave">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Enregistrer"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbSaveActionPerformed"/>
+ </Events>
+ </Component>
+ <Container class="javax.swing.JTabbedPane" name="tabs">
+ <Properties>
+ <Property name="tabLayoutPolicy" type="int" value="1"/>
+ </Properties>
+
+ <Layout class="org.netbeans.modules.form.compat2.layouts.support.JTabbedPaneSupportLayout"/>
+ </Container>
+ </SubComponents>
+</Form>
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.admin;
+
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.dgfip.xemelios.auth.impl.std.db.ui.PnlConfigAuthentication;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import fr.gouv.finances.dgfip.xemelios.data.DataConfigurationException;
+import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
+import fr.gouv.finances.dgfip.xemelios.data.impl.pool.PoolManager;
+import java.awt.event.ActionEvent;
+import java.awt.event.KeyEvent;
+import java.sql.Connection;
+import java.util.ArrayList;
+
+import javax.swing.AbstractAction;
+import javax.swing.JComponent;
+import javax.swing.JOptionPane;
+import javax.swing.JRootPane;
+import javax.swing.KeyStroke;
+
+/**
+ *
+ * @author chm
+ */
+public class DlgSystemConfiguration extends javax.swing.JDialog {
+ private AbstractAction escapeAction;
+ ArrayList<ParamSaver> panels;
+
+ /** Creates new form DlgTestProxy */
+ public DlgSystemConfiguration(java.awt.Frame parent, boolean modal) {
+ super(parent, modal);
+ panels = new ArrayList<ParamSaver>();
+ initComponents();
+ PnlProxy pnlProxy = new PnlProxy(MainWindow.getInstance().getEnvProperties());
+ tabs.addTab("Proxy",pnlProxy);
+ panels.add(pnlProxy);
+// PnlExport pnlExport = new PnlExport(MainWindow.getInstance().getEnvProperties());
+// tabs.addTab("Exports",pnlExport);
+// panels.add(pnlExport);
+ PnlUpdate pnlUpdate = new PnlUpdate(MainWindow.getInstance().getEnvProperties());
+ tabs.addTab("Mises à jour", pnlUpdate);
+ panels.add(pnlUpdate);
+ PnlProfils pnlProfils = new PnlProfils(MainWindow.getInstance().getEnvProperties());
+ tabs.add("Abonnements", pnlProfils);
+ panels.add(pnlProfils);
+ if("true".equals(MainWindow.getInstance().getEnvProperties().getProperty(Constants.SYS_PROP_PNL_SYSPROP))) {
+ PnlSystemProperties pnlSysProps = new PnlSystemProperties(MainWindow.getInstance().getEnvProperties());
+ tabs.addTab("Propriétés Systèmes",pnlSysProps);
+ panels.add(pnlSysProps);
+ }
+ Connection con = null;
+ try {
+ con = PoolManager.getInstance().getConnection();
+ if(PnlConfigAuthentication.isLocalComputerServer(con)) {
+ String className = DataLayerManager.getImplementation().getParameterValue("authEngineClassName");
+ final PnlConfigAuthentication pnl = new PnlConfigAuthentication(className);
+ ParamSaver pm = new ParamSaver() {
+ @Override
+ public void saveConfiguration() {
+ if(!pnl.saveData()) {
+ JOptionPane.showMessageDialog(DlgSystemConfiguration.this, "Vous ne pouvez pas choisir un moteur d'authentification\nqui n'est pas installé sur votre serveur.","Configuration impossible",JOptionPane.WARNING_MESSAGE);
+ }
+ }
+ };
+ panels.add(pm);
+ tabs.add("Authentification",pnl);
+ }
+ } catch(DataConfigurationException ex) {
+ // on peut ignorer
+ } finally {
+ if(con!=null) PoolManager.getInstance().releaseConnection(con);
+ }
+ setLocationRelativeTo(getParent());
+ }
+
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ pbClose = new javax.swing.JButton();
+ pbSave = new javax.swing.JButton();
+ tabs = new javax.swing.JTabbedPane();
+
+ setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+ setTitle("Paramétrage de XéMéLios");
+
+ pbClose.setText("Fermer");
+ pbClose.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbCloseActionPerformed(evt);
+ }
+ });
+
+ pbSave.setText("Enregistrer");
+ pbSave.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbSaveActionPerformed(evt);
+ }
+ });
+
+ tabs.setTabLayoutPolicy(javax.swing.JTabbedPane.SCROLL_TAB_LAYOUT);
+
+ org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
+ .addContainerGap()
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
+ .add(org.jdesktop.layout.GroupLayout.LEADING, tabs, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 567, Short.MAX_VALUE)
+ .add(layout.createSequentialGroup()
+ .add(pbSave)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(pbClose)))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
+ .addContainerGap()
+ .add(tabs, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 425, Short.MAX_VALUE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(pbClose)
+ .add(pbSave))
+ .addContainerGap())
+ );
+
+ pack();
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void pbSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbSaveActionPerformed
+ for(ParamSaver ps:panels) {
+ ps.saveConfiguration();
+ }
+ }//GEN-LAST:event_pbSaveActionPerformed
+
+ private void pbCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbCloseActionPerformed
+ setVisible(false);
+ }//GEN-LAST:event_pbCloseActionPerformed
+
+
+ @Override
+ protected JRootPane createRootPane() {
+ KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0);
+ JRootPane rp = new JRootPane();
+ escapeAction = new AbstractAction("Annuler") {
+ private static final long serialVersionUID = 1L;
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ pbCloseActionPerformed(evt);
+ }
+ };
+ rp.registerKeyboardAction(escapeAction,"TOTOTOTO",ks,JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
+ }
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JButton pbClose;
+ private javax.swing.JButton pbSave;
+ private javax.swing.JTabbedPane tabs;
+ // End of variables declaration//GEN-END:variables
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.admin;
+
+/**
+ *
+ * @author chm
+ */
+interface ParamSaver {
+ /**
+ * Called by DlgTestProxy to notify each panel to save configuration
+ */
+ public void saveConfiguration();
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.3" maxVersion="1.5" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="2"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="jScrollPane2" alignment="0" pref="399" max="32767" attributes="0"/>
+ <Group type="102" alignment="0" attributes="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="jLabel1" min="-2" max="-2" attributes="0"/>
+ <Component id="jLabel2" alignment="0" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="jScrollPane1" pref="238" max="32767" attributes="0"/>
+ <Component id="cbxExporter" alignment="0" pref="238" max="32767" attributes="0"/>
+ </Group>
+ </Group>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="1" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="jScrollPane2" min="-2" max="-2" attributes="0"/>
+ <EmptySpace pref="24" max="32767" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="jLabel1" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="cbxExporter" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="jLabel2" min="-2" max="-2" attributes="0"/>
+ <Component id="jScrollPane1" min="-2" pref="105" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace min="-2" pref="79" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Component class="javax.swing.JLabel" name="jLabel1">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Méthode d'export Excel"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JComboBox" name="cbxExporter">
+ <Properties>
+ <Property name="model" type="javax.swing.ComboBoxModel" editor="org.netbeans.modules.form.editors2.ComboBoxModelEditor">
+ <StringArray count="0"/>
+ </Property>
+ </Properties>
+ <Events>
+ <EventHandler event="itemStateChanged" listener="java.awt.event.ItemListener" parameters="java.awt.event.ItemEvent" handler="cbxExporterItemStateChanged"/>
+ </Events>
+ <AuxValues>
+ <AuxValue name="JavaCodeGenerator_CreateCodeCustom" type="java.lang.String" value="new JComboBox(exporters)"/>
+ </AuxValues>
+ </Component>
+ <Component class="javax.swing.JLabel" name="jLabel2">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Description"/>
+ </Properties>
+ </Component>
+ <Container class="javax.swing.JScrollPane" name="jScrollPane1">
+ <AuxValues>
+ <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
+ </AuxValues>
+
+ <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
+ <SubComponents>
+ <Component class="javax.swing.JTextArea" name="dfDesc">
+ <Properties>
+ <Property name="columns" type="int" value="20"/>
+ <Property name="editable" type="boolean" value="false"/>
+ <Property name="rows" type="int" value="5"/>
+ </Properties>
+ </Component>
+ </SubComponents>
+ </Container>
+ <Container class="javax.swing.JScrollPane" name="jScrollPane2">
+ <Properties>
+ <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
+ <Border info="null"/>
+ </Property>
+ </Properties>
+ <AuxValues>
+ <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
+ </AuxValues>
+
+ <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
+ <SubComponents>
+ <Component class="javax.swing.JTextArea" name="jTextArea1">
+ <Properties>
+ <Property name="background" type="java.awt.Color" editor="org.netbeans.beaninfo.editors.ColorEditor">
+ <Color blue="ee" green="ee" id="Panel.background" palette="3" red="ee" type="palette"/>
+ </Property>
+ <Property name="columns" type="int" value="20"/>
+ <Property name="rows" type="int" value="5"/>
+ <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
+ <Border info="null"/>
+ </Property>
+ </Properties>
+ <AuxValues>
+ <AuxValue name="JavaCodeGenerator_CreateCodeCustom" type="java.lang.String" value="new javax.swing.JTextArea(PANEL_DESCRIPTION)"/>
+ </AuxValues>
+ </Component>
+ </SubComponents>
+ </Container>
+ </SubComponents>
+</Form>
--- /dev/null
+/*
+ * Copyright
+ * 2008 axYus - www.axyus.com
+ * 2008 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.admin;
+
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.Properties;
+import javax.swing.JComboBox;
+import org.apache.log4j.Logger;
+
+/**
+ *
+ * @author chm
+ */
+public class PnlExport extends javax.swing.JPanel implements ParamSaver {
+ private static Logger logger = Logger.getLogger(PnlExport.class);
+ private PropertiesExpansion applicationConfiguration;
+ private static String PANEL_DESCRIPTION = "Permet de configurer la façon dont les données sont exportées\npar le menu Fichier / Export, ou par le menu Exports / Executer";
+
+ private static ExporterConfig EXPORT_CSV = new ExporterConfig("fr.gouv.finances.cp.xemelios.export.CsvExporter","Exports CSV","Permet de réaliser des exports au format CSV.");
+ private static ExporterConfig EXPORT_XLS_2000 = new ExporterConfig("fr.gouv.finances.cp.xemelios.export.HtmlTableExporter","Exports Excel 2000/2003/2007","Permet de réaliser des exports de gros volumes pour Excel.\nNécessite qu'Excel 2000 / 2003 / 2007 soit installé sur le poste.");
+ private static ExporterConfig EXPORT_XLS_97 = new ExporterConfig("fr.gouv.finances.cp.xemelios.export.SylkExporter","Exports Excel 97","Permet de réaliser des exports de gros volumes pour Excel.\nNécessite qu'Excel 97 soit installé sur le poste.\nNe convient pas à Excel 97SR1 et 97SR2.");
+ private static ExporterConfig EXPORT_XLS_97SR1 = new ExporterConfig("fr.gouv.finances.cp.xemelios.export.HtmlTableExporterXls97SR1","Exports Excel 97 SR1 / SR2b","Permet de réaliser des exports de gros volumes pour Excel.\nNécessite qu'Excel 97 SR1 ou SR2b soit installé sur le poste.");
+ private static ExporterConfig EXPORT_XLS_JXL = new ExporterConfig("fr.gouv.finances.cp.xemelios.export.JxlExporter","Exports Excel simples","Permet de réaliser des exports pour toutes versions d'Excel,\nmais limités à de petits fichiers.");
+ private static ExporterConfig EXPORT_FULL_XLS = new ExporterConfig("fr.gouv.finances.cp.xemelios.export.FullXlsExporter", "Exports Excel Full", "Exports scindés en plusieurs documents Excel");
+
+ private static ExporterConfig[] exporters = {EXPORT_CSV, EXPORT_XLS_2000, EXPORT_XLS_97, EXPORT_XLS_97SR1, EXPORT_XLS_JXL, EXPORT_FULL_XLS};
+ /** Creates new form PnlExport */
+ public PnlExport(PropertiesExpansion applicationConfiguration) {
+ this.applicationConfiguration = applicationConfiguration;
+ initComponents();
+ initializeData();
+ }
+
+ protected void initializeData() {
+ String exporterClassName = applicationConfiguration.getProperty(Constants.SYS_PROP_XEMELIOS_EXPORTER_CLASS);
+ for(ExporterConfig ec:exporters) {
+ if(ec.getClassName().equals(exporterClassName)) {
+ cbxExporter.setSelectedItem(ec);
+ break;
+ }
+ }
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ jLabel1 = new javax.swing.JLabel();
+ cbxExporter = new JComboBox(exporters);
+ jLabel2 = new javax.swing.JLabel();
+ jScrollPane1 = new javax.swing.JScrollPane();
+ dfDesc = new javax.swing.JTextArea();
+ jScrollPane2 = new javax.swing.JScrollPane();
+ jTextArea1 = new javax.swing.JTextArea(PANEL_DESCRIPTION);
+
+ jLabel1.setText("Méthode d'export Excel");
+
+ cbxExporter.addItemListener(new java.awt.event.ItemListener() {
+ public void itemStateChanged(java.awt.event.ItemEvent evt) {
+ cbxExporterItemStateChanged(evt);
+ }
+ });
+
+ jLabel2.setText("Description");
+
+ dfDesc.setColumns(20);
+ dfDesc.setEditable(false);
+ dfDesc.setRows(5);
+ jScrollPane1.setViewportView(dfDesc);
+
+ jScrollPane2.setBorder(null);
+
+ jTextArea1.setBackground(javax.swing.UIManager.getDefaults().getColor("Panel.background"));
+ jTextArea1.setColumns(20);
+ jTextArea1.setRows(5);
+ jTextArea1.setBorder(null);
+ jScrollPane2.setViewportView(jTextArea1);
+
+ org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
+ this.setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
+ .add(layout.createSequentialGroup()
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(jLabel1)
+ .add(jLabel2))
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 238, Short.MAX_VALUE)
+ .add(cbxExporter, 0, 238, Short.MAX_VALUE))))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
+ .addContainerGap()
+ .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 24, Short.MAX_VALUE)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(jLabel1)
+ .add(cbxExporter, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(jLabel2)
+ .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 105, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
+ .add(79, 79, 79))
+ );
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void cbxExporterItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbxExporterItemStateChanged
+ if(cbxExporter.getSelectedItem()!=null) {
+ dfDesc.setText(((ExporterConfig)cbxExporter.getSelectedItem()).getDescription());
+ }
+ }//GEN-LAST:event_cbxExporterItemStateChanged
+
+ @Override
+ public void saveConfiguration() {
+// PropertiesExpansion props = new PropertiesExpansion(System.getProperties());
+ Properties xemProps = new Properties();
+
+ File xemPropsFile = new File(applicationConfiguration.replace("${xemelios.prg}/root/xemelios.properties"));
+ if(!xemPropsFile.exists()) {
+ String className = ((ExporterConfig)cbxExporter.getSelectedItem()).getClassName();
+ System.setProperty(Constants.SYS_PROP_XEMELIOS_EXPORTER_CLASS, className);
+ } else {
+ try {
+ xemProps.load(new FileInputStream(xemPropsFile));
+ String className = ((ExporterConfig)cbxExporter.getSelectedItem()).getClassName();
+ xemProps.put(Constants.SYS_PROP_XEMELIOS_EXPORTER_CLASS, className);
+ applicationConfiguration.setProperty(Constants.SYS_PROP_XEMELIOS_EXPORTER_CLASS, className);
+ FileOutputStream fos = new FileOutputStream(xemPropsFile);
+ xemProps.store(fos,"");
+ fos.close();
+ } catch(IOException ioEx) {
+ logger.error("while saving exporter configuration: ",ioEx);
+ }
+ }
+ }
+
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JComboBox cbxExporter;
+ private javax.swing.JTextArea dfDesc;
+ private javax.swing.JLabel jLabel1;
+ private javax.swing.JLabel jLabel2;
+ private javax.swing.JScrollPane jScrollPane1;
+ private javax.swing.JScrollPane jScrollPane2;
+ private javax.swing.JTextArea jTextArea1;
+ // End of variables declaration//GEN-END:variables
+
+ private static class ExporterConfig {
+ private String className;
+ private String title;
+ private String description;
+
+ public ExporterConfig(String className, String title, String description) {
+ super();
+ this.className=className;
+ this.title=title;
+ this.description=description;
+ }
+ @Override
+ public String toString() { return title; }
+ public String getClassName() { return className; }
+ public String getTitle() { return title; }
+ public String getDescription() { return description; }
+ }
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.6" maxVersion="1.7" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="1" attributes="0">
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="1" attributes="0">
+ <Component id="jScrollPane1" alignment="0" pref="492" max="32767" attributes="0"/>
+ <Component id="jLabel1" alignment="0" min="-2" max="-2" attributes="0"/>
+ <Group type="102" alignment="0" attributes="0">
+ <Component id="jButtonComposants" min="-2" max="-2" attributes="0"/>
+ <EmptySpace type="separate" max="-2" attributes="0"/>
+ <Component id="jButtonDetail" min="-2" max="-2" attributes="0"/>
+ <EmptySpace pref="295" max="32767" attributes="0"/>
+ <Component id="jButtonEnregistrer" min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="jLabel1" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="jScrollPane1" min="-2" pref="309" max="-2" attributes="0"/>
+ <EmptySpace max="32767" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="jButtonComposants" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="jButtonEnregistrer" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="jButtonDetail" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace min="-2" pref="26" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Component class="javax.swing.JLabel" name="jLabel1">
+ <Properties>
+ <Property name="font" type="java.awt.Font" editor="org.netbeans.modules.form.editors2.FontEditor">
+ <FontInfo relative="true">
+ <Font bold="true" component="jLabel1" property="font" relativeSize="true" size="0"/>
+ </FontInfo>
+ </Property>
+ <Property name="text" type="java.lang.String" value="Liste des profils"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JButton" name="jButtonComposants">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Avancé"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButtonComposantsActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="jButtonEnregistrer">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Enregistrer"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButtonEnregistrerActionPerformed"/>
+ </Events>
+ </Component>
+ <Container class="javax.swing.JScrollPane" name="jScrollPane1">
+ <AuxValues>
+ <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
+ </AuxValues>
+
+ <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
+ <SubComponents>
+ <Component class="org.jdesktop.swingx.JXTable" name="jxTableProfils">
+ <Properties>
+ <Property name="model" type="javax.swing.table.TableModel" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
+ <Connection code="pTableModel" type="code"/>
+ </Property>
+ </Properties>
+ </Component>
+ </SubComponents>
+ </Container>
+ <Component class="javax.swing.JButton" name="jButtonDetail">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Détails"/>
+ <Property name="actionCommand" type="java.lang.String" value="Détail"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButtonDetailActionPerformed"/>
+ </Events>
+ </Component>
+ </SubComponents>
+</Form>
--- /dev/null
+/*
+ * Copyright
+ * 2010 axYus - www.axyus.com
+ * 2010 F.Nhieu - franck.nhieu@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui.admin;
+
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.cp.xemelios.updater.installed.InstalledModel;
+import fr.gouv.finances.cp.xemelios.updater.profils.ProfilModel;
+import fr.gouv.finances.cp.xemelios.updater.profils.ComponentModel;
+import fr.gouv.finances.cp.xemelios.updater.profils.ProfilsParser;
+import fr.gouv.finances.cp.xemelios.updater.profils.ProfilsModel;
+import fr.gouv.finances.cp.xemelios.updater.ui.DlgComposants;
+import fr.gouv.finances.cp.xemelios.updater.ui.DlgProfilDetail;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import fr.gouv.finances.dgfip.xemelios.common.NetAccess;
+import java.awt.Component;
+import java.awt.Font;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import javax.swing.JOptionPane;
+import javax.swing.JTable;
+import javax.swing.ListSelectionModel;
+import javax.swing.event.ListSelectionEvent;
+import javax.swing.event.ListSelectionListener;
+import javax.swing.event.TableModelEvent;
+import javax.swing.event.TableModelListener;
+import javax.swing.table.AbstractTableModel;
+import javax.swing.table.DefaultTableCellRenderer;
+import javax.swing.table.TableColumn;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.log4j.Logger;
+
+/**
+ *
+ * @author franck
+ */
+public class PnlProfils extends javax.swing.JPanel implements ParamSaver {
+
+ private static Logger logger = Logger.getLogger(PnlProfils.class);
+ private PropertiesExpansion applicationProperties;
+ private ProfilsTableModel pTableModel;
+ private ProfilsModel psm;
+ private InstalledModel im;
+ private boolean ProfilsLoaded;
+ /**
+ *
+ */
+ public static final transient int COL_ABONNEMENT = 0;
+ /**
+ *
+ */
+ public static final transient int COL_DESCRIPTION = 1;
+
+ /** Creates new form PnlProfils
+ * @param applicationProperties
+ */
+ public PnlProfils(PropertiesExpansion applicationProperties) {
+ this.applicationProperties = applicationProperties;
+ psm = new ProfilsModel(ProfilsModel.QN);
+ pTableModel = new ProfilsTableModel(psm.getProfils());
+ ProfilsLoaded = false;
+
+ initComponents();
+ DescCellRenderer renderer = new DescCellRenderer(pTableModel);
+ jxTableProfils.setDefaultRenderer(String.class, renderer);
+
+ jButtonEnregistrer.setVisible(false);
+
+ jxTableProfils.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
+ jxTableProfils.setShowGrid(true, false);
+ jxTableProfils.setSortable(false);
+
+ TableColumn col;
+ col = jxTableProfils.getColumnModel().getColumn(COL_ABONNEMENT);
+ col.setPreferredWidth(80);
+ col.setMinWidth(60);
+
+ col = jxTableProfils.getColumnModel().getColumn(COL_DESCRIPTION);
+ col.setPreferredWidth(250);
+
+ jButtonDetail.setEnabled(false);
+
+ jxTableProfils.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
+
+ @Override
+ public void valueChanged(ListSelectionEvent e) {
+ int row = jxTableProfils.getSelectedRow();
+ if (row >= 0 && psm.getProfils().get(row).getComponents().size() > 0) {
+ jButtonDetail.setEnabled(true);
+ } else {
+ jButtonDetail.setEnabled(false);
+ }
+ }
+ });
+ }
+
+ @Override
+ public void setVisible(boolean aFlag) {
+ super.setVisible(aFlag);
+
+ if (ProfilsLoaded) {
+ return;
+ }
+
+ if (aFlag) {
+ try {
+ String urlLocation = applicationProperties.getProperty(Constants.SYS_PROP_MAJ_PROFILS_URL);
+ HttpClient client = NetAccess.getHttpClient(MainWindow.getInstance().getEnvProperties());
+
+ psm = ProfilsModel.loadModel(urlLocation, client);
+ logger.debug("Profils chargés : " + psm.toString());
+ pTableModel = new ProfilsTableModel(psm.getProfils());
+ ProfilsLoaded = true;
+ } catch (Exception ex) {
+ logger.error(ex.toString());
+ JOptionPane.showMessageDialog(this, "Impossible d'accéder à la définition des profils.\nVeuillez vérifier que le paramétrage de l'accès à Internet est correct.", ex.getMessage(), JOptionPane.ERROR_MESSAGE);
+ if (false) {
+ psm = new ProfilsModel(ProfilsModel.QN);
+ pTableModel = new ProfilsTableModel(psm.getProfils());
+ jxTableProfils.setModel(pTableModel);
+ DescCellRenderer renderer = new DescCellRenderer(pTableModel);
+ jxTableProfils.setDefaultRenderer(String.class, renderer);
+ pTableModel.fireTableDataChanged();
+ ProfilsLoaded = false;
+ }
+
+ jButtonComposants.setEnabled(false);
+ jButtonDetail.setEnabled(false);
+ jButtonEnregistrer.setEnabled(false);
+
+ return; // inutile de charger les abonnements courant de l'utilisateur
+ }
+
+ try {
+ im = InstalledModel.readFromFile(applicationProperties.getProperty(Constants.SYS_PROP_INSTALLED_FILENAME));
+ im.setFileLocation(applicationProperties.getProperty(Constants.SYS_PROP_INSTALLED_FILENAME));
+ if (im != null) {
+ logger.debug("Installed:nbre Component=" + im.getComponents().size());
+ for (ComponentModel cm : im.getComponents()) {
+ logger.debug("c uri=" + cm.getUri() + " / desc=" + cm.getDescription());
+ }
+ logger.debug("Installed:nbre Profil=" + im.getProfils().size());
+ for (ProfilModel pm : im.getProfils()) {
+ logger.debug("p id=" + pm.getId() + " / desc=" + pm.getDescription());
+ }
+
+ // inscription des profils requis, enregistrement.
+ boolean bTouched = false;
+ for (ProfilModel pm : psm.getProfils()) {
+ if (pm.isRequired()) {
+ if (im.getProfilIdx(pm.getId()) == InstalledModel.NOT_FOUND) {
+ ProfilModel npm = new ProfilModel(pm.getId(), pm.getDescription());
+ im.getProfils().add(npm);
+ bTouched = true;
+ }
+ }
+ }
+ if (bTouched) {
+ im.setComponents(createComponentsList());
+ }
+ }
+ } catch (Exception ex) {
+ logger.error(ex);
+ JOptionPane.showMessageDialog(this, "Impossible de lire le fichier des abonnements.", ex.getMessage(), JOptionPane.ERROR_MESSAGE);
+ }
+
+ /*
+ * A ce stade, tout s'est bien passé, on rafraichit le JTable
+ */
+ jButtonDetail.setEnabled(false);
+ jxTableProfils.setModel(pTableModel);
+ DescCellRenderer renderer = new DescCellRenderer(pTableModel);
+ jxTableProfils.setDefaultRenderer(String.class, renderer);
+ pTableModel.fireTableDataChanged();
+ }
+ }
+
+ @Override
+ public void saveConfiguration() {
+ jButtonEnregistrerActionPerformed(null);
+ }
+
+ private class ProfilsTableModel extends AbstractTableModel implements TableModelListener {
+
+ ArrayList<ProfilModel> getProfils() {
+ return profils;
+ }
+ private ArrayList<ProfilModel> profils;
+
+ @Override
+ public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
+ //super.setValueAt(aValue, rowIndex, columnIndex);
+ //logger.debug("rowIndex=" + rowIndex + "/columnIndex=" + columnIndex + "/aValue=" + aValue.toString());
+ switch (columnIndex) {
+ case COL_ABONNEMENT:
+ ProfilModel pm = profils.get(rowIndex);
+ int idxFound = im.getProfilIdx(pm.getId());
+ if (idxFound != InstalledModel.NOT_FOUND) { // profil trouvé
+ if (aValue.equals(false)) { // case doit être décochée
+ im.getProfils().remove(idxFound); // on supprime le profil des profils installés
+ }
+ } else { // profil non trouvé
+ if (aValue.equals(true)) { // case doit être cochée
+ ProfilModel npm = new ProfilModel(pm.getId(), pm.getDescription());
+ im.getProfils().add(npm); // on ajoute le profil à la liste des profils installés
+ }
+ }
+ for (ProfilModel pml : im.getProfils()) {
+ logger.debug("p id=" + pml.getId() + " / desc=" + pml.getDescription());
+ }
+ break;
+ default:
+ break;
+ }
+ }
+
+ @Override
+ public void fireTableCellUpdated(int row, int column) {
+ super.fireTableCellUpdated(row, column);
+ }
+
+ public ProfilsTableModel(ArrayList<ProfilModel> profils) {
+ this.profils = profils;
+ }
+
+ @Override
+ public int getRowCount() {
+ return profils.size();
+ }
+
+ @Override
+ public int getColumnCount() {
+ return 2;
+ }
+
+ @Override
+ public Object getValueAt(int rowIndex, int columnIndex) {
+ ProfilModel pm = profils.get(rowIndex);
+ switch (columnIndex) {
+ case COL_ABONNEMENT:
+ if (pm.isRequired()) {
+ // TODO faire comme les autres pm différents de isrequired
+ // Profil requis, on regarde s'il est dans la liste des abonnements
+ // Si présent on ne fait rien, sinon on l'ajoute aux profils installés
+ return true; // required, on retourne true direct si profils requis
+ }
+ if (im == null) {
+ return false; // pas d'entrée profil dans installed.xml
+ } else {
+ for (ProfilModel ipm : im.getProfils()) {
+ if (pm.getId().equals(ipm.getId())) {
+ // ce profil est installé
+ return true;
+ }
+ }
+ }
+ return false;
+ case COL_DESCRIPTION:
+ return pm.getDescription();
+ default:
+ return "unknow columnIndex";
+ }
+ }
+
+ @Override
+ public boolean isCellEditable(int rowIndex, int columnIndex) {
+ switch (columnIndex) {
+ case COL_ABONNEMENT:
+ // profil obligatoire, donc la selection n'est pas modifiable
+ if (profils.get(rowIndex).isRequired()) {
+ return false;
+ } else {
+ return true;
+ }
+ case COL_DESCRIPTION:
+ return false;
+ default:
+ return false;
+ }
+ }
+
+ @Override
+ public Class<?> getColumnClass(int columnIndex) {
+ switch (columnIndex) {
+ case COL_ABONNEMENT:
+ return Boolean.class;
+ case COL_DESCRIPTION:
+ return String.class;
+ default:
+ return super.getColumnClass(columnIndex);
+ }
+ }
+
+ @Override
+ public String getColumnName(int column) {
+ switch (column) {
+ case COL_ABONNEMENT:
+ return "abonnement";
+ case COL_DESCRIPTION:
+ return "description";
+ default:
+ return "unknow column";
+ }
+ }
+
+ @Override
+ public void tableChanged(TableModelEvent e) {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+ }
+
+ /**
+ * Renvoie la liste des profils disponibles.
+ * Renvoie toujours quelquechose de non null, meme si la liste des profils n'est pas disponible
+ * @return
+ */
+ private ProfilsModel loadProfils() {
+ logger.debug("xemelios.profils.source=" + applicationProperties.getProperty(Constants.SYS_PROP_MAJ_PROFILS_URL));
+ try {
+ String urlLocation = applicationProperties.getProperty(Constants.SYS_PROP_MAJ_PROFILS_URL);
+ HttpClient client = NetAccess.getHttpClient(MainWindow.getInstance().getEnvProperties());
+ GetMethod meth = new GetMethod(urlLocation);
+ meth.addRequestHeader("Pragma", "no-cache");
+
+ int httpRet = client.executeMethod(meth);
+ if (httpRet > 300) {
+ throw new Exception(meth.getStatusText());
+ }
+ InputStream is = meth.getResponseBodyAsStream();
+ ProfilsParser pp = new ProfilsParser();
+ pp.parse(is);
+ is.close();
+ return (ProfilsModel) pp.getMarshallable();
+ } catch (Exception ex) {
+ logger.warn("in loadProfils()", ex);
+ return new ProfilsModel(ProfilsModel.QN);
+ }
+ }
+
+ private ArrayList<ComponentModel> createComponentsList() {
+ // Création de la liste des composants actifs selon les composants "editable" et les profils
+ ArrayList<ComponentModel> nic = new ArrayList<ComponentModel>();
+ // Trt des composants "editable"
+ for (ComponentModel ic : im.getComponents()) {
+ if (ic.isEditable()) {
+ logger.debug("ajout du composant editable " + ic.getUri() + "/" + ic.getDescription());
+ nic.add(ic);
+ }
+ }
+ // Trt des composants selon les profils "actifs"
+ for (ProfilModel ip : im.getProfils()) {
+ for (ProfilModel p : psm.getProfils()) { // On scan les profils disponibles
+ if (p.getId().equals(ip.getId())) { // Profil trouvé dans les profils actifs, on ajoute tout les composants du profil dispo
+ for (ComponentModel c : p.getComponents()) {
+ boolean bFound = false;
+ for (ComponentModel cnic : nic) { // On test si le composant a déjà été ajouté pour éviter les redondances
+ if (cnic.getUri().equals(c.getUri())) {
+ bFound = true;
+ logger.debug("composant " + c.getUri() + "/" + c.getDescription() + " déja ajouté");
+ break;
+ }
+ }
+ if (!bFound) {
+ // On cherche si le composant a déjà été installé, auquel cas
+ // on prend le CM correspondant plutot que le CM du profil qui ne
+ // contient pas la version
+ int idx = im.getComponentIdx(c.getUri());
+ if(idx != InstalledModel.NOT_FOUND) {
+ c = im.getComponents().get(idx);
+ }
+ logger.debug("ajout du composant " + c.getUri() + "/" + c.getDescription() + "/" + c.getVersion());
+ nic.add(c);
+ }
+ }
+ }
+ }
+ }
+ return nic;
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ @SuppressWarnings("unchecked")
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ jLabel1 = new javax.swing.JLabel();
+ jButtonComposants = new javax.swing.JButton();
+ jButtonEnregistrer = new javax.swing.JButton();
+ jScrollPane1 = new javax.swing.JScrollPane();
+ jxTableProfils = new org.jdesktop.swingx.JXTable();
+ jButtonDetail = new javax.swing.JButton();
+
+ jLabel1.setFont(jLabel1.getFont().deriveFont(jLabel1.getFont().getStyle() | java.awt.Font.BOLD));
+ jLabel1.setText("Liste des profils");
+
+ jButtonComposants.setText("Avancé");
+ jButtonComposants.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ jButtonComposantsActionPerformed(evt);
+ }
+ });
+
+ jButtonEnregistrer.setText("Enregistrer");
+ jButtonEnregistrer.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ jButtonEnregistrerActionPerformed(evt);
+ }
+ });
+
+ jxTableProfils.setModel(pTableModel);
+ jScrollPane1.setViewportView(jxTableProfils);
+
+ jButtonDetail.setText("Détails");
+ jButtonDetail.setActionCommand("Détail");
+ jButtonDetail.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ jButtonDetailActionPerformed(evt);
+ }
+ });
+
+ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
+ this.setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
+ .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 452, Short.MAX_VALUE)
+ .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
+ .addComponent(jButtonComposants)
+ .addGap(18, 18, 18)
+ .addComponent(jButtonDetail)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 215, Short.MAX_VALUE)
+ .addComponent(jButtonEnregistrer)))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(jLabel1)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 309, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(jButtonComposants)
+ .addComponent(jButtonEnregistrer)
+ .addComponent(jButtonDetail))
+ .addGap(26, 26, 26))
+ );
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void jButtonComposantsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonComposantsActionPerformed
+ // TODO add your handling code here:
+ DlgComposants dlgComposants = new DlgComposants(MainWindow.getInstance(), true);
+ dlgComposants.setVisible(true);
+ }//GEN-LAST:event_jButtonComposantsActionPerformed
+
+ private void jButtonEnregistrerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEnregistrerActionPerformed
+ // TODO add your handling code here:
+ if(!ProfilsLoaded) return;
+ im.setComponents(createComponentsList());
+ for (ProfilModel pm : im.getProfils()) {
+ pm.setDontWriteOptionalAttributes(true);
+ }
+ try {
+ Charset cs = Charset.forName("ISO-8859-1");
+ File fo = new File(applicationProperties.getProperty(Constants.SYS_PROP_INSTALLED_FILENAME));
+ im.outputToFile(fo, cs);
+ } catch (IOException ex) {
+ logger.error(ex);
+ }
+ setVisible(false);
+
+ }//GEN-LAST:event_jButtonEnregistrerActionPerformed
+
+ private void jButtonDetailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDetailActionPerformed
+ // TODO add your handling code here:
+
+
+ logger.debug("Selected Row=" + jxTableProfils.getSelectedRow());
+ ProfilModel pm = psm.getProfils().get(jxTableProfils.getSelectedRow());
+ logger.debug("profil=" + pm.getDescription() + "/nbComposants=" + pm.getComponents().size());
+
+ DlgProfilDetail nd = new DlgProfilDetail(MainWindow.getInstance(), psm.getProfils().get(jxTableProfils.getSelectedRow()));
+ nd.setTitle("Détail du profil");
+ nd.setLocationRelativeTo(MainWindow.getInstance());
+ nd.setVisible(true);
+
+ }//GEN-LAST:event_jButtonDetailActionPerformed
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JButton jButtonComposants;
+ private javax.swing.JButton jButtonDetail;
+ private javax.swing.JButton jButtonEnregistrer;
+ private javax.swing.JLabel jLabel1;
+ private javax.swing.JScrollPane jScrollPane1;
+ private org.jdesktop.swingx.JXTable jxTableProfils;
+ // End of variables declaration//GEN-END:variables
+
+ private class DescCellRenderer extends DefaultTableCellRenderer {
+
+ private ProfilsTableModel model;
+
+ public DescCellRenderer(ProfilsTableModel model) {
+ super();
+ this.model = model;
+ }
+
+ @Override
+ public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
+ Component parentComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
+ Component renderer = parentComponent;
+ if (column == 1) {
+ ProfilModel pm = model.getProfils().get(row);
+ if (pm.isRequired()) {
+ Font oldFont = renderer.getFont();
+ Font newFont = oldFont.deriveFont(Font.ITALIC | Font.BOLD); // oldFont.getStyle() |
+ renderer.setFont(newFont);
+ }
+
+ }
+ return renderer;
+ }
+ }
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.3" maxVersion="1.3" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="2"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="1" attributes="0">
+ <Group type="103" groupAlignment="1" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace min="12" pref="12" max="12" attributes="0"/>
+ <Component id="pbTest" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <Group type="102" alignment="1" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="1" attributes="0">
+ <Group type="102" alignment="1" attributes="0">
+ <EmptySpace min="-2" pref="17" max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="lblUser" alignment="0" min="-2" max="-2" attributes="0"/>
+ <Component id="lblPassword" alignment="0" min="-2" max="-2" attributes="0"/>
+ <Component id="lblDomain" alignment="0" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace min="-2" pref="12" max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="dfProxyUser" pref="290" max="32767" attributes="0"/>
+ <Component id="dfProxyPassword" alignment="0" pref="290" max="32767" attributes="0"/>
+ <Component id="dfDomainName" alignment="0" pref="290" max="32767" attributes="0"/>
+ </Group>
+ </Group>
+ <Component id="chkAuthenticationRequired" alignment="0" min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ <Group type="102" alignment="0" attributes="0">
+ <Group type="103" groupAlignment="1" attributes="0">
+ <Group type="102" alignment="0" attributes="1">
+ <EmptySpace min="-2" pref="29" max="-2" attributes="0"/>
+ <Component id="lblServer" min="-2" max="-2" attributes="0"/>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Component id="dfProxyServer" pref="265" max="32767" attributes="0"/>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Component id="lblPort" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="chkUseProxy" min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Component id="dfProxyPort" min="-2" pref="40" max="-2" attributes="0"/>
+ <EmptySpace min="1" pref="1" max="1" attributes="0"/>
+ </Group>
+ </Group>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="chkUseProxy" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="lblServer" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="dfProxyServer" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="lblPort" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="dfProxyPort" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace min="-2" pref="16" max="-2" attributes="0"/>
+ <Component id="chkAuthenticationRequired" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="lblUser" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="dfProxyUser" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="lblPassword" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="dfProxyPassword" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="lblDomain" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="dfDomainName" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace pref="19" max="32767" attributes="0"/>
+ <Component id="pbTest" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Component class="javax.swing.JCheckBox" name="chkAuthenticationRequired">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Mon serveur proxy requiert une authentification"/>
+ <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
+ <Border info="org.netbeans.modules.form.compat2.border.EmptyBorderInfo">
+ <EmptyBorder bottom="0" left="0" right="0" top="0"/>
+ </Border>
+ </Property>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="chkAuthenticationRequiredActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JCheckBox" name="chkUseProxy">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="J'utilise un serveur proxy pour me connecter à internet"/>
+ <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
+ <Border info="org.netbeans.modules.form.compat2.border.EmptyBorderInfo">
+ <EmptyBorder bottom="0" left="0" right="0" top="0"/>
+ </Border>
+ </Property>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="chkUseProxyActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="pbTest">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Tester"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbTestActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JLabel" name="lblServer">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Serveur"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JTextField" name="dfProxyServer">
+ </Component>
+ <Component class="javax.swing.JLabel" name="lblPort">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Port"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JTextField" name="dfProxyPort">
+ </Component>
+ <Component class="javax.swing.JLabel" name="lblUser">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Utilisateur"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JTextField" name="dfProxyUser">
+ </Component>
+ <Component class="javax.swing.JLabel" name="lblPassword">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Mot de passe"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JPasswordField" name="dfProxyPassword">
+ </Component>
+ <Component class="javax.swing.JLabel" name="lblDomain">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Domaine Windows"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JTextField" name="dfDomainName">
+ </Component>
+ </SubComponents>
+</Form>
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.admin;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Properties;
+
+import javax.swing.JOptionPane;
+
+import org.apache.commons.httpclient.HostConfiguration;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpMethod;
+import org.apache.commons.httpclient.UsernamePasswordCredentials;
+import org.apache.commons.httpclient.auth.AuthScope;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.log4j.Logger;
+
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import fr.gouv.finances.dgfip.xemelios.common.Scramble;
+import java.net.InetAddress;
+import org.apache.commons.httpclient.Credentials;
+import org.apache.commons.httpclient.NTCredentials;
+
+/**
+ *
+ * @author chm
+ */
+public class PnlProxy extends javax.swing.JPanel implements ParamSaver {
+ private static final String URL_TO_REACH = "http://www.xemelios.org/updates33/update.xml";
+ private static final Logger logger = Logger.getLogger(PnlProxy.class);
+ private PropertiesExpansion applicationConfiguration;
+
+ /** Creates new form PnlProxy */
+ public PnlProxy(PropertiesExpansion applicationConfiguration) {
+ this.applicationConfiguration = applicationConfiguration;
+ initComponents();
+ initValues();
+ }
+ private void initValues() {
+ String proxyServer = applicationConfiguration.getProperty(Constants.SYS_PROP_PROXY_SERVER);
+ String proxyPort = applicationConfiguration.getProperty(Constants.SYS_PROP_PROXY_PORT);
+ String proxyUser = applicationConfiguration.getProperty(Constants.SYS_PROP_PROXY_USER);
+ String proxyPassword = applicationConfiguration.getProperty(Constants.SYS_PROP_PROXY_PASSWD);
+ String proxyDomain = applicationConfiguration.getProperty(Constants.SYS_PROP_PROXY_DOMAIN);
+ setValues(proxyServer,proxyPort,proxyUser,proxyPassword,proxyDomain);
+ }
+ private void setValues(String server, String port, String user, String password, String proxyDomain) {
+ if(server!=null) {
+ dfProxyServer.setText(server);
+ chkUseProxy.setSelected(true);
+ } else {
+ dfProxyServer.setText("");
+ chkUseProxy.setSelected(false);
+ }
+ enableProxyControls(chkUseProxy.isSelected());
+ dfProxyPort.setText(port!=null?port:"");
+ if(user!=null) {
+ dfProxyUser.setText(user);
+ chkAuthenticationRequired.setSelected(true);
+ } else {
+ dfProxyUser.setText("");
+ chkAuthenticationRequired.setSelected(false);
+ }
+ enableAuthenticationControls(chkAuthenticationRequired.isSelected());
+ dfProxyPassword.setText(password!=null?Scramble.unScramblePassword(password):"");
+ dfDomainName.setText(proxyDomain!=null?proxyDomain:"");
+ }
+ private void runTest() {
+ String proxyHost = null;
+ String proxyPort = null;
+ String proxyUser = null;
+ String proxyPasswd = null;
+ String domainName = null;
+ int intProxyPort = 0;
+
+ if(dfProxyServer.getText()!=null && dfProxyServer.getText().length()>0) proxyHost = dfProxyServer.getText();
+ if(dfProxyPort.getText()!=null && dfProxyPort.getText().length()>0) proxyPort = dfProxyPort.getText();
+ if(dfProxyUser.getText()!=null && dfProxyUser.getText().length()>0) proxyUser = dfProxyUser.getText();
+ if(dfProxyPassword.getPassword().length>0) proxyPasswd = new String(dfProxyPassword.getPassword());
+ if(proxyPort!=null) {
+ try {
+ intProxyPort = Integer.parseInt(proxyPort);
+ } catch(NumberFormatException nfEx) {
+ JOptionPane.showMessageDialog(this,proxyPort+" n'est pas un numéro de port valide.","ERREUR",JOptionPane.ERROR_MESSAGE);
+ return;
+ }
+ }
+ if(dfDomainName.getText()!=null && dfDomainName.getText().length()>0) domainName = dfDomainName.getText();
+ URL url = null;
+ try {
+ url = new URL(URL_TO_REACH);
+ } catch(MalformedURLException muEx) {
+ JOptionPane.showMessageDialog(this,"URL not valid : "+URL_TO_REACH,"ERROR",JOptionPane.ERROR_MESSAGE);
+ return;
+ }
+
+// METHOD WITH APACHE COMMONS-HTTPCLIENT
+ HttpClient client = new HttpClient();
+ HostConfiguration hc = new HostConfiguration();
+ if(proxyHost!=null) {
+ hc.setProxy(proxyHost,intProxyPort);
+ client.setHostConfiguration(hc);
+ }
+ if(proxyUser!=null) {
+ Credentials creds = null;
+ if(domainName!=null && domainName.length()>0) {
+ String hostName = "127.0.0.1";
+ try {
+ InetAddress ip = InetAddress.getByName("127.0.0.1");
+ hostName = ip.getHostName();
+ } catch(Exception ex) {
+ logger.error("",ex);
+ }
+ creds = new NTCredentials(proxyUser, proxyPasswd, hostName, domainName);
+ } else {
+ creds = new UsernamePasswordCredentials(proxyUser, proxyPasswd);
+ }
+ client.getState().setProxyCredentials(AuthScope.ANY, creds);
+ }
+ HttpMethod meth = new GetMethod(URL_TO_REACH);
+ int ret = 0;
+ try {
+ ret = client.executeMethod(meth);
+ if(ret>300) {
+ // an error occured
+ JOptionPane.showMessageDialog(this," "+ret+" : "+meth.getStatusText(),"ERREUR",JOptionPane.ERROR_MESSAGE);
+ return;
+ } else {
+ String resp = meth.getResponseBodyAsString();
+ JOptionPane.showMessageDialog(this,"Connexion réussie !","Ok, ça marche...",JOptionPane.INFORMATION_MESSAGE);
+ }
+ } catch(Throwable t) {
+ JOptionPane.showMessageDialog(this,t.getMessage(),t.getClass().getName(),JOptionPane.ERROR_MESSAGE);
+ }
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ chkAuthenticationRequired = new javax.swing.JCheckBox();
+ chkUseProxy = new javax.swing.JCheckBox();
+ pbTest = new javax.swing.JButton();
+ lblServer = new javax.swing.JLabel();
+ dfProxyServer = new javax.swing.JTextField();
+ lblPort = new javax.swing.JLabel();
+ dfProxyPort = new javax.swing.JTextField();
+ lblUser = new javax.swing.JLabel();
+ dfProxyUser = new javax.swing.JTextField();
+ lblPassword = new javax.swing.JLabel();
+ dfProxyPassword = new javax.swing.JPasswordField();
+ lblDomain = new javax.swing.JLabel();
+ dfDomainName = new javax.swing.JTextField();
+
+ chkAuthenticationRequired.setText("Mon serveur proxy requiert une authentification");
+ chkAuthenticationRequired.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
+ chkAuthenticationRequired.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ chkAuthenticationRequiredActionPerformed(evt);
+ }
+ });
+
+ chkUseProxy.setText("J'utilise un serveur proxy pour me connecter à internet");
+ chkUseProxy.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
+ chkUseProxy.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ chkUseProxyActionPerformed(evt);
+ }
+ });
+
+ pbTest.setText("Tester");
+ pbTest.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbTestActionPerformed(evt);
+ }
+ });
+
+ lblServer.setText("Serveur");
+
+ lblPort.setText("Port");
+
+ lblUser.setText("Utilisateur");
+
+ lblPassword.setText("Mot de passe");
+
+ lblDomain.setText("Domaine Windows");
+
+ org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
+ this.setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
+ .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
+ .add(12, 12, 12)
+ .add(pbTest))
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
+ .add(layout.createSequentialGroup()
+ .add(17, 17, 17)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(lblUser)
+ .add(lblPassword)
+ .add(lblDomain))
+ .add(12, 12, 12)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(dfProxyUser, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 290, Short.MAX_VALUE)
+ .add(dfProxyPassword, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 290, Short.MAX_VALUE)
+ .add(dfDomainName, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 290, Short.MAX_VALUE)))
+ .add(org.jdesktop.layout.GroupLayout.LEADING, chkAuthenticationRequired)))
+ .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
+ .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
+ .add(29, 29, 29)
+ .add(lblServer)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(dfProxyServer, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 265, Short.MAX_VALUE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(lblPort))
+ .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
+ .addContainerGap()
+ .add(chkUseProxy)))
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(dfProxyPort, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 40, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .add(1, 1, 1)))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(chkUseProxy)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(lblServer)
+ .add(dfProxyServer, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .add(lblPort)
+ .add(dfProxyPort, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
+ .add(16, 16, 16)
+ .add(chkAuthenticationRequired)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(lblUser)
+ .add(dfProxyUser, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(lblPassword)
+ .add(dfProxyPassword, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(lblDomain)
+ .add(dfDomainName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 19, Short.MAX_VALUE)
+ .add(pbTest)
+ .addContainerGap())
+ );
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void pbTestActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbTestActionPerformed
+ runTest();
+ }//GEN-LAST:event_pbTestActionPerformed
+
+ private void chkUseProxyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkUseProxyActionPerformed
+ boolean selected = chkUseProxy.isSelected();
+ enableProxyControls(selected);
+ }//GEN-LAST:event_chkUseProxyActionPerformed
+
+ private void chkAuthenticationRequiredActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkAuthenticationRequiredActionPerformed
+ boolean selected = chkAuthenticationRequired.isSelected();
+ enableAuthenticationControls(selected);
+ }//GEN-LAST:event_chkAuthenticationRequiredActionPerformed
+
+ private void enableProxyControls(boolean state) {
+ lblServer.setEnabled(state);
+ dfProxyServer.setEnabled(state);
+ lblPort.setEnabled(state);
+ dfProxyPort.setEnabled(state);
+ chkAuthenticationRequired.setEnabled(state);
+ if(!state) {
+ dfProxyServer.setText("");
+ dfProxyPort.setText("");
+ }
+ if(state) enableAuthenticationControls(chkAuthenticationRequired.isSelected());
+ else enableAuthenticationControls(false);
+ }
+ private void enableAuthenticationControls(boolean state) {
+ lblUser.setEnabled(state);
+ dfProxyUser.setEnabled(state);
+ lblPassword.setEnabled(state);
+ dfProxyPassword.setEnabled(state);
+ lblDomain.setEnabled(state);
+ dfDomainName.setEnabled(state);
+ if(!state) {
+ dfProxyUser.setText("");
+ dfProxyPassword.setText("");
+ dfDomainName.setText("");
+ }
+ }
+
+ @Override
+ public void saveConfiguration() {
+ // initialize a properties expansion from system properties
+// PropertiesExpansion props = new PropertiesExpansion(System.getProperties());
+ Properties xemProps = new Properties();
+
+ File xemPropsFile = new File(applicationConfiguration.replace("${xemelios.prg}/root/xemelios.properties"));
+logger.debug("xemPropsFile is "+xemPropsFile.getPath());
+ if(!xemPropsFile.exists()) {
+ } else {
+ try {
+ xemProps.load(new FileInputStream(xemPropsFile));
+
+ String proxyHost = null;
+ String proxyPort = null;
+ String proxyUser = null;
+ String proxyPasswd = null;
+ String domainName = null;
+
+ if(dfProxyServer.getText()!=null && dfProxyServer.getText().length()>0) proxyHost = dfProxyServer.getText();
+ if(dfProxyPort.getText()!=null && dfProxyPort.getText().length()>0) proxyPort = dfProxyPort.getText();
+ if(dfProxyUser.getText()!=null && dfProxyUser.getText().length()>0) proxyUser = dfProxyUser.getText();
+ if(dfProxyPassword.getPassword().length>0) proxyPasswd = new String(dfProxyPassword.getPassword());
+ if(dfDomainName.getText()!=null && dfDomainName.getText().length()>0) domainName = dfDomainName.getText();
+
+ if(proxyHost!=null) {
+ xemProps.put(Constants.SYS_PROP_PROXY_SERVER,proxyHost);
+ xemProps.put(Constants.SYS_PROP_PROXY_PORT,proxyPort);
+ applicationConfiguration.setProperty(Constants.SYS_PROP_PROXY_SERVER,proxyHost);
+ applicationConfiguration.setProperty(Constants.SYS_PROP_PROXY_PORT,proxyPort);
+ if(proxyUser!=null) {
+ xemProps.put(Constants.SYS_PROP_PROXY_USER,proxyUser);
+ xemProps.put(Constants.SYS_PROP_PROXY_PASSWD,Scramble.scramblePassword(proxyPasswd));
+ applicationConfiguration.setProperty(Constants.SYS_PROP_PROXY_USER,proxyUser);
+ applicationConfiguration.setProperty(Constants.SYS_PROP_PROXY_PASSWD,Scramble.scramblePassword(proxyPasswd));
+ } else {
+ xemProps.remove(Constants.SYS_PROP_PROXY_USER);
+ xemProps.remove(Constants.SYS_PROP_PROXY_PASSWD);
+ applicationConfiguration.remove(Constants.SYS_PROP_PROXY_USER);
+ applicationConfiguration.remove(Constants.SYS_PROP_PROXY_PASSWD);
+ }
+ if(domainName!=null) {
+ xemProps.put(Constants.SYS_PROP_PROXY_DOMAIN,domainName);
+ applicationConfiguration.setProperty(Constants.SYS_PROP_PROXY_DOMAIN,domainName);
+ } else {
+ xemProps.remove(Constants.SYS_PROP_PROXY_DOMAIN);
+ applicationConfiguration.remove(Constants.SYS_PROP_PROXY_DOMAIN);
+ }
+ } else {
+ xemProps.remove(Constants.SYS_PROP_PROXY_SERVER);
+ xemProps.remove(Constants.SYS_PROP_PROXY_PORT);
+ xemProps.remove(Constants.SYS_PROP_PROXY_USER);
+ xemProps.remove(Constants.SYS_PROP_PROXY_PASSWD);
+ applicationConfiguration.remove(Constants.SYS_PROP_PROXY_SERVER);
+ applicationConfiguration.remove(Constants.SYS_PROP_PROXY_PORT);
+ applicationConfiguration.remove(Constants.SYS_PROP_PROXY_USER);
+ applicationConfiguration.remove(Constants.SYS_PROP_PROXY_PASSWD);
+ }
+ FileOutputStream fos = new FileOutputStream(xemPropsFile);
+ xemProps.store(fos,"");
+ fos.close();
+ } catch(IOException ioEx) {
+ logger.error("while saving proxy configuration: ",ioEx);
+ }
+ }
+
+ }
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JCheckBox chkAuthenticationRequired;
+ private javax.swing.JCheckBox chkUseProxy;
+ private javax.swing.JTextField dfDomainName;
+ private javax.swing.JPasswordField dfProxyPassword;
+ private javax.swing.JTextField dfProxyPort;
+ private javax.swing.JTextField dfProxyServer;
+ private javax.swing.JTextField dfProxyUser;
+ private javax.swing.JLabel lblDomain;
+ private javax.swing.JLabel lblPassword;
+ private javax.swing.JLabel lblPort;
+ private javax.swing.JLabel lblServer;
+ private javax.swing.JLabel lblUser;
+ private javax.swing.JButton pbTest;
+ // End of variables declaration//GEN-END:variables
+
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.3" maxVersion="1.5" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="2"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="1" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="1" attributes="0">
+ <Component id="jScrollPane1" alignment="0" pref="374" max="32767" attributes="0"/>
+ <Component id="jLabel1" alignment="0" min="-2" max="-2" attributes="0"/>
+ <Group type="102" alignment="0" attributes="0">
+ <Component id="jLabel2" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="dfValue" pref="293" max="32767" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="pbSet" min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Component id="jLabel1" min="-2" max="-2" attributes="0"/>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Component id="jScrollPane1" pref="195" max="32767" attributes="0"/>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="jLabel2" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="dfValue" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="pbSet" alignment="3" pref="28" max="32767" attributes="0"/>
+ </Group>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Component class="javax.swing.JLabel" name="jLabel1">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Propriétés systèmes"/>
+ </Properties>
+ </Component>
+ <Container class="javax.swing.JScrollPane" name="jScrollPane1">
+ <AuxValues>
+ <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
+ </AuxValues>
+
+ <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
+ <SubComponents>
+ <Component class="javax.swing.JList" name="lstProps">
+ <Properties>
+ <Property name="model" type="javax.swing.ListModel" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
+ <Connection code="listModel" type="code"/>
+ </Property>
+ <Property name="selectionMode" type="int" value="0"/>
+ </Properties>
+ </Component>
+ </SubComponents>
+ </Container>
+ <Component class="javax.swing.JLabel" name="jLabel2">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Valeur"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JTextField" name="dfValue">
+ </Component>
+ <Component class="javax.swing.JButton" name="pbSet">
+ <Properties>
+ <Property name="icon" type="javax.swing.Icon" editor="org.netbeans.modules.form.editors2.IconEditor">
+ <Image iconType="3" name="/fr/gouv/finances/cp/xemelios/ui/resources/edit-redo.png"/>
+ </Property>
+ <Property name="toolTipText" type="java.lang.String" value="Enregistrer la valeur"/>
+ <Property name="enabled" type="boolean" value="false"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbSetActionPerformed"/>
+ </Events>
+ </Component>
+ </SubComponents>
+</Form>
--- /dev/null
+/*
+ * Copyright
+ * 2010 axYus - www.axyus.com
+ * 2010 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.admin;
+
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.util.TreeSet;
+import javax.swing.AbstractListModel;
+import javax.swing.event.ListSelectionEvent;
+import javax.swing.event.ListSelectionListener;
+import org.apache.log4j.Logger;
+
+/**
+ *
+ * @author chm
+ */
+public class PnlSystemProperties extends javax.swing.JPanel implements ParamSaver {
+ private static final Logger logger = Logger.getLogger(PnlSystemProperties.class);
+ private TreeSet<Prop> properties;
+ private LM listModel;
+ private Prop currentProp;
+ private PropertiesExpansion applicationConfiguration;
+
+ /** Creates new form PnlUpdate */
+ public PnlSystemProperties(PropertiesExpansion applicationConfiguration) {
+ this.applicationConfiguration = applicationConfiguration;
+ preInitComponents();
+ initComponents();
+ postInitComponents();
+ }
+
+ protected void preInitComponents() {
+ properties = new TreeSet<Prop>();
+ for(Object key:applicationConfiguration.keySet()) {
+ String propName = key.toString();
+ if(propName.startsWith("xemelios")) {
+ Prop prop = new Prop(propName,applicationConfiguration.getProperty(propName));
+ properties.add(prop);
+ }
+ }
+ // on va chercher celles existantes (potentiellement)
+ Class clazz = Constants.class;
+ Field[] fields = clazz.getFields();
+ for(int i=0;i<fields.length;i++) {
+ if(fields[i].getType().equals(String.class) && (fields[i].getModifiers() | (Modifier.PUBLIC + Modifier.STATIC + Modifier.FINAL))>0) {
+ try {
+ String propName = fields[i].get(null).toString();
+ if(propName.startsWith("xemelios") || fields[i].getName().startsWith("SYS_PROP")) {
+ Prop p = new Prop(propName,null);
+ if(!properties.contains(p)) properties.add(p);
+ }
+ } catch(Exception ex) {
+ logger.debug("while introspecting",ex);
+ }
+ }
+ }
+ listModel = new LM(properties);
+ }
+
+ protected void postInitComponents() {
+ lstProps.addListSelectionListener(new ListSelectionListener() {
+
+ @Override
+ public void valueChanged(ListSelectionEvent e) {
+ currentProp = (Prop)lstProps.getSelectedValue();
+ if(currentProp!=null) {
+ dfValue.setEditable(true);
+ dfValue.setText(currentProp.getPropValue());
+ pbSet.setEnabled(true);
+ } else {
+ dfValue.setEditable(false);
+ dfValue.setText(null);
+ pbSet.setEnabled(false);
+ }
+ }
+ });
+
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ jLabel1 = new javax.swing.JLabel();
+ jScrollPane1 = new javax.swing.JScrollPane();
+ lstProps = new javax.swing.JList();
+ jLabel2 = new javax.swing.JLabel();
+ dfValue = new javax.swing.JTextField();
+ pbSet = new javax.swing.JButton();
+
+ jLabel1.setText("Propriétés systèmes");
+
+ lstProps.setModel(listModel);
+ lstProps.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
+ jScrollPane1.setViewportView(lstProps);
+
+ jLabel2.setText("Valeur");
+
+ pbSet.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fr/gouv/finances/cp/xemelios/ui/resources/edit-redo.png"))); // NOI18N
+ pbSet.setToolTipText("Enregistrer la valeur");
+ pbSet.setEnabled(false);
+ pbSet.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbSetActionPerformed(evt);
+ }
+ });
+
+ org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
+ this.setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
+ .addContainerGap()
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
+ .add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 374, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel1)
+ .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
+ .add(jLabel2)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(dfValue, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 287, Short.MAX_VALUE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(pbSet)))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(jLabel1)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(jLabel2)
+ .add(dfValue, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .add(pbSet, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE))
+ .addContainerGap())
+ );
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void pbSetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbSetActionPerformed
+ if(currentProp!=null) {
+ String value = dfValue.getText();
+ if(value!=null && value.length()==0) value = null;
+ currentProp.setPropValue(value);
+ System.setProperty(currentProp.getPropName(), value);
+ }
+ }//GEN-LAST:event_pbSetActionPerformed
+
+ @Override
+ public void saveConfiguration() { }
+
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JTextField dfValue;
+ private javax.swing.JLabel jLabel1;
+ private javax.swing.JLabel jLabel2;
+ private javax.swing.JScrollPane jScrollPane1;
+ private javax.swing.JList lstProps;
+ private javax.swing.JButton pbSet;
+ // End of variables declaration//GEN-END:variables
+
+ private class Prop implements Comparable {
+ private String propName = null;
+ private String propValue = null;
+ private String documentation = null;
+
+ public Prop(String propName, String propValue) {
+ super();
+ this.propName=propName;
+ this.propValue=propValue;
+ }
+ public Prop(String propName, String propValue, String documentation) {
+ this(propName, propValue);
+ this.documentation=documentation;
+ }
+ @Override
+ public String toString() { return propName; }
+
+ public String getDocumentation() {
+ return documentation;
+ }
+
+ public void setDocumentation(String documentation) {
+ this.documentation = documentation;
+ }
+
+ public String getPropName() {
+ return propName;
+ }
+
+ public void setPropName(String propName) {
+ this.propName = propName;
+ }
+
+ public String getPropValue() {
+ return propValue;
+ }
+
+ public void setPropValue(String propValue) {
+ this.propValue = propValue;
+ }
+ public boolean equals(Prop other) { return propName.equals(other.getPropName()); }
+
+ @Override
+ public int compareTo(Object o) {
+ Prop other = (Prop)o;
+ return propName.compareTo(other.getPropName());
+ }
+ }
+
+ private class LM extends AbstractListModel {
+ private Prop[] data;
+
+ public LM(TreeSet<Prop> properties) {
+ super();
+ data = new Prop[properties.size()];
+ properties.toArray(data);
+ }
+
+ @Override
+ public int getSize() {
+ return data.length;
+ }
+
+ @Override
+ public Object getElementAt(int index) {
+ return data[index];
+ }
+
+ }
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.3" maxVersion="1.5" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="2"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="1" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="1" attributes="0">
+ <Component id="pnlConfig" alignment="0" max="32767" attributes="0"/>
+ <Component id="pnlStrategie" alignment="0" max="32767" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="pnlStrategie" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="pnlConfig" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="32767" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Container class="javax.swing.JPanel" name="pnlStrategie">
+ <Properties>
+ <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
+ <Border info="org.netbeans.modules.form.compat2.border.TitledBorderInfo">
+ <TitledBorder title="Stratégie de mise à jour"/>
+ </Border>
+ </Property>
+ </Properties>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" attributes="0">
+ <Component id="jLabel1" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="cbxStrategie" pref="174" max="32767" attributes="0"/>
+ </Group>
+ <Component id="lblStrat" alignment="0" pref="340" max="32767" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <Component id="lblStrat" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="jLabel1" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="cbxStrategie" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="32767" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Component class="javax.swing.JLabel" name="lblStrat">
+ <Properties>
+ <Property name="text" type="java.lang.String" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
+ <Connection code="STRAT_STRING" type="code"/>
+ </Property>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JLabel" name="jLabel1">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Stratégie de mise à jour"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JComboBox" name="cbxStrategie">
+ <Properties>
+ <Property name="model" type="javax.swing.ComboBoxModel" editor="org.netbeans.modules.form.editors2.ComboBoxModelEditor">
+ <StringArray count="0"/>
+ </Property>
+ </Properties>
+ <AuxValues>
+ <AuxValue name="JavaCodeGenerator_CreateCodeCustom" type="java.lang.String" value="new javax.swing.JComboBox(STRATEGIES)"/>
+ </AuxValues>
+ </Component>
+ </SubComponents>
+ </Container>
+ <Container class="javax.swing.JPanel" name="pnlConfig">
+ <Properties>
+ <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
+ <Border info="org.netbeans.modules.form.compat2.border.TitledBorderInfo">
+ <TitledBorder title="Configuration"/>
+ </Border>
+ </Property>
+ </Properties>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="lblConfig" alignment="0" pref="340" max="32767" attributes="0"/>
+ <Group type="102" alignment="0" attributes="0">
+ <Component id="jLabel2" min="-2" max="-2" attributes="0"/>
+ <EmptySpace min="-2" pref="71" max="-2" attributes="0"/>
+ <Component id="cbxConfig" pref="184" max="32767" attributes="0"/>
+ </Group>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <Component id="lblConfig" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="jLabel2" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="cbxConfig" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="32767" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Component class="javax.swing.JLabel" name="lblConfig">
+ <Properties>
+ <Property name="text" type="java.lang.String" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
+ <Connection code="CONFIG_STRAT" type="code"/>
+ </Property>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JLabel" name="jLabel2">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Configuration"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JComboBox" name="cbxConfig">
+ <Properties>
+ <Property name="model" type="javax.swing.ComboBoxModel" editor="org.netbeans.modules.form.editors2.ComboBoxModelEditor">
+ <StringArray count="0"/>
+ </Property>
+ </Properties>
+ <AuxValues>
+ <AuxValue name="JavaCodeGenerator_CreateCodeCustom" type="java.lang.String" value="new javax.swing.JComboBox(CONFIGS)"/>
+ </AuxValues>
+ </Component>
+ </SubComponents>
+ </Container>
+ </SubComponents>
+</Form>
--- /dev/null
+/*
+ * Copyright
+ * 2008 axYus - www.axyus.com
+ * 2008 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.admin;
+
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.Properties;
+import org.apache.log4j.Logger;
+
+/**
+ *
+ * @author chm
+ */
+public class PnlUpdate extends javax.swing.JPanel implements ParamSaver {
+ private static final Logger logger = Logger.getLogger(PnlUpdate.class);
+ private static final transient String STRAT_STRING = "<html>Cette option permet de déterminer le comportement de XéMéLios vis à vis<br/>des mises à jour :<ul><li>soit les mises à jour se font automatiquement,</li><li>soit XéMéLios demande confirmation avant installation,</li><li>soit aucune mise à jour n'est proposée.</li></ul>";
+ private static final transient String CONFIG_STRAT = "<html>Cette option permet de configurer le niveau auquel XéMéLios doit se<br/>mettre à jour :<ul><li>soit sur les composants en production (par défaut),</li><li>soit sur les composants en recette (ceci peut générer des erreurs d'exécution),</li><li>soit sur les composants en cours de développement (ceci génèrera très probablement des erreurs).</li></ul></html>";
+ private static final Pair[] STRATEGIES = { new Pair(Constants.MAJ_SILENT,"Automatique"), new Pair(Constants.MAJ_CONFIRM,"Avec confirmation"), new Pair(Constants.MAJ_NONE,"Pas de proposition") };
+ private static final Pair[] CONFIGS = { new Pair(Constants.MAJ_PROD, "En production"), new Pair(Constants.MAJ_RECETTE, "En recette"), new Pair(Constants.MAJ_PRIVATE, "En développement") };
+ private PropertiesExpansion applicationProperties;
+
+ /** Creates new form PnlUpdate */
+ public PnlUpdate(PropertiesExpansion applicationProperties) {
+ this.applicationProperties = applicationProperties;
+ initComponents();
+ initValues();
+ }
+ private void initValues() {
+ String currentStrat = applicationProperties.getProperty(Constants.SYS_PROP_MAJ_STRATEGY);
+ if(currentStrat==null) currentStrat = Constants.MAJ_CONFIRM;
+ for(int i=0;i<cbxStrategie.getItemCount();i++) {
+ Pair p = (Pair)cbxStrategie.getItemAt(i);
+ if(p.key.equals(currentStrat)) {
+ cbxStrategie.setSelectedIndex(i);
+ break;
+ }
+ }
+ String currentConfig = applicationProperties.getProperty(Constants.SYS_PROP_MAJ_CONFIG);
+ if(currentStrat==null) currentConfig = Constants.MAJ_PROD;
+ for(int i=0;i<cbxConfig.getItemCount();i++) {
+ Pair p = (Pair)cbxConfig.getItemAt(i);
+ if(p.key.equals(currentConfig)) {
+ cbxConfig.setSelectedIndex(i);
+ break;
+ }
+ }
+
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ pnlStrategie = new javax.swing.JPanel();
+ lblStrat = new javax.swing.JLabel();
+ jLabel1 = new javax.swing.JLabel();
+ cbxStrategie = new javax.swing.JComboBox(STRATEGIES);
+ pnlConfig = new javax.swing.JPanel();
+ lblConfig = new javax.swing.JLabel();
+ jLabel2 = new javax.swing.JLabel();
+ cbxConfig = new javax.swing.JComboBox(CONFIGS);
+
+ pnlStrategie.setBorder(javax.swing.BorderFactory.createTitledBorder("Stratégie de mise à jour"));
+
+ lblStrat.setText(STRAT_STRING);
+
+ jLabel1.setText("Stratégie de mise à jour");
+
+ org.jdesktop.layout.GroupLayout pnlStrategieLayout = new org.jdesktop.layout.GroupLayout(pnlStrategie);
+ pnlStrategie.setLayout(pnlStrategieLayout);
+ pnlStrategieLayout.setHorizontalGroup(
+ pnlStrategieLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(pnlStrategieLayout.createSequentialGroup()
+ .addContainerGap()
+ .add(pnlStrategieLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(pnlStrategieLayout.createSequentialGroup()
+ .add(jLabel1)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(cbxStrategie, 0, 174, Short.MAX_VALUE))
+ .add(lblStrat, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 340, Short.MAX_VALUE))
+ .addContainerGap())
+ );
+ pnlStrategieLayout.setVerticalGroup(
+ pnlStrategieLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(pnlStrategieLayout.createSequentialGroup()
+ .add(lblStrat)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(pnlStrategieLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(jLabel1)
+ .add(cbxStrategie, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
+ .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ );
+
+ pnlConfig.setBorder(javax.swing.BorderFactory.createTitledBorder("Configuration"));
+
+ lblConfig.setText(CONFIG_STRAT);
+
+ jLabel2.setText("Configuration");
+
+ org.jdesktop.layout.GroupLayout pnlConfigLayout = new org.jdesktop.layout.GroupLayout(pnlConfig);
+ pnlConfig.setLayout(pnlConfigLayout);
+ pnlConfigLayout.setHorizontalGroup(
+ pnlConfigLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(pnlConfigLayout.createSequentialGroup()
+ .addContainerGap()
+ .add(pnlConfigLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(lblConfig, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 340, Short.MAX_VALUE)
+ .add(pnlConfigLayout.createSequentialGroup()
+ .add(jLabel2)
+ .add(71, 71, 71)
+ .add(cbxConfig, 0, 184, Short.MAX_VALUE)))
+ .addContainerGap())
+ );
+ pnlConfigLayout.setVerticalGroup(
+ pnlConfigLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(pnlConfigLayout.createSequentialGroup()
+ .add(lblConfig)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(pnlConfigLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(jLabel2)
+ .add(cbxConfig, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
+ .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ );
+
+ org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
+ this.setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
+ .addContainerGap()
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
+ .add(org.jdesktop.layout.GroupLayout.LEADING, pnlConfig, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.LEADING, pnlStrategie, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(pnlStrategie, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(pnlConfig, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ );
+ }// </editor-fold>//GEN-END:initComponents
+
+ @Override
+ public void saveConfiguration() {
+ Properties xemProps = new Properties();
+
+ File xemPropsFile = new File(applicationProperties.replace("${xemelios.prg}/root/xemelios.properties"));
+ try {
+ if(xemPropsFile.exists()) {
+ xemProps.load(new FileInputStream(xemPropsFile));
+ }
+ xemProps.setProperty(Constants.SYS_PROP_MAJ_STRATEGY,((Pair)cbxStrategie.getSelectedItem()).key);
+ applicationProperties.setProperty(Constants.SYS_PROP_MAJ_STRATEGY,((Pair)cbxStrategie.getSelectedItem()).key);
+ xemProps.setProperty(Constants.SYS_PROP_MAJ_CONFIG,((Pair)cbxConfig.getSelectedItem()).key);
+ applicationProperties.setProperty(Constants.SYS_PROP_MAJ_CONFIG,((Pair)cbxConfig.getSelectedItem()).key);
+ FileOutputStream fos = new FileOutputStream(xemPropsFile);
+ xemProps.store(fos,"");
+ fos.close();
+ } catch(IOException ioEx) {
+ logger.error("in saveConfiguration",ioEx);
+ }
+ }
+
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JComboBox cbxConfig;
+ private javax.swing.JComboBox cbxStrategie;
+ private javax.swing.JLabel jLabel1;
+ private javax.swing.JLabel jLabel2;
+ private javax.swing.JLabel lblConfig;
+ private javax.swing.JLabel lblStrat;
+ private javax.swing.JPanel pnlConfig;
+ private javax.swing.JPanel pnlStrategie;
+ // End of variables declaration//GEN-END:variables
+
+}
--- /dev/null
+<?xml version="1.1" encoding="UTF-8" ?>
+
+<Form version="1.3" maxVersion="1.7" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="jScrollPane1" alignment="0" pref="380" max="32767" attributes="0"/>
+ <Component id="jLabel1" alignment="0" min="-2" pref="117" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="jLabel1" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="jScrollPane1" min="-2" pref="106" max="-2" attributes="0"/>
+ <EmptySpace pref="163" max="32767" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Component class="javax.swing.JLabel" name="jLabel1">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Version JAVA utilisée :"/>
+ </Properties>
+ </Component>
+ <Container class="javax.swing.JScrollPane" name="jScrollPane1">
+ <AuxValues>
+ <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
+ </AuxValues>
+
+ <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
+ <SubComponents>
+ <Component class="javax.swing.JTextArea" name="jTextArea1">
+ <Properties>
+ <Property name="background" type="java.awt.Color" editor="org.netbeans.beaninfo.editors.ColorEditor">
+ <Color blue="d8" green="e9" id="Panel.background" palette="3" red="ec" type="palette"/>
+ </Property>
+ <Property name="columns" type="int" value="20"/>
+ <Property name="rows" type="int" value="5"/>
+ <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
+ <Border info="null"/>
+ </Property>
+ </Properties>
+ </Component>
+ </SubComponents>
+ </Container>
+ </SubComponents>
+</Form>
--- /dev/null
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+/*
+ * PnlVersion.java
+ *
+ * Created on 28 oct. 2010, 17:27:00
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.admin;
+
+import org.apache.log4j.Logger;
+
+/**
+ *
+ * @author franck.nhieu
+ */
+public class PnlVersion extends javax.swing.JPanel implements ParamSaver {
+ private static Logger logger = Logger.getLogger(PnlVersion.class);
+
+ /** Creates new form PnlVersion */
+ public PnlVersion() {
+ initComponents();
+ String spec_version = System.getProperty("java.specification.version");
+ String upd_version = System.getProperty("java.version");
+ String jvm_version = System.getProperty("java.vm.version");
+
+ double vnum = Double.parseDouble(spec_version);
+ if( vnum >= 1.6d )
+ spec_version = spec_version.concat("(OK)");
+ else
+ spec_version = spec_version.concat("(KO)");
+ jTextArea1.setText(spec_version);
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ @SuppressWarnings("unchecked")
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ jLabel1 = new javax.swing.JLabel();
+ jScrollPane1 = new javax.swing.JScrollPane();
+ jTextArea1 = new javax.swing.JTextArea();
+
+ jLabel1.setText("Version JAVA utilisée :");
+
+ jTextArea1.setBackground(javax.swing.UIManager.getDefaults().getColor("Panel.background"));
+ jTextArea1.setColumns(20);
+ jTextArea1.setRows(5);
+ jTextArea1.setBorder(null);
+ jScrollPane1.setViewportView(jTextArea1);
+
+ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
+ this.setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
+ .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(jLabel1)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addContainerGap(163, Short.MAX_VALUE))
+ );
+ }// </editor-fold>//GEN-END:initComponents
+
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JLabel jLabel1;
+ private javax.swing.JScrollPane jScrollPane1;
+ private javax.swing.JTextArea jTextArea1;
+ // End of variables declaration//GEN-END:variables
+
+ @Override
+ public void saveConfiguration() {
+ //throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2009 axYus - www.axyus.com
+ * 2009 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui.collectivites;
+
+import fr.gouv.finances.cp.utils.ui.VerticalFlowLayout;
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
+import java.awt.BorderLayout;
+import java.awt.GridBagConstraints;
+import java.awt.GridBagLayout;
+import java.awt.Insets;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Vector;
+import javax.swing.JButton;
+import javax.swing.JComboBox;
+import javax.swing.JDialog;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import org.apache.log4j.Logger;
+
+/**
+ *
+ * @author chm
+ */
+public class DlgSelectCollectivite extends JDialog implements ParentCollectiviteListener {
+ private static final Logger logger = Logger.getLogger(DlgSelectCollectivite.class);
+
+ private DocumentModel dm;
+ private XemeliosUser user;
+ private JFrame parent;
+ private JComboBox cbxCollectivites;
+ private ParentCollectiviteContainer container;
+ private boolean response;
+
+ public DlgSelectCollectivite(DocumentModel dm, XemeliosUser user, JFrame parent) {
+ super(parent, "Choisir une collectivité", true);
+ this.dm=dm;
+ this.user=user;
+ this.parent=parent;
+ initComponents();
+ }
+
+ protected void initComponents() {
+ setLayout(new BorderLayout());
+ JPanel vPane = new JPanel(new VerticalFlowLayout());
+// final Pair parentColls[] = new Pair[dm.getCollectivitePath().getParentsCount()];
+ container = new ParentCollectiviteContainer(dm.getCollectivitePath().getParentsCount());
+ JPanel collPane = new JPanel(new GridBagLayout());
+ GridBagConstraints cstr = new GridBagConstraints();
+ cstr.ipadx = 2;
+ cstr.ipady = 2;
+ cstr.insets = new Insets(2, 2, 2, 2);
+ //int rowCount = 0;
+ cstr.gridy=0;
+ if(dm.getCollectivitePath().getParentsCount()>0) {
+ for(int i=dm.getCollectivitePath().getParentsCount()-1;i>=0;i--) {
+ PnlCollectivite pnl = new PnlCollectivite(this, dm, dm.getCollectivitePath().getParent(i), container, user);
+ cstr.gridx=0;
+ cstr.weightx=1d;
+ cstr.anchor=GridBagConstraints.EAST;
+ collPane.add(pnl.getLabel(),cstr);
+ cstr.gridx=1;
+ cstr.weightx=0d;
+ cstr.anchor=GridBagConstraints.WEST;
+ collPane.add(pnl.getTextField(),cstr);
+ cstr.gridx=2;
+ cstr.anchor=GridBagConstraints.CENTER;
+ collPane.add(pnl.getButton(),cstr);
+ cstr.gridy++;
+ }
+ }
+ cstr.gridx=0;
+ cstr.weightx=1d;
+ cstr.anchor=GridBagConstraints.EAST;
+ collPane.add(new JLabel("Collectivité"),cstr);
+ cstr.gridx=1;
+ cstr.weightx=0d;
+ cstr.gridwidth=2;
+ cstr.anchor=GridBagConstraints.WEST;
+ cbxCollectivites = new JComboBox();
+ collPane.add(cbxCollectivites,cstr);
+ addComplementElements(collPane,cstr);
+ vPane.add(collPane);
+ JPanel hPane = new JPanel(new BorderLayout());
+ JPanel buttonPane = new JPanel();
+ JButton pbCancel = new JButton("Annuler");
+ pbCancel.addActionListener(new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ setVisible(false);
+ }
+ });
+ buttonPane.add(pbCancel);
+ JButton pbOk = new JButton("Ok");
+ pbOk.addActionListener(new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ if(cbxCollectivites.getSelectedIndex()>=0) {
+ response = true;
+ setVisible(false);
+ }
+ }
+ });
+ buttonPane.add(pbOk);
+ hPane.add(buttonPane,BorderLayout.CENTER);
+ vPane.add(hPane);
+ add(vPane,BorderLayout.CENTER);
+ container.addListener(this);
+ if(dm.getCollectivitePath().getParentsCount()==0) {
+ valueChanged(1, null);
+ }
+ pack();
+ setLocationRelativeTo(parent);
+ }
+ public void addComplementElements(JPanel collPane,GridBagConstraints cstr) {
+
+ }
+ public void valueChanged(int pos, Pair newValue) {
+ if(pos==1) { // direct parent has changed
+ cbxCollectivites.removeAllItems();
+ try {
+ Vector<Pair> colls = DataLayerManager.getImplementation().getCollectivites(dm, container.getParents(), user);
+ for(Pair p:colls)
+ cbxCollectivites.addItem(new MyPair(p));
+ } catch(Exception ex) {
+ logger.error("while querying collectivites:",ex);
+ }
+ } else {
+ cbxCollectivites.removeAllItems();
+ }
+ }
+ @Override
+ public void setVisible(boolean b) {
+ if(b) {
+ response = false;
+ }
+ super.setVisible(b);
+ }
+ public boolean run() {
+ setVisible(true);
+ return response;
+ }
+ public Pair getCollectivite() { return (Pair)cbxCollectivites.getSelectedItem(); }
+
+ public DocumentModel getDm() {
+ return dm;
+ }
+
+ public XemeliosUser getUser() {
+ return user;
+ }
+ JComboBox getCbxCollectivite() { return cbxCollectivites; }
+ static class ParentCollectiviteContainer {
+ Pair parentColls[];
+ List<ParentCollectiviteListener> listeners;
+ private int size = 0;
+ public ParentCollectiviteContainer(int size) {
+ super();
+ this.size=size;
+ parentColls = new Pair[size];
+ listeners = new ArrayList<ParentCollectiviteListener>();
+ }
+ public void setPair(int pos,Pair value) {
+ parentColls[pos] = value;
+ for(int i=pos-1;i>=0;i--) {
+ parentColls[i] = null;
+ fireValueChanged(pos+1, value);
+ }
+ fireValueChanged(pos+1, value);
+ }
+ public Pair getPair(int pos) {
+ return parentColls[pos];
+ }
+ protected void fireValueChanged(int pos, Pair value) {
+ for(ParentCollectiviteListener listener:listeners) {
+ listener.valueChanged(pos, value);
+ }
+ }
+ void addListener(ParentCollectiviteListener listener) {
+ listeners.add(listener);
+ }
+ public int getSize() { return size; }
+ public Pair[] getParents() { return parentColls; }
+ @Override
+ public String toString() {
+ StringBuffer sb = new StringBuffer();
+ sb.append("[");
+ for(int i=0;i<parentColls.length;i++) {
+ sb.append(parentColls[i]);
+ if(i!=(parentColls.length-1)) sb.append(",");
+ }
+ sb.append("]");
+ return sb.toString();
+ }
+ }
+
+ private class MyPair extends Pair {
+ public MyPair(Pair p) {
+ super(p.key,p.libelle);
+ }
+
+ @Override
+ public String toString() {
+ return libelle.concat(" (").concat(key).concat(")");
+ }
+
+ }
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2009 axYus - www.axyus.com
+ * 2009 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui.collectivites;
+
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.SpecialKeyModel;
+import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
+import java.awt.GridBagConstraints;
+import java.awt.event.ItemEvent;
+import java.awt.event.ItemListener;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Vector;
+import javax.swing.JComboBox;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import org.apache.log4j.Logger;
+
+/**
+ *
+ * @author chm
+ */
+public class DlgSelectNavigationTarget extends DlgSelectCollectivite {
+ private static final Logger logger = Logger.getLogger(DlgSelectCollectivite.class);
+ ArrayList<JComboBox> specialKeysLists;
+ ArrayList<SpecialKeyModel> models;
+ ArrayList<Pair> specialKeys;
+ private JComboBox cbxBudget;
+
+ public DlgSelectNavigationTarget(DocumentModel dm, XemeliosUser user, JFrame parent) {
+ super(dm,user,parent);
+ setTitle("Choisir une collectivité, un budget ...");
+ }
+ public Pair getBudget() { return (Pair)cbxBudget.getSelectedItem(); }
+ public List<Pair> getSpecialKeys() { return specialKeys; }
+
+ @Override
+ public void addComplementElements(JPanel collPane, GridBagConstraints cstr) {
+ getCbxCollectivite().addItemListener(new ItemListener() {
+ public void itemStateChanged(ItemEvent e) {
+ if(e.getStateChange()==ItemEvent.DESELECTED) {
+ cbxBudget.removeAllItems();
+ } else {
+ try {
+ Vector<Pair> data = DataLayerManager.getImplementation().getBudgets(getDm(), getCollectivite(), getUser());
+ for(Pair p:data) cbxBudget.addItem(p);
+ cbxBudget.setSelectedIndex(0);
+ } catch(Exception ex) {
+ logger.error("while getting budgets:",ex);
+ }
+ }
+ }
+ });
+ cstr.gridy++;
+ cstr.gridx=0;
+ cstr.gridwidth=1;
+ cstr.weightx=1d;
+ cstr.anchor=GridBagConstraints.EAST;
+ collPane.add(new JLabel("Budget"),cstr);
+ cbxBudget = new JComboBox();
+ cstr.gridx=1;
+ cstr.weightx=0d;
+ cstr.gridwidth=2;
+ cstr.anchor=GridBagConstraints.WEST;
+ collPane.add(cbxBudget,cstr);
+ if(!getDm().getSpecialKeys().isEmpty()) {
+ cbxBudget.addItemListener(new ItemListener() {
+ public void itemStateChanged(ItemEvent e) {
+ try {
+ if(getBudget()!=null) {
+ Vector<Pair> data = DataLayerManager.getImplementation().getSpecialKeys1(getDm(), getCollectivite(), getBudget(), true, getUser());
+ JComboBox cbx = specialKeysLists.get(0);
+ cbx.removeAllItems();
+ for(Pair p:data) cbx.addItem(p);
+ cbx.setSelectedIndex(0);
+ }
+ } catch(Exception ex) {
+ logger.error("while getting keys1:",ex);
+ }
+ }
+ });
+ specialKeysLists = new ArrayList<JComboBox>();
+ models = new ArrayList<SpecialKeyModel>();
+ specialKeys = new ArrayList<Pair>();
+ for(SpecialKeyModel skm:getDm().getSpecialKeys()) {
+ cstr.gridy++;
+ cstr.gridx=0;
+ cstr.gridwidth=1;
+ cstr.weightx=1d;
+ cstr.anchor=GridBagConstraints.EAST;
+ collPane.add(new JLabel(skm.getLibelle()),cstr);
+ JComboBox cbx = new JComboBox();
+ cstr.gridx=1;
+ cstr.weightx=0d;
+ cstr.gridwidth=2;
+ cstr.anchor=GridBagConstraints.WEST;
+ collPane.add(cbx,cstr);
+ specialKeysLists.add(cbx);
+ cbx.addItemListener(new ItemListener() {
+ public void itemStateChanged(ItemEvent e) {
+ JComboBox thisOne = (JComboBox)e.getItemSelectable();
+ int rank = specialKeysLists.indexOf(thisOne);
+ if(e.getStateChange()==ItemEvent.DESELECTED) {
+ for(int i=rank+1;i<specialKeysLists.size();i++) {
+ JComboBox cbx = specialKeysLists.get(i);
+ cbx.removeAllItems();
+ }
+ while(specialKeys.size()>rank) specialKeys.remove(rank);
+ } else {
+ specialKeys.add((Pair)thisOne.getSelectedItem());
+// SpecialKeyModel skm = models.get(rank);
+ if(rank==0) {
+ try {
+ Vector<Pair> data = DataLayerManager.getImplementation().getSpecialKeys2(getDm(), getCollectivite(), getBudget(), (Pair)thisOne.getSelectedItem(), true, getUser());
+ JComboBox cbx = specialKeysLists.get(1);
+ for(Pair p:data) cbx.addItem(p);
+ cbx.setSelectedIndex(0);
+ } catch(IndexOutOfBoundsException aioobEx) {
+ // ignore
+ } catch(Exception ex) {
+ logger.error("while getting keys2:",ex);
+ }
+ } else if(rank==1) {
+ JComboBox previousOne = specialKeysLists.get(0);
+ try {
+ Vector<Pair> data = DataLayerManager.getImplementation().getSpecialKeys3(getDm(), getCollectivite(), getBudget(), (Pair)thisOne.getSelectedItem(), (Pair)previousOne.getSelectedItem(),true, getUser());
+ JComboBox cbx = specialKeysLists.get(2);
+ for(Pair p:data) cbx.addItem(p);
+ cbx.setSelectedIndex(0);
+ } catch(IndexOutOfBoundsException aioobEx) {
+ // ignore
+ } catch(Exception ex) {
+ logger.error("while getting keys3:",ex);
+ }
+ }
+ }
+ }
+ });
+ }
+ }
+ }
+
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.3" maxVersion="1.7" type="org.netbeans.modules.form.forminfo.JDialogFormInfo">
+ <Properties>
+ <Property name="defaultCloseOperation" type="int" value="2"/>
+ <Property name="title" type="java.lang.String" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
+ <Connection code="title" type="code"/>
+ </Property>
+ </Properties>
+ <SyntheticProperties>
+ <SyntheticProperty name="formSizePolicy" type="int" value="1"/>
+ </SyntheticProperties>
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="2"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="jScrollPane1" alignment="0" max="32767" attributes="0"/>
+ <Component id="jLabel1" alignment="0" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ </Group>
+ <Group type="102" alignment="1" attributes="0">
+ <EmptySpace pref="174" max="32767" attributes="0"/>
+ <Component id="pbCancel" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="pbOk" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Component id="jLabel1" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="jScrollPane1" pref="305" max="32767" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="pbOk" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="pbCancel" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Component class="javax.swing.JLabel" name="jLabel1">
+ <Properties>
+ <Property name="text" type="java.lang.String" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
+ <Connection code="message" type="code"/>
+ </Property>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JButton" name="pbOk">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Ok"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbOkActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="pbCancel">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Annuler"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbCancelActionPerformed"/>
+ </Events>
+ </Component>
+ <Container class="javax.swing.JScrollPane" name="jScrollPane1">
+ <AuxValues>
+ <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
+ </AuxValues>
+
+ <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
+ <SubComponents>
+ <Component class="org.jdesktop.swingx.JXTable" name="table">
+ <Properties>
+ <Property name="model" type="javax.swing.table.TableModel" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
+ <Connection code="tableModel" type="code"/>
+ </Property>
+ </Properties>
+ <Events>
+ <EventHandler event="mouseClicked" listener="java.awt.event.MouseListener" parameters="java.awt.event.MouseEvent" handler="tableMouseClicked"/>
+ </Events>
+ </Component>
+ </SubComponents>
+ </Container>
+ </SubComponents>
+</Form>
--- /dev/null
+/*
+ * Copyright
+ * 2009 axYus - www.axyus.com
+ * 2009 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui.collectivites;
+
+import fr.gouv.finances.dgfip.utils.Pair;
+import java.util.Vector;
+import javax.swing.JDialog;
+import javax.swing.JList;
+import javax.swing.ListSelectionModel;
+import javax.swing.table.DefaultTableModel;
+
+/**
+ *
+ * @author chm
+ */
+public class DlgSelectPair extends javax.swing.JDialog {
+ private static final long serialVersionUID = 1L;
+
+ private String title, message;
+ private Vector<Pair> elements;
+ private boolean response = false;
+ private PairTableModel tableModel;
+
+ /** Creates new form DlgSelectPair */
+ public DlgSelectPair(JDialog parent, String title, String message, Vector<Pair> elements) {
+ super(parent, true);
+ this.title=title;
+ this.message=message;
+ this.elements=elements;
+ tableModel = new PairTableModel(this.elements);
+ initComponents();
+ table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
+ setLocationRelativeTo(parent);
+ }
+
+ public Pair showSelectionBox() {
+ response = false;
+ setVisible(true);
+ if(response) {
+ return elements.get(table.convertRowIndexToModel(table.getSelectedRow()));
+ } else {
+ return null;
+ }
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ @SuppressWarnings("unchecked")
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ jLabel1 = new javax.swing.JLabel();
+ pbOk = new javax.swing.JButton();
+ pbCancel = new javax.swing.JButton();
+ jScrollPane1 = new javax.swing.JScrollPane();
+ table = new org.jdesktop.swingx.JXTable();
+
+ setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+ setTitle(title);
+
+ jLabel1.setText(message);
+
+ pbOk.setText("Ok");
+ pbOk.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbOkActionPerformed(evt);
+ }
+ });
+
+ pbCancel.setText("Annuler");
+ pbCancel.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbCancelActionPerformed(evt);
+ }
+ });
+
+ table.setModel(tableModel);
+ table.addMouseListener(new java.awt.event.MouseAdapter() {
+ public void mouseClicked(java.awt.event.MouseEvent evt) {
+ tableMouseClicked(evt);
+ }
+ });
+ jScrollPane1.setViewportView(table);
+
+ org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(jScrollPane1)
+ .add(jLabel1))
+ .addContainerGap())
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
+ .addContainerGap(174, Short.MAX_VALUE)
+ .add(pbCancel)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(pbOk)
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(jLabel1)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 305, Short.MAX_VALUE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(pbOk)
+ .add(pbCancel))
+ .addContainerGap())
+ );
+
+ pack();
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void pbCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbCancelActionPerformed
+ setVisible(false);
+ }//GEN-LAST:event_pbCancelActionPerformed
+
+ private void pbOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbOkActionPerformed
+ if(table.getSelectedRowCount()>0) {
+ response = true;
+ setVisible(false);
+ }
+ }//GEN-LAST:event_pbOkActionPerformed
+
+ private void tableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableMouseClicked
+ if(evt.getClickCount()>=2) {
+ pbOk.doClick();
+ }
+ }//GEN-LAST:event_tableMouseClicked
+
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JLabel jLabel1;
+ private javax.swing.JScrollPane jScrollPane1;
+ private javax.swing.JButton pbCancel;
+ private javax.swing.JButton pbOk;
+ private org.jdesktop.swingx.JXTable table;
+ // End of variables declaration//GEN-END:variables
+
+ private class PairTableModel extends DefaultTableModel {
+ private static final long serialVersionUID = 1L;
+ private Vector<Pair> data;
+ public PairTableModel(Vector<Pair> data) {
+ super();
+ this.data=data;
+ }
+
+ @Override
+ public Object getValueAt(int row, int column) {
+ Pair p = data.get(row);
+ if(column==0) return p.key;
+ else return p.libelle;
+ }
+
+ @Override
+ public boolean isCellEditable(int row, int column) {
+ return false;
+ }
+
+ @Override
+ public String getColumnName(int column) {
+ switch(column) {
+ case 0: return "Code";
+ default: return "Libellé";
+ }
+ }
+
+ @Override
+ public int getColumnCount() {
+ return 2;
+ }
+ public void setData(Vector<Pair> data) {
+ this.data=data;
+ fireTableDataChanged();
+ }
+
+ @Override
+ public int getRowCount() {
+ return data!=null ? data.size() : 0;
+ }
+
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2009 axYus - www.axyus.com
+ * 2009 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui.collectivites;
+
+import fr.gouv.finances.dgfip.utils.Pair;
+
+/**
+ *
+ * @author chm
+ */
+public interface ParentCollectiviteListener {
+ public void valueChanged(int pos, Pair newValue);
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2009 axYus - www.axyus.com
+ * 2009 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui.collectivites;
+
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ParentModel;
+import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.util.Vector;
+import javax.swing.JButton;
+import javax.swing.JDialog;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JTextField;
+import org.apache.log4j.Logger;
+
+/**
+ *
+ * @author chm
+ */
+public class PnlCollectivite extends JPanel implements ParentCollectiviteListener {
+ private static final Logger logger = Logger.getLogger(PnlCollectivite.class);
+ private DocumentModel dm;
+ private ParentModel parentModel = null;
+ private DlgSelectCollectivite.ParentCollectiviteContainer collectivites;
+ private XemeliosUser user = null;
+ private JTextField df;
+ private Pair selectedPair;
+ private int level;
+ private JDialog parentDialog;
+ private JLabel lbl;
+ private JButton pb;
+
+ PnlCollectivite(JDialog parentDialog, DocumentModel dm, ParentModel parentModel, DlgSelectCollectivite.ParentCollectiviteContainer collectivites, XemeliosUser user) {
+ super();
+ this.parentDialog=parentDialog;
+ this.dm = dm;
+ this.parentModel=parentModel;
+ this.level = parentModel.getLevel();
+ this.collectivites=collectivites;
+ this.user=user;
+ initComponents();
+ collectivites.addListener(this);
+ }
+
+ protected void initComponents() {
+ lbl = new JLabel(getLibelle());
+ df = new JTextField();
+ df.setEditable(false);
+ df.setColumns(40);
+ pb = new JButton("...") {
+ @Override
+ public int getHeight() {
+ return df.getHeight();
+ }
+ @Override
+ public int getWidth() {
+ return getHeight();
+ }
+ };
+ pb.addActionListener(new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+// logger.debug(collectivites);
+ if(collectivites.getSize()>=level) {
+ Pair[] localParents = new Pair[collectivites.getSize()-level];
+ for(int i=parentModel.getLevel();i<collectivites.getSize();i++) {
+ localParents[i-level] = collectivites.getPair(i);
+ }
+ try {
+ Vector<Pair> colls = DataLayerManager.getImplementation().getParentCollectivites(dm, level, localParents, user);
+ Vector<Pair> tmpColls = new Vector<Pair>();
+ for(Pair p:colls) tmpColls.add(new MyPair(p));
+ DlgSelectPair dlg = new DlgSelectPair(parentDialog, "Collectivités", parentModel.getLibelle(), tmpColls);
+ Pair p = dlg.showSelectionBox();
+ if(p!=null) {
+ selectedPair = p;
+ df.setText(selectedPair.toString());
+ collectivites.setPair(parentModel.getLevel()-1,selectedPair);
+ }
+ } catch(Exception ex) {
+ logger.error("looking for parents:",ex);
+ }
+ }
+// logger.debug(collectivites);
+ }
+ });
+// add(pb);
+ }
+
+ protected String getLibelle() {
+ return parentModel.getLibelle();
+ }
+
+ public void valueChanged(int pos, Pair newValue) {
+// logger.debug(getLibelle()+"("+level+") received valueChanged("+pos+","+newValue+")");
+ if(pos>level) {
+ selectedPair = null;
+ df.setText("");
+ }
+ }
+ public JLabel getLabel() { return lbl; }
+ public JTextField getTextField() { return df; }
+ public JButton getButton() { return pb; }
+
+ private class MyPair extends Pair {
+ public MyPair(Pair p) {
+ super(p.key,p.libelle);
+ }
+
+ @Override
+ public String toString() {
+ if(!key.equals(libelle))
+ return libelle.concat(" (").concat(key).concat(")");
+ else
+ return libelle;
+ }
+
+ }
+
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 N.Le Corre - nicolas.lecorre@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.export;
+
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.KeyEvent;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.io.File;
+import java.sql.SQLException;
+import java.util.Vector;
+
+import javax.swing.AbstractAction;
+import javax.swing.Action;
+import javax.swing.DefaultComboBoxModel;
+import javax.swing.JComboBox;
+import javax.swing.JComponent;
+import javax.swing.JDialog;
+import javax.swing.JFileChooser;
+import javax.swing.JFrame;
+import javax.swing.JOptionPane;
+import javax.swing.JRootPane;
+import javax.swing.KeyStroke;
+import javax.swing.ListSelectionModel;
+import javax.swing.SwingUtilities;
+import javax.swing.event.ListSelectionEvent;
+import javax.swing.event.ListSelectionListener;
+import javax.swing.filechooser.FileFilter;
+import javax.swing.table.AbstractTableModel;
+
+import org.apache.log4j.Logger;
+
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.cp.utils.StartUrl;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentsModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.EtatModel;
+import fr.gouv.finances.dgfip.xemelios.data.DataConfigurationException;
+import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
+import fr.gouv.finances.dgfip.xemelios.data.DataResultSet;
+import fr.gouv.finances.dgfip.xemelios.export.ConfigModel;
+import fr.gouv.finances.cp.xemelios.export.Exporter;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.cp.xemelios.ui.resulttable.EtatResultTableModel;
+import fr.gouv.finances.dgfip.xemelios.auth.UnauthorizedException;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+import fr.gouv.finances.dgfip.xemelios.swing.InterruptibleInfiniteGlassPane;
+
+/**
+ *
+ * @author nicolas.lecorre
+ */
+public class DlgSearchConfig extends JDialog {
+ private static Logger logger = Logger.getLogger(DlgSearchConfig.class);
+
+ //
+ private File _f = null;
+
+ private DlgSearchConfig _sc = null;
+
+ // la liste des documents
+ private DocumentsModel docModels;
+
+ // résultat de la recherche
+ private Vector<ConfigModel> listeConfigs;
+
+ private int mode = 0;
+ // menu Fichier / Exporter
+ public static final int EXEC_FROM_RECHERCHE = 1;
+ // Menu Export / Config
+ public static final int EXEC_FROM_CONF = 2;
+ // Menu Export / Executer
+ public static final int EXEC_FROM_MENU = 3;
+
+ // variables pour l'export
+ private EtatResultTableModel ertm;
+ private DocumentModel dm;
+ private ElementModel em;
+
+ private Pair coll = null;
+ private Pair budg = null;
+ private String fic = null;
+ private Pair SK1 = null;
+ private Pair SK2 = null;
+ private int whatToExport = 0;
+
+ private InterruptibleInfiniteGlassPane interruptible;
+
+ private XemeliosUser user;
+
+ /** Creates new form SearchConfigs */
+ public DlgSearchConfig(JFrame parent,DocumentsModel dm, int mode, XemeliosUser user) {
+ super(parent, true);
+ _sc = this;
+ this.user=user;
+ docModels = dm;
+ setMode(mode);
+//logger.debug("mode is "+mode);
+ initComponents();
+
+ }
+
+ private void activateSupModButtons(boolean active) {
+ bSupprimer.setEnabled(active);
+ bChanger.setEnabled(active);
+ }
+ private void activateNewRechButton(boolean active) {
+ bNouveau.setEnabled(active);
+ bRechercher.setEnabled(active);
+ }
+ private void shouldActivateNewRech() {
+ if (!((Pair)cbEtat.getSelectedItem()).key.equals("RIEN")) {
+ activateNewRechButton(true);
+ } else {
+ activateNewRechButton(false);
+ }
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ */
+ private void initComponents() {
+ jPanel1 = new javax.swing.JPanel();
+ jLabel2 = new javax.swing.JLabel();
+ cbDoc = new javax.swing.JComboBox();
+ jLabel3 = new javax.swing.JLabel();
+ cbEtat = new javax.swing.JComboBox();
+ bRechercher = new javax.swing.JButton();
+ jPanel2 = new javax.swing.JPanel();
+ jScrollPane2 = new javax.swing.JScrollPane();
+ jTable1 = new javax.swing.JTable();
+ bNouveau = new javax.swing.JButton();
+ bChanger = new javax.swing.JButton();
+ bSupprimer = new javax.swing.JButton();
+ bExecuter = new javax.swing.JButton();
+ bFermer = new javax.swing.JButton();
+
+ setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+
+ jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Recherche"));
+ jLabel2.setText("Document");
+
+ Vector<Pair>cbDocItems = getDocsIds();
+ cbDoc.setModel(new javax.swing.DefaultComboBoxModel(cbDocItems));
+ cbDoc.setSelectedIndex(0);
+ cbDoc.setBorder(javax.swing.BorderFactory.createEtchedBorder());
+ cbDoc.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ JComboBox cb = (JComboBox)e.getSource();
+ String petName = ((Pair)cb.getSelectedItem()).key;
+ updateEtats(petName);
+ //activateNewRechButton(false);
+ shouldActivateNewRech();
+ activateSupModButtons(false);
+ }
+ });
+
+ jLabel3.setText("Etat");
+
+
+ cbEtat.setBorder(javax.swing.BorderFactory.createEtchedBorder());
+ cbEtat.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ shouldActivateNewRech();
+ }
+ });
+
+ bRechercher.setText("Rechercher");
+ bRechercher.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ bRechercherActionPerformed(evt);
+ }
+ });
+
+ org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
+ jPanel1.setLayout(jPanel1Layout);
+ jPanel1Layout.setHorizontalGroup(
+ jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(jPanel1Layout.createSequentialGroup()
+ .addContainerGap()
+ .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(jLabel2)
+ .add(jLabel3))
+ .add(39, 39, 39)
+ .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(cbDoc, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 356, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .add(jPanel1Layout.createSequentialGroup()
+ .add(cbEtat, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 356, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 27, Short.MAX_VALUE)
+ .add(bRechercher)))
+ .addContainerGap())
+ );
+ jPanel1Layout.setVerticalGroup(
+ jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(jPanel1Layout.createSequentialGroup()
+ .addContainerGap()
+ .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(jLabel2)
+ .add(cbDoc, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 24, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(cbEtat, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 24, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .add(jLabel3)
+ .add(bRechercher))
+ .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ );
+
+ jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Configurations"));
+ jScrollPane2.setViewportView(jTable1);
+
+ jTable1.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(MouseEvent e) {
+ if (e.getClickCount()==2) {
+ if (mode!=EXEC_FROM_CONF) {
+ bExecuterActionPerformed(null);
+ } else {
+ bChangerActionPerformed(null);
+ }
+ }
+ }
+ });
+ jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
+ jTable1.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
+ @Override
+ public void valueChanged(ListSelectionEvent e) {
+ if(jTable1.getSelectedRow() >= 0) {
+ bSupprimer.setEnabled(true);
+ bChanger.setEnabled(true);
+ if(getMode()!=EXEC_FROM_CONF) bExecuter.setEnabled(true);
+ } else {
+ bSupprimer.setEnabled(false);
+ bChanger.setEnabled(false);
+ bExecuter.setEnabled(false);
+ }
+ }
+ });
+
+ org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
+ jPanel2.setLayout(jPanel2Layout);
+ jPanel2Layout.setHorizontalGroup(
+ jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2Layout.createSequentialGroup()
+ .addContainerGap()
+ .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 557, Short.MAX_VALUE)
+ .addContainerGap())
+ );
+ jPanel2Layout.setVerticalGroup(
+ jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(jPanel2Layout.createSequentialGroup()
+ .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 327, Short.MAX_VALUE)
+ .addContainerGap())
+ );
+
+ bNouveau.setText("Nouveau");
+ bNouveau.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ bNouveauActionPerformed(evt);
+ }
+ });
+
+ bChanger.setText("Modifier");
+ bChanger.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ bChangerActionPerformed(evt);
+ }
+ });
+
+ bSupprimer.setText("Supprimer");
+ bSupprimer.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ bSupprimerActionPerformed(evt);
+ }
+ });
+ bExecuter.setText("Exécuter");
+ bExecuter.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ bExecuterActionPerformed(evt);
+ }
+ });
+ bFermer.setText("Fermer");
+ bFermer.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ bFermerActionPerformed(evt);
+ }
+ });
+
+ org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
+ .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .add(layout.createSequentialGroup()
+ .add(bExecuter)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(bSupprimer)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(bChanger)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(bNouveau)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 50, Short.MAX_VALUE)
+ .add(bFermer)))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(bNouveau)
+ .add(bChanger)
+ .add(bSupprimer)
+ .add(bExecuter)
+ .add(bFermer))
+ .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ );
+ setTitle("Liste des configurations d'export");
+ setDefaultCloseOperation(DISPOSE_ON_CLOSE);
+ pack();
+ setLocationRelativeTo(getParent());
+
+ // désactivation de certains boutons
+ activateNewRechButton(false);
+ activateSupModButtons(false);
+
+ //Si on n'a qu'un seul document et qu'un seul état, on les sélectionne et on lance la recherche
+ if (cbDocItems.size()==1) {
+ String petName = ((Pair)cbDoc.getSelectedItem()).key;
+ updateEtats(petName);
+
+ }
+ setGlassPane(interruptible = new InterruptibleInfiniteGlassPane());
+ bExecuter.setEnabled(false);
+ }
+
+ private void bSupprimerActionPerformed(java.awt.event.ActionEvent evt) {
+ if(JOptionPane.showConfirmDialog(this,"Etes vous sur de vouloir supprimer cette configuration ?","Suppression",JOptionPane.YES_NO_OPTION)==JOptionPane.NO_OPTION)
+ return;
+ try {
+ DataLayerManager.getImplementation().deleteConfigExport(this.listeConfigs.get(jTable1.getSelectedRow()),user);
+ bRechercherActionPerformed(null);
+ } catch (Exception e) {
+ logger.error("Erreur lors de la suppression d'une configuration",e);
+ }
+ }
+
+ private void bFermerActionPerformed(java.awt.event.ActionEvent evt) {
+ this.dispose();
+ }
+ private void bExecuterActionPerformed(java.awt.event.ActionEvent evt) {
+ if (mode == EXEC_FROM_CONF) return;
+ if (jTable1.getSelectedRow()<0) return;
+ JFileChooser fc = new JFileChooser();
+ fc.setFileFilter(new FileFilter(){
+ @Override
+ public boolean accept(File f) {
+ return f.isDirectory() || f.getName().toUpperCase().endsWith(".XLS");
+ }
+ @Override
+ public String getDescription() { return "Fichier Excel"; }
+ });
+ if(fc.showSaveDialog(this)==JFileChooser.APPROVE_OPTION) {
+ _f = fc.getSelectedFile();
+ // verification de la presence d'une extension
+ // on cherche un '.' aux positions len-1, len-2, len-3, len-4
+ String fileName = _f.getAbsolutePath();
+ int len = fileName.length();
+ if(fileName.substring(len-4).indexOf('.')<0) {
+ fileName=fileName+".xls";
+ _f = new File(fileName);
+ }
+ if(_f.exists()) {
+ if(JOptionPane.showConfirmDialog(this,fileName+"\nCe fichier existe déjà . Voulez-vous l'écraser ?","Ecrasement",JOptionPane.YES_NO_OPTION)==JOptionPane.NO_OPTION)
+ return;
+ }
+
+ if (mode == EXEC_FROM_RECHERCHE) {
+ try {
+// ExportJob ej = new ExportJob();
+// ej.setDataResultSet(ertm.getResultSet());
+// ej.setDocumentId(dm.getId());
+// ej.setEtatId(em.getParent().getId());
+// ej.setElementId(em.getId());
+// ej.setExportConfigId(Long.parseLong(listeConfigs.get(jTable1.getSelectedRow()).getId()));
+// ej.setExportName("toto");
+// ej.setFileName("toto");
+// DataLayerManager.getImplementation().createExportJob(ej, user);
+ SwingUtilities.invokeLater(new Runnable() {
+ @Override
+ public void run() {
+ String etatKey = ((Pair)cbEtat.getSelectedItem()).key;
+ Exporter ex = new Exporter(_f, ertm.getResultSet(), dm, etatKey, em, listeConfigs.get(jTable1.getSelectedRow()),MainWindow.getInstance().getEnvProperties());
+ ex.setParentFrame(_sc);
+ interruptible.setThreadToInterrupt(ex);
+ getGlassPane().setVisible(true);
+ ex.execute();
+ }
+ });
+ } catch (Exception e) {
+ logger.error(e);
+ }
+ } else {
+ try {
+ SwingUtilities.invokeLater(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ String docKey = ((Pair)cbDoc.getSelectedItem()).key;
+ String etatKey = ((Pair)cbEtat.getSelectedItem()).key;
+ em = (docModels.getDocumentById(docKey)).getEtatById(etatKey).getImportableElement();
+
+ /**
+ * CREATION de la requête en fonction de ce que l'on exporte
+ */
+
+ DataResultSet drs = DataLayerManager.getImplementation().getDataResultSetForExport(whatToExport, em, coll, budg, fic, SK1, SK2, user);
+ Exporter ex = new Exporter(_f, drs, dm, etatKey, em, listeConfigs.get(jTable1.getSelectedRow()), MainWindow.getInstance().getEnvProperties());
+ ex.setParentFrame(_sc);
+ interruptible.setThreadToInterrupt(ex);
+ getGlassPane().setVisible(true);
+ ex.execute();
+ } catch(UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(getParent(), ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (DataConfigurationException dae) {
+ logger.error("", dae);
+ } catch (SQLException sqle) {
+ logger.error("", sqle);
+ }
+ }
+ });
+ } catch (Exception e) {
+ logger.error(e);
+ }
+ }
+ }
+ }
+
+ public void showXLS() {
+ try {
+ getGlassPane().setVisible(false);
+ setVisible(false);
+ StartUrl.startUrl(_f.toURI().toURL().toExternalForm());
+ } catch (Throwable t) {}
+ }
+
+ public void bRechercherActionPerformed(java.awt.event.ActionEvent evt) {
+ jTable1.removeAll();
+ try {
+ String docKey = ((Pair)cbDoc.getSelectedItem()).key;
+ String etatKey = ((Pair)cbEtat.getSelectedItem()).key;
+ if (!"RIEN".equals(docKey) && !"RIEN".equals(etatKey)) {
+ listeConfigs = DataLayerManager.getImplementation().getListeConfigsExport(docKey, etatKey, user);
+ jTable1.setModel(new ConfigTableModel(listeConfigs));
+ }
+ } catch (Throwable t) {}
+
+ }
+
+ private void bChangerActionPerformed(java.awt.event.ActionEvent evt) {
+ String docKey = ((Pair)cbDoc.getSelectedItem()).key;
+ String etatKey = ((Pair)cbEtat.getSelectedItem()).key;
+ DocumentModel dm2 = this.docModels.getDocumentById(docKey);
+ EditConfig ec = new EditConfig(this, dm2, this.listeConfigs.get(jTable1.getSelectedRow()),user);
+ ec.setVisible(true);
+ }
+
+ private void bNouveauActionPerformed(java.awt.event.ActionEvent evt) {
+ String docKey = ((Pair)cbDoc.getSelectedItem()).key;
+ String etatKey = ((Pair)cbEtat.getSelectedItem()).key;
+ DocumentModel dm2 = this.docModels.getDocumentById(docKey);
+ EditConfig ec = new EditConfig(this, dm2, etatKey,user);
+ ec.setVisible(true);
+ }
+
+ private javax.swing.JButton bChanger;
+ private javax.swing.JButton bNouveau;
+ private javax.swing.JButton bRechercher;
+ private javax.swing.JComboBox cbDoc;
+ private javax.swing.JComboBox cbEtat;
+ private javax.swing.JLabel jLabel2;
+ private javax.swing.JLabel jLabel3;
+ private javax.swing.JPanel jPanel1;
+ private javax.swing.JPanel jPanel2;
+ private javax.swing.JScrollPane jScrollPane2;
+ private javax.swing.JTable jTable1;
+ private javax.swing.JButton bSupprimer;
+ private javax.swing.JButton bExecuter;
+ private javax.swing.JButton bFermer;
+ private Action escapeAction;
+
+ // retourne la liste des id de documents
+ private Vector<Pair> getDocsIds() {
+ Vector<Pair> ret = new Vector<Pair>();
+ if (docModels.getDocuments().size()>1)
+ ret.add(new Pair("RIEN", "Sélectionnez un document"));
+ for (DocumentModel dm2:docModels.getDocuments()) {
+ // si le doc a au moins un etat exportable
+ for (EtatModel em2:dm2.getEtats()) {
+ if (em2.isExportable()) {
+ ret.add(new Pair(dm2.getId(),dm2.getTitre()));
+ break;
+ }
+ }
+ }
+ return ret;
+ }
+ // retourne la liste des id états d'un document
+ private Vector<Pair> getEtatsIds(String docID) {
+ Vector<Pair> ret = new Vector<Pair>();
+ if (docModels.getDocumentById(docID).getEtats().size()>1)
+ ret.add(new Pair("RIEN", "Sélectionnez un état"));
+ for (EtatModel em2:docModels.getDocumentById(docID).getEtats()) {
+ if (em2.isExportable())
+ ret.add(new Pair(em2.getId(), em2.getTitre()));
+ }
+ return ret;
+ }
+
+ // mets à jour la liste des états
+ private void updateEtats(String docID) {
+ if (!"RIEN".equals(docID)) {
+ Vector<Pair> cbEtatIds = getEtatsIds(docID);
+ cbEtat.setModel(new DefaultComboBoxModel(cbEtatIds));
+ if (cbEtatIds.size()==1) {
+ cbEtat.setSelectedIndex(0);
+ bRechercherActionPerformed(null);
+ activateNewRechButton(true);
+ }
+ } else
+ cbEtat.setModel(new DefaultComboBoxModel());
+ }
+
+ private class ConfigTableModel extends AbstractTableModel {
+ private String[] columnNames = new String [] { "Code", "Libellé", "Créateur", "Date création" };
+ private Vector<String[]> data = new Vector<String[]>();
+
+ public ConfigTableModel(Vector<ConfigModel> d) {
+ int row=0, column=0;
+ for (ConfigModel cm:d) {
+ column=0;
+ String[] tmp = new String[4];
+ tmp[column++] = cm.getCode();
+ tmp[column++] = cm.getLibelle();
+ tmp[column++] = cm.getOwner();
+ tmp[column++] = cm.getDateCreation();
+ data.add(tmp);
+ }
+ }
+
+ @Override
+ public String getColumnName(int column) {
+ return columnNames[column];
+ }
+
+ @Override
+ public boolean isCellEditable(int rowIndex, int columnIndex) {
+ return false;
+ }
+
+ @Override
+ public int getColumnCount() {
+ return columnNames.length;
+ }
+
+ @Override
+ public int getRowCount() {
+ return (data!=null?data.size():0);
+ }
+
+ @Override
+ public Object getValueAt(int rowIndex, int columnIndex) {
+ return (data!=null?data.get(rowIndex)[columnIndex]:"");
+ }
+ }
+ @Override
+ protected JRootPane createRootPane() {
+ KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0);
+ JRootPane rp = new JRootPane();
+ escapeAction = new AbstractAction("Fermer") {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ setVisible(false);
+ }
+ };
+ rp.registerKeyboardAction(escapeAction,"TOTOTOTO",ks,JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
+ }
+
+ public int getMode() {
+ return mode;
+ }
+
+ public void setMode(int mode) {
+ this.mode = mode;
+ }
+
+ public ConfigModel getConfigSelected() {
+ return this.listeConfigs.get(jTable1.getSelectedRow());
+ }
+
+ public EtatResultTableModel getErtm() {
+ return ertm;
+ }
+
+ public void setErtm(EtatResultTableModel ertm) {
+ this.ertm = ertm;
+ }
+
+ public ElementModel getEm() {
+ return em;
+ }
+
+ public void setEm(ElementModel em) {
+ this.em = em;
+ }
+
+ public DocumentModel getDm() {
+ return dm;
+ }
+
+ public void setDm(DocumentModel dm) {
+ this.dm = dm;
+ }
+
+ /**
+ * teste si le documentModel contient au moins un étatModel exportable
+ */
+ public static boolean docHasEtatToExport(DocumentsModel dms) {
+ if (dms.getDocuments().size()<1) return false;
+
+ for (DocumentModel dm:dms.getDocuments()) {
+ for (EtatModel em:dm.getEtats()) {
+ if (em.isExportable()) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ public Pair getBudg() {
+ return budg;
+ }
+
+ public void setBudg(Pair budg) {
+ this.budg = budg;
+ }
+
+ public Pair getColl() {
+ return coll;
+ }
+
+ public void setColl(Pair coll) {
+ this.coll = coll;
+ }
+
+ public void setWhatToExport(int whatToExport) {
+ this.whatToExport = whatToExport;
+ }
+
+ public void setFic(String fic) {
+ this.fic = fic;
+ }
+
+ public Pair getSK1() {
+ return SK1;
+ }
+
+ public void setSK1(Pair sk1) {
+ SK1 = sk1;
+ }
+
+ public Pair getSK2() {
+ return SK2;
+ }
+
+ public void setSK2(Pair sk2) {
+ SK2 = sk2;
+ }
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.3" maxVersion="1.3" type="org.netbeans.modules.form.forminfo.JDialogFormInfo">
+ <Properties>
+ <Property name="defaultCloseOperation" type="int" value="2"/>
+ <Property name="title" type="java.lang.String" value="Configuration d'export"/>
+ </Properties>
+ <SyntheticProperties>
+ <SyntheticProperty name="formSizePolicy" type="int" value="1"/>
+ </SyntheticProperties>
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="2"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="jPanel2" alignment="0" max="32767" attributes="0"/>
+ <Component id="jPanel1" alignment="0" max="32767" attributes="0"/>
+ <Group type="102" alignment="1" attributes="0">
+ <Component id="bAnnuler" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="bEnregistrer" min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <Component id="jPanel1" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="jPanel2" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="32767" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="bEnregistrer" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="bAnnuler" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Container class="javax.swing.JPanel" name="jPanel1">
+ <Properties>
+ <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
+ <Border info="org.netbeans.modules.form.compat2.border.TitledBorderInfo">
+ <TitledBorder title="Identification"/>
+ </Border>
+ </Property>
+ </Properties>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="jLabel1" min="-2" max="-2" attributes="0"/>
+ <Component id="jLabel2" alignment="0" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace min="-2" pref="26" max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="tLibelle" pref="581" max="32767" attributes="0"/>
+ <Component id="tCode" alignment="0" pref="581" max="32767" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="jLabel1" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="tCode" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="tLibelle" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="jLabel2" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="32767" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Component class="javax.swing.JLabel" name="jLabel1">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Code"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JLabel" name="jLabel2">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Libellé"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JTextField" name="tCode">
+ </Component>
+ <Component class="javax.swing.JTextField" name="tLibelle">
+ </Component>
+ </SubComponents>
+ </Container>
+ <Container class="javax.swing.JPanel" name="jPanel2">
+ <Properties>
+ <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
+ <Border info="org.netbeans.modules.form.compat2.border.TitledBorderInfo">
+ <TitledBorder title="Configuration"/>
+ </Border>
+ </Property>
+ </Properties>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="1" attributes="0">
+ <EmptySpace pref="405" max="32767" attributes="0"/>
+ <Component id="bSelectAll" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="bSelectNone" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <Group type="102" alignment="0" attributes="0">
+ <Component id="liste" pref="659" max="32767" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" attributes="0">
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="bSelectNone" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="bSelectAll" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace pref="12" max="32767" attributes="0"/>
+ <Component id="liste" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Component class="javax.swing.JButton" name="bSelectNone">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Tout désélectionner"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="bSelectNoneActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="bSelectAll">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Tout sélectionner"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="bSelectAllActionPerformed"/>
+ </Events>
+ </Component>
+ <Container class="javax.swing.JScrollPane" name="liste">
+ <AuxValues>
+ <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
+ </AuxValues>
+
+ <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
+ <SubComponents>
+ <Component class="org.jdesktop.swingx.JXTreeTable" name="treeTable">
+ <Properties>
+ <Property name="autoResizeMode" type="int" value="3"/>
+ </Properties>
+ <AuxValues>
+ <AuxValue name="JavaCodeGenerator_CreateCodeCustom" type="java.lang.String" value="new JXTreeTablePropertyEditor();"/>
+ </AuxValues>
+ </Component>
+ </SubComponents>
+ </Container>
+ </SubComponents>
+ </Container>
+ <Component class="javax.swing.JButton" name="bEnregistrer">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Enregistrer"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="bEnregistrerActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="bAnnuler">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Annuler"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="bAnnulerActionPerformed"/>
+ </Events>
+ </Component>
+ </SubComponents>
+</Form>
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui.export;
+
+import java.awt.Component;
+import java.awt.event.ActionEvent;
+import java.awt.event.KeyEvent;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.util.Vector;
+
+import javax.swing.AbstractAction;
+import javax.swing.JCheckBox;
+import javax.swing.JComponent;
+import javax.swing.JDialog;
+import javax.swing.JLabel;
+import javax.swing.JRootPane;
+import javax.swing.JTable;
+import javax.swing.KeyStroke;
+import javax.swing.event.TreeExpansionEvent;
+import javax.swing.event.TreeExpansionListener;
+import javax.swing.table.DefaultTableCellRenderer;
+import javax.swing.table.TableCellRenderer;
+
+import org.apache.log4j.Logger;
+import org.jdesktop.swingx.JXTreeTable;
+
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import fr.gouv.finances.dgfip.xemelios.common.config.ChampModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.EtatModel;
+import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
+import fr.gouv.finances.dgfip.xemelios.export.ConfigModel;
+import fr.gouv.finances.dgfip.xemelios.export.ConfigParser;
+import fr.gouv.finances.dgfip.xemelios.export.ExportChampModel;
+import fr.gouv.finances.dgfip.xemelios.export.ExportElementModel;
+import fr.gouv.finances.dgfip.xemelios.export.ExportModel;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+import java.io.OutputStreamWriter;
+import org.jdesktop.swingx.treetable.AbstractTreeTableModel;
+
+/**
+ *
+ * @author nicolas.lecorre
+ */
+public class EditConfig extends JDialog {
+
+ private static final long serialVersionUID = 5669669876743219771L;
+ private static Logger logger = Logger.getLogger(EditConfig.class);
+ private DocumentModel dm;
+ private ConfigModel cm;
+ private String docID, etatID;
+ // la structure contenant la configuration
+ private ExportModel data = new ExportModel(ExportModel.QN);
+ // la structure contenant la configuration à modifier
+ private ExportModel dataToBeModified = null;
+ private AbstractAction escapeAction;
+ private XemeliosUser user;
+
+ /** Creates new form EditConfig */
+ public EditConfig(JDialog parent, DocumentModel d, ConfigModel c, XemeliosUser user) {
+ super(parent);
+ this.dm = d;
+ docID = dm.getId();
+ this.cm = c;
+ etatID = cm.getEtatID();
+ this.user = user;
+ try {
+ ConfigParser cp = new ConfigParser();
+ cp.parse(new ByteArrayInputStream(c.getConfigLines()));
+ dataToBeModified = (ExportModel) cp.getMarshallable();
+ } catch (Exception e) {
+ logger.error("Erreur lors de la lecture de la configuration à modifier", e);
+ }
+ initComponents();
+ tCode.setText(c.getCode());
+ tLibelle.setText(c.getLibelle());
+ setLocationRelativeTo(getParent());
+ treeTable.setTreeTableModel(createModel(dm, cm.getEtatID()));
+ updateModel();
+ treeTable.addTreeExpansionListener(new TreeExpansionListener() {
+
+ @Override
+ public void treeCollapsed(TreeExpansionEvent event) {
+ }
+
+ @Override
+ public void treeExpanded(TreeExpansionEvent event) {
+ treeTable.packAll();
+ }
+ });
+ treeTable.getColumnModel().getColumn(1).setMaxWidth(25);
+ treeTable.expandAll();
+ }
+
+ public EditConfig(JDialog parent, DocumentModel d, String etatID, XemeliosUser user) {
+ super(parent);
+ this.dm = d;
+ docID = dm.getId();
+ this.etatID = etatID;
+ this.user=user;
+ initComponents();
+ setLocationRelativeTo(getParent());
+ treeTable.setTreeTableModel(createModel(dm, etatID));
+ treeTable.addTreeExpansionListener(new TreeExpansionListener() {
+
+ @Override
+ public void treeCollapsed(TreeExpansionEvent event) {
+ }
+
+ @Override
+ public void treeExpanded(TreeExpansionEvent event) {
+ treeTable.packAll();
+ }
+ });
+ treeTable.getColumnModel().getColumn(1).setMaxWidth(25);
+ treeTable.expandAll();
+ }
+
+ /**
+ * Merge le model créé à partir du fichier métier Xemelios et de la configuration que l'on tente de modifier
+ */
+ private void updateModel() {
+ if (dataToBeModified != null) {
+ for (ExportElementModel eemDest : data.getEnfants()) {
+ String eID = eemDest.getId();
+ for (ExportElementModel eemRef : dataToBeModified.getEnfants()) {
+ if (eemRef.getId().equals(eID)) {
+ updateEEM(eemRef, eemDest);
+ }
+ }
+ }
+ }
+ }
+
+ private void updateEEM(ExportElementModel reference, ExportElementModel destination) {
+ for (ExportChampModel ecmDest : destination.getChamps()) {
+ String cID = ecmDest.getId();
+ for (ExportChampModel ecmRef : reference.getChamps()) {
+ if (ecmRef.getId().equals(cID)) {
+ ecmDest.setSelectionne(ecmRef.isSelectionne());
+ }
+ }
+ }
+ for (ExportElementModel eemDest : destination.getEnfants()) {
+ String eID = eemDest.getId();
+ for (ExportElementModel eemRef : reference.getEnfants()) {
+ if (eemRef.getId().equals(eID)) {
+ updateEEM(eemRef, eemDest);
+ }
+ }
+ }
+ }
+
+ private ConfigTreeTableModel createModel(DocumentModel dm, String etatID) {
+ ConfigTreeTableModel ret = new ConfigTreeTableModel(data);
+ EtatModel em = dm.getEtatById(etatID);
+ ElementModel emROOT = null;
+ for (String k : em.getElements().keySet()) {
+ ElementModel tmp = em.getElements().get(k);
+ if (tmp.getSimpleParent() == null) {
+ emROOT = tmp;
+ break;
+ }
+ }
+ // maintenant, on dispose de l'élément ROOT pour notre arbre
+ if (emROOT != null) {
+ try {
+ ExportModel exm = new ExportModel(ExportModel.QN);
+ exm.setId((cm != null ? cm.getId() : ""));
+ exm.setCode((cm != null ? cm.getCode() : ""));
+ exm.setLibelle((cm != null ? cm.getLibelle() : ""));
+ // les champs de l'élément ROOT
+ ExportElementModel eem = buildEEM(emROOT, null);
+ if (emROOT.getEnfant() != null) {
+ eem.setEnfants(readChildren(emROOT, em, eem));
+ // les fils
+ }
+ exm.addEnfant(eem);
+ data = exm;
+ ret.setData(exm);
+ } catch (Exception e) {
+ logger.error("Erreur lors de la lecture de la définition de la configuration", e);
+ }
+ } else {
+ logger.error("Impossible de trouver l'élément ROOT");
+ }
+
+ return ret;
+ }
+
+ private Vector<ExportElementModel> readChildren(ElementModel p, EtatModel em, ExportElementModel parent) throws Exception {
+ Vector<ExportElementModel> ret = new Vector<ExportElementModel>();
+ for (String k : p.getEnfant().getEnfants().keySet()) {
+ ElementModel child = em.getElementById(k);
+ ExportElementModel eem = buildEEM(child, parent);
+ if (child.getEnfant() != null && child.getEnfant().getEnfants().size() > 0) {
+ eem.setEnfants(readChildren(child, em, eem));
+ }
+ ret.add(eem);
+ }
+ return ret;
+ }
+
+ private ExportElementModel buildEEM(ElementModel em, ExportElementModel parent) throws Exception {
+ ExportElementModel ret = new ExportElementModel(ExportElementModel.QN);
+ ret.setId(em.getId());
+ ret.setLibelle(em.getTitre());
+ ret.setParent(parent);
+
+ // l'éventuel ExportElementModel présente dans la config correspondant
+ ExportElementModel eemRef = null;
+ if (dataToBeModified != null) {
+ eemRef = findCorrespondingEEM(ret, dataToBeModified.getEnfants());
+ }
+
+ // champs de l'élément ROOT
+ for (ChampModel tmpC : em.getListeResultat().getListeChamps()) {
+ if (tmpC.isExportable()) {
+ ExportChampModel ecm = new ExportChampModel(ExportChampModel.QN);
+ ecm.setId(tmpC.getId());
+ ecm.setLibelle(tmpC.getLibelle()); // +" ("+((ElementModel)(tmpC.getParentAsNoeudModifiable().getParentAsNoeudModifiable())).getId()
+ ecm.setEditable(!tmpC.isIdentifiant());
+ ecm.setIdentifiant(tmpC.isIdentifiant());
+ //TODO
+ if (eemRef != null) {
+ ExportChampModel ecmRef = findCorrespondingECM(ecm, eemRef);
+ if (ecmRef != null) {
+ ecm.setSelectionne(ecmRef.isSelectionne());
+ } else {
+ ecm.setSelectionne(false);
+ }
+ } else {
+ ecm.setSelectionne(false);
+ }
+ ret.addChamp(ecm);
+ }
+ }
+ return ret;
+ }
+
+ private ExportChampModel findCorrespondingECM(ExportChampModel ecm, ExportElementModel eem) {
+ for (ExportChampModel e : eem.getChamps()) {
+ if (e.getId().equals(ecm.getId())) {
+ return ecm;
+ }
+ }
+ return null;
+ }
+
+ private ExportElementModel findCorrespondingEEM(ExportElementModel eem, Vector<ExportElementModel> liste) {
+ ExportElementModel ret = null;
+ for (ExportElementModel e : liste) {
+ if (e.getId().equals(eem.getId())) {
+ ret = e;
+ break;
+ } else if (e.getEnfants().size() > 0) {
+ ret = findCorrespondingEEM(eem, e.getEnfants());
+ if (ret != null) {
+ break;
+ }
+ }
+ }
+ return ret;
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ jPanel1 = new javax.swing.JPanel();
+ jLabel1 = new javax.swing.JLabel();
+ jLabel2 = new javax.swing.JLabel();
+ tCode = new javax.swing.JTextField();
+ tLibelle = new javax.swing.JTextField();
+ jPanel2 = new javax.swing.JPanel();
+ bSelectNone = new javax.swing.JButton();
+ bSelectAll = new javax.swing.JButton();
+ liste = new javax.swing.JScrollPane();
+ treeTable = new JXTreeTablePropertyEditor();
+ bEnregistrer = new javax.swing.JButton();
+ bAnnuler = new javax.swing.JButton();
+
+ setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+ setTitle("Configuration d'export");
+
+ jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Identification"));
+
+ jLabel1.setText("Code");
+
+ jLabel2.setText("Libellé");
+
+ org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
+ jPanel1.setLayout(jPanel1Layout);
+ jPanel1Layout.setHorizontalGroup(
+ jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(jPanel1Layout.createSequentialGroup()
+ .addContainerGap()
+ .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(jLabel1)
+ .add(jLabel2))
+ .add(26, 26, 26)
+ .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(tLibelle, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 581, Short.MAX_VALUE)
+ .add(tCode, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 581, Short.MAX_VALUE))
+ .addContainerGap())
+ );
+ jPanel1Layout.setVerticalGroup(
+ jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(jPanel1Layout.createSequentialGroup()
+ .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(jLabel1)
+ .add(tCode, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(tLibelle, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .add(jLabel2))
+ .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ );
+
+ jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Configuration"));
+
+ bSelectNone.setText("Tout désélectionner");
+ bSelectNone.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ bSelectNoneActionPerformed(evt);
+ }
+ });
+
+ bSelectAll.setText("Tout sélectionner");
+ bSelectAll.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ bSelectAllActionPerformed(evt);
+ }
+ });
+
+ treeTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_LAST_COLUMN);
+ liste.setViewportView(treeTable);
+
+ org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
+ jPanel2.setLayout(jPanel2Layout);
+ jPanel2Layout.setHorizontalGroup(
+ jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2Layout.createSequentialGroup()
+ .addContainerGap(390, Short.MAX_VALUE)
+ .add(bSelectAll)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(bSelectNone))
+ .add(jPanel2Layout.createSequentialGroup()
+ .add(liste, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 653, Short.MAX_VALUE)
+ .addContainerGap())
+ );
+ jPanel2Layout.setVerticalGroup(
+ jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(jPanel2Layout.createSequentialGroup()
+ .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(bSelectNone)
+ .add(bSelectAll))
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 12, Short.MAX_VALUE)
+ .add(liste, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .addContainerGap())
+ );
+
+ bEnregistrer.setText("Enregistrer");
+ bEnregistrer.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ bEnregistrerActionPerformed(evt);
+ }
+ });
+
+ bAnnuler.setText("Annuler");
+ bAnnuler.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ bAnnulerActionPerformed(evt);
+ }
+ });
+
+ org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
+ .add(bAnnuler)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(bEnregistrer)))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(bEnregistrer)
+ .add(bAnnuler))
+ .addContainerGap())
+ );
+
+ pack();
+ }// </editor-fold>//GEN-END:initComponents
+ private void bEnregistrerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bEnregistrerActionPerformed
+ boolean needInsert = false;
+ if (cm == null) {
+ cm = new ConfigModel(ConfigModel.QN);
+ needInsert = true;
+ }
+ try {
+ cm.setCode(tCode.getText());
+ cm.setLibelle(tLibelle.getText());
+ data.setId(cm.getCode());
+ data.setLibelle(cm.getLibelle());
+ cm.setDocID(docID);
+ cm.setEtatID(etatID);
+ cm.setOwner(MainWindow.getInstance().getConnectedUser().getId());
+ ensureKeysSelected();
+ ByteArrayOutputStream sos = new ByteArrayOutputStream();
+ OutputStreamWriter os = new OutputStreamWriter(sos, "ISO-8859-1");
+ XmlOutputter xo = new XmlOutputter(os, "ISO-8859-1");
+ data.marshall(xo);
+ os.flush();
+ cm.setConfigLines(sos.toByteArray());
+ if (needInsert) {
+ DataLayerManager.getImplementation().insertConfigExport(cm, user);
+ } else {
+ DataLayerManager.getImplementation().updateConfigExport(cm, user);
+ }
+ ((DlgSearchConfig) getParent()).bRechercherActionPerformed(null);
+ } catch (Exception e) {
+ logger.error("Erreur lors de la sauvegarde de la configuration", e);
+ }
+ this.dispose();
+ }//GEN-LAST:event_bEnregistrerActionPerformed
+
+ /**
+ * Assure que pour chaque niveau, si un champs est sélectionné, les éléments formant la clef de ce niveau le sont aussi.
+ * Assure aussi que si un champs est sélectionné pour un niveau, les clefs des niveaux parents le sont aussi.
+ */
+ private void ensureKeysSelected() {
+ // la liste des éléments dont il faut sélectionner la clef
+ Vector<ExportElementModel> toSelect = new Vector<ExportElementModel>();
+ for (ExportElementModel ecm : data.getEnfants()) {
+ browseChildrenToSelect(ecm, toSelect);
+ }
+
+// sélection de la clef de chaque élément identifié
+ for (ExportElementModel e : toSelect) {
+ e.selectChampsKey();
+ e.selectParentChampsKey();
+ }
+
+ }
+
+ private void browseChildrenToSelect(ExportElementModel parent, Vector<ExportElementModel> toSelect) {
+ if (parent.hasChampSelected()) {
+ toSelect.add(parent);
+ }
+
+ for (ExportElementModel ecm : parent.getEnfants()) {
+ browseChildrenToSelect(ecm, toSelect);
+ }
+
+ }
+
+ private void bAnnulerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bAnnulerActionPerformed
+ this.dispose();
+ }//GEN-LAST:event_bAnnulerActionPerformed
+
+ private void bSelectNoneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bSelectNoneActionPerformed
+ toggleAll(false);
+ treeTable.repaint();
+ }//GEN-LAST:event_bSelectNoneActionPerformed
+
+ private void bSelectAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bSelectAllActionPerformed
+ toggleAll(true);
+ treeTable.repaint();
+ }//GEN-LAST:event_bSelectAllActionPerformed
+
+ /**
+ * Change l'état sélectionné de toutes les feuilles de l'arbre
+ * @param select true => sélectionne, false => désélectionne
+ */
+ private void toggleAll(boolean select) {
+ for (ExportElementModel eem : data.getEnfants()) {
+ toggle(eem, select);
+ }
+
+ }
+
+ private void toggle(ExportElementModel e, boolean select) {
+ for (ExportChampModel ecm : e.getChamps()) {
+ ecm.setSelectionne(select);
+ }
+
+ for (ExportElementModel eem : e.getEnfants()) {
+ toggle(eem, select);
+ }
+
+ }
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JButton bAnnuler;
+ private javax.swing.JButton bEnregistrer;
+ private javax.swing.JButton bSelectAll;
+ private javax.swing.JButton bSelectNone;
+ private javax.swing.JLabel jLabel1;
+ private javax.swing.JLabel jLabel2;
+ private javax.swing.JPanel jPanel1;
+ private javax.swing.JPanel jPanel2;
+ private javax.swing.JScrollPane liste;
+ private javax.swing.JTextField tCode;
+ private javax.swing.JTextField tLibelle;
+ private org.jdesktop.swingx.JXTreeTable treeTable;
+ // End of variables declaration//GEN-END:variables
+ private static class JXTreeTablePropertyEditor extends JXTreeTable {
+
+ private static final long serialVersionUID = -5756581514191559300L;
+ private TableCellRenderer booleanRenderer, booleanDisabledRenderer, blankRenderer;
+
+ public JXTreeTablePropertyEditor() {
+ super();
+ booleanRenderer = new DefaultTableCellRenderer() {
+
+ private JCheckBox chk = new JCheckBox();
+
+ @Override
+ public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
+ JLabel lbl = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
+ chk.setSelected(((Boolean) value).booleanValue());
+ chk.setBackground(lbl.getBackground());
+ chk.setBorder(lbl.getBorder());
+ return chk;
+ }
+ };
+ booleanDisabledRenderer = new DefaultTableCellRenderer() {
+
+ private JCheckBox chk = new JCheckBox();
+
+ @Override
+ public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
+ JLabel lbl = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
+ chk.setSelected(((Boolean) value).booleanValue());
+ chk.setBackground(lbl.getBackground());
+ chk.setBorder(lbl.getBorder());
+ chk.setEnabled(false);
+ return chk;
+ }
+ };
+ blankRenderer = new DefaultTableCellRenderer() {
+
+ @Override
+ public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
+ JLabel lbl = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
+ lbl.setText("");
+ return lbl;
+ }
+ };
+ }
+
+ @Override
+ public TableCellRenderer getCellRenderer(int row, int column) {
+ if (column == 1 && getTreeTableModel() instanceof ConfigTreeTableModel) {
+ ConfigTreeTableModel model = (ConfigTreeTableModel) getTreeTableModel();
+ Object node = getPathForRow(row).getLastPathComponent();
+ if (node instanceof ExportChampModel) {
+// ExportChampModel ecm = (ExportChampModel)node;
+// if(!ecm.isEditable()) {
+// return booleanDisabledRenderer;
+// } else {
+ return booleanRenderer;
+// }
+ } else if (node instanceof ExportElementModel) {
+ return blankRenderer;
+ }
+ return super.getCellRenderer(row, column);
+ } else {
+ return super.getCellRenderer(row, column);
+ }
+ }
+ }
+
+ private static class ConfigTreeTableModel extends AbstractTreeTableModel {
+
+ private String[] columnNames = new String[]{"", ""};
+ private ExportModel _data;
+
+ public ConfigTreeTableModel(ExportModel data) {
+ _data = data;
+ }
+
+ @Override
+ public boolean isLeaf(Object node) {
+ if (node instanceof ExportElementModel) {
+ return (((ExportElementModel) node).getEnfants().size() == 0 && ((ExportElementModel) node).getChamps().size() == 0);
+ } else if (node instanceof ExportChampModel) {
+ return true;
+ } else {
+ return true;
+ }
+ }
+
+ @Override
+ public Class getColumnClass(int i) {
+ if (i == 0) {
+ return super.getColumnClass(i);
+ } else if (i == 1) {
+ return Boolean.class;
+ } else {
+ return super.getColumnClass(i);
+ }
+ }
+
+ @Override
+ public Object getValueAt(Object object, int i) {
+ if (object instanceof ExportElementModel) {
+ if (i == 0) {
+ return ((ExportElementModel) object).getLibelle();
+ } else if (i == 1) {
+ return new Boolean(Boolean.FALSE);
+ } else {
+ return "";
+ }
+ } else {
+ if (i == 0) {
+ return ((ExportChampModel) object).getLibelle();
+ } else if (i == 1) {
+ return new Boolean(((ExportChampModel) object).isSelectionne());
+ } else {
+ return "";
+ }
+ }
+ }
+
+ @Override
+ public void setValueAt(Object value, Object node, int column) {
+ ExportChampModel ecm = (ExportChampModel) node;
+ if (column == 1) {
+ ecm.setSelectionne((Boolean) value);
+ }
+ }
+
+ @Override
+ public int getChildCount(Object parent) {
+ if (parent instanceof ExportElementModel) {
+ ExportElementModel eem = (ExportElementModel) parent;
+ return (eem.getEnfants().size() + eem.getChamps().size());
+ } else if (parent instanceof ExportChampModel) {
+ return 0;
+ } else {
+ return 0;
+ }
+ }
+
+ @Override
+ public Object getChild(Object parent, int index) {
+ if (parent instanceof ExportElementModel) {
+ ExportElementModel eem = (ExportElementModel) parent;
+ if (index < eem.getChamps().size()) {
+ return eem.getChamps().get(index);
+ } else {
+ // les enfants sont après les champs
+ return eem.getEnfants().get(index - eem.getChamps().size());
+ }
+ } else {
+ return null;
+ }
+ }
+
+ @Override
+ public boolean isCellEditable(Object object, int i) {
+ if (object instanceof ExportChampModel) {
+ return true;
+ }//(i==1 && ((ExportChampModel)object).isEditable());
+ else {
+ return false;
+ }
+ }
+
+ @Override
+ public int getIndexOfChild(Object parent, Object child) {
+ if (parent instanceof ExportElementModel) {
+ ExportElementModel p = (ExportElementModel) parent;
+ if (child instanceof ExportChampModel) {
+ ExportChampModel c = (ExportChampModel) child;
+ int i = 0;
+ for (; i < p.getChamps().size(); i++) {
+ ExportChampModel t = (ExportChampModel) p.getChamps().get(i);
+ if (t.getId().equals(c.getId())) {
+ return i;
+ }
+ }
+ } else {
+ ExportElementModel c = (ExportElementModel) child;
+ int i = 0;
+ for (; i < p.getEnfants().size(); i++) {
+ ExportElementModel t = (ExportElementModel) p.getEnfants().get(i);
+ if (t.getId().equals(c.getId())) {
+ return (i + p.getChamps().size());
+ }
+ }
+ }
+ }
+ return -1;
+ }
+
+ @Override
+ public Object getRoot() {
+ return _data.getEnfants().get(0);
+ }
+
+ @Override
+ public int getColumnCount() {
+ return columnNames.length;
+ }
+
+ public int getRowCount2() {
+ int ret = getChampsCount(this._data);
+ if (this._data.getEnfants().size() > 0) {
+ ret += getChildsCount(_data);
+ }
+ return ret;
+ }
+
+ public int getChampsCount(Object parent) {
+ return ((ExportElementModel) parent).getChamps().size();
+ }
+
+ public int getChildsCount(Object parent) {
+ int ret = getChampsCount(parent);
+ for (ExportElementModel eem : ((ExportElementModel) parent).getEnfants()) {
+ ret += getChildsCount(eem);
+ }
+ return ret;
+ }
+
+ @Override
+ public String getColumnName(int arg0) {
+ return columnNames[arg0];
+ }
+
+ public ExportModel getData() {
+ return _data;
+ }
+
+ public void setData(ExportModel data) {
+ this._data = data;
+ }
+ }
+
+ @Override
+ protected JRootPane createRootPane() {
+ KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
+ JRootPane rp = new JRootPane();
+ escapeAction =
+ new AbstractAction("Fermer") {
+
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ setVisible(false);
+ }
+ };
+ rp.registerKeyboardAction(escapeAction, "TOTOTOTO", ks, JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
+ }
+
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.3" maxVersion="1.7" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="1" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="1" attributes="0">
+ <Component id="jScrollPane1" alignment="0" pref="500" max="32767" attributes="0"/>
+ <Component id="jLabel1" alignment="0" pref="500" max="32767" attributes="0"/>
+ <Component id="jLabel2" alignment="0" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="jLabel1" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="jLabel2" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="jScrollPane1" pref="83" max="32767" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Component class="javax.swing.JLabel" name="jLabel1">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="<html>Vous allez ici définir votre profil et l'usage que vous allez faire de XeMeLios.<br/>
En fonction de l'usage choisi, XeMeLios installera les composants nécessaires et les maintiendra à jour.<br/>
Vous pouvez effectuez le choix de votre (vos) usage(s) ci-dessous, et pourrez les redéfinir à tout moment dans le menu Fichier/Configuration, onglet Abonnements</html>"/>
+ </Properties>
+ </Component>
+ <Container class="javax.swing.JScrollPane" name="jScrollPane1">
+ <AuxValues>
+ <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
+ </AuxValues>
+
+ <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
+ <SubComponents>
+ <Component class="javax.swing.JTable" name="tblProfils">
+ <Properties>
+ <Property name="model" type="javax.swing.table.TableModel" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
+ <Connection code="tm" type="code"/>
+ </Property>
+ </Properties>
+ </Component>
+ </SubComponents>
+ </Container>
+ <Component class="javax.swing.JLabel" name="jLabel2">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Liste des profils"/>
+ </Properties>
+ </Component>
+ </SubComponents>
+</Form>
--- /dev/null
+/*
+ * Copyright
+ * 2011 axYus - http://www.axyus.com
+ * 2011 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS_NB.
+ *
+ * XEMELIOS_NB 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 2 of the License, or
+ * (at your option) any later version.
+ *
+ * XEMELIOS_NB 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 Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with XEMELIOS_NB; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.firststart;
+
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.cp.xemelios.updater.installed.InstalledModel;
+import fr.gouv.finances.cp.xemelios.updater.profils.ProfilModel;
+import fr.gouv.finances.cp.xemelios.updater.profils.ProfilsModel;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import java.awt.Component;
+import java.awt.Font;
+import java.util.ArrayList;
+import java.util.Map;
+import javax.swing.JOptionPane;
+import javax.swing.JTable;
+import javax.swing.SwingUtilities;
+import javax.swing.event.TableModelEvent;
+import javax.swing.event.TableModelListener;
+import javax.swing.table.AbstractTableModel;
+import javax.swing.table.DefaultTableCellRenderer;
+import org.apache.log4j.Logger;
+import org.netbeans.spi.wizard.Wizard;
+import org.netbeans.spi.wizard.WizardPanelNavResult;
+
+/**
+ *
+ * @author cmarchand
+ */
+public class PnlFirstAbo extends org.netbeans.spi.wizard.WizardPage {
+ private static final Logger logger = Logger.getLogger(PnlFirstAbo.class);
+ private InstalledModel im;
+ private ProfilsModel profils;
+ private ProfilsTableModel tm;
+ private boolean profilsLoaded = false;
+ static PnlFirstAbo instance = null;
+
+ /** Creates new form PnlFirstAbo */
+ public PnlFirstAbo() {
+ super();
+ instance = this;
+ try {
+ loadInstalled();
+// profils = ProfilsModel.loadModel(MainWindow.getInstance().getEnvProperties().getProperty(Constants.SYS_PROP_MAJ_PROFILS_URL), PnlFirstConfigProxy.client);
+ tm = new ProfilsTableModel(null, im);
+ } catch(Exception ex) {
+ logger.error("<init>",ex);
+ }
+ initComponents();
+ tblProfils.setDefaultRenderer(String.class, new DescCellRenderer(tm));
+ loadProfils();
+ }
+
+ public void testProfilsLoaded() {
+ if(!profilsLoaded)
+ loadProfils();
+ }
+
+ private void loadProfils() {
+ Runnable runner = new Runnable() {
+ @Override
+ public void run() {
+ setBusy(true);
+ try {
+ profils = ProfilsModel.loadModel(MainWindow.getInstance().getEnvProperties().getProperty(Constants.SYS_PROP_MAJ_PROFILS_URL), PnlFirstConfigProxy.client);
+ tm.profils = profils.getProfils();
+ tm.fireTableDataChanged();
+ profilsLoaded = true;
+ } catch(Exception ex) {
+ JOptionPane.showMessageDialog(PnlFirstAbo.instance, "Impossible d'accéder à la définition des profils.\nVeuillez vérifier qu le paramétrage de l'accès à Internet est correct.",ex.getMessage(),JOptionPane.ERROR_MESSAGE);
+ } finally {
+ setBusy(false);
+ }
+ }
+ };
+ SwingUtilities.invokeLater(runner);
+ }
+ public static String getDescription() {
+ return "Configuration de l'usage de Xemelios";
+ }
+
+ private void loadInstalled() throws Exception {
+ im = InstalledModel.readFromFile(MainWindow.getInstance().getEnvProperties().getProperty(Constants.SYS_PROP_INSTALLED_FILENAME));
+ im.setFileLocation(MainWindow.getInstance().getEnvProperties().getProperty(Constants.SYS_PROP_INSTALLED_FILENAME));
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ @SuppressWarnings("unchecked")
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ jLabel1 = new javax.swing.JLabel();
+ jScrollPane1 = new javax.swing.JScrollPane();
+ tblProfils = new javax.swing.JTable();
+ jLabel2 = new javax.swing.JLabel();
+
+ jLabel1.setText("<html>Vous allez ici définir votre profil et l'usage que vous allez faire de XeMeLios.<br/>\nEn fonction de l'usage choisi, XeMeLios installera les composants nécessaires et les maintiendra à jour.<br/>\nVous pouvez effectuez le choix de votre (vos) usage(s) ci-dessous, et pourrez les redéfinir à tout moment dans le menu Fichier/Configuration, onglet Abonnements</html>");
+
+ tblProfils.setModel(tm);
+ jScrollPane1.setViewportView(tblProfils);
+
+ jLabel2.setText("Liste des profils");
+
+ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
+ this.setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
+ .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)
+ .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)
+ .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(jLabel2)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 83, Short.MAX_VALUE)
+ .addContainerGap())
+ );
+ }// </editor-fold>//GEN-END:initComponents
+
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JLabel jLabel1;
+ private javax.swing.JLabel jLabel2;
+ private javax.swing.JScrollPane jScrollPane1;
+ private javax.swing.JTable tblProfils;
+ // End of variables declaration//GEN-END:variables
+
+ private static class ProfilsTableModel extends AbstractTableModel implements TableModelListener {
+ private InstalledModel im;
+ private ArrayList<ProfilModel> profils;
+
+ @Override
+ public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
+ //super.setValueAt(aValue, rowIndex, columnIndex);
+ //logger.debug("rowIndex=" + rowIndex + "/columnIndex=" + columnIndex + "/aValue=" + aValue.toString());
+ switch (columnIndex) {
+ case 0:
+ ProfilModel pm = profils.get(rowIndex);
+ int idxFound = im.getProfilIdx(pm.getId());
+ if (idxFound != InstalledModel.NOT_FOUND) { // profil trouvé
+ if (aValue.equals(false)) { // case doit être décochée
+ im.getProfils().remove(idxFound); // on supprime le profil des profils installés
+ }
+ } else { // profil non trouvé
+ if (aValue.equals(true)) { // case doit être cochée
+ ProfilModel npm = new ProfilModel(pm.getId(), pm.getDescription());
+ im.getProfils().add(npm); // on ajoute le profil à la liste des profils installés
+ }
+ }
+ for (ProfilModel pml : im.getProfils()) {
+ logger.debug("p id=" + pml.getId() + " / desc=" + pml.getDescription());
+ }
+ break;
+ default:
+ break;
+ }
+ }
+
+ @Override
+ public void fireTableCellUpdated(int row, int column) {
+ super.fireTableCellUpdated(row, column);
+ }
+
+ public ProfilsTableModel(ArrayList<ProfilModel> profils, InstalledModel im) {
+ super();
+ this.profils = profils;
+ this.im = im;
+ }
+
+ @Override
+ public int getRowCount() {
+ if(profils!=null)
+ return profils.size();
+ else return 0;
+ }
+
+ @Override
+ public int getColumnCount() {
+ return 2;
+ }
+
+ @Override
+ public Object getValueAt(int rowIndex, int columnIndex) {
+ ProfilModel pm = profils.get(rowIndex);
+ switch (columnIndex) {
+ case 0:
+ if (pm.isRequired()) {
+ // TODO faire comme les autres pm différents de isrequired
+ // Profil requis, on regarde s'il est dans la liste des abonnements
+ // Si présent on ne fait rien, sinon on l'ajoute aux profils installés
+ return true; // required, on retourne true direct si profils requis
+ }
+ if (im == null) {
+ return false; // pas d'entrée profil dans installed.xml
+ } else {
+ for (ProfilModel ipm : im.getProfils()) {
+ if (pm.getId().equals(ipm.getId())) {
+ // ce profil est installé
+ return true;
+ }
+ }
+ }
+ return false;
+ case 1:
+ return pm.getDescription();
+ default:
+ return "unknow columnIndex";
+ }
+ }
+
+ @Override
+ public boolean isCellEditable(int rowIndex, int columnIndex) {
+ switch (columnIndex) {
+ case 0:
+ // profil obligatoire, donc la selection n'est pas modifiable
+ if (profils.get(rowIndex).isRequired()) {
+ return false;
+ } else {
+ return true;
+ }
+ case 1:
+ return false;
+ default:
+ return false;
+ }
+ }
+
+ @Override
+ public Class<?> getColumnClass(int columnIndex) {
+ switch (columnIndex) {
+ case 0:
+ return Boolean.class;
+ case 1:
+ return String.class;
+ default:
+ return super.getColumnClass(columnIndex);
+ }
+ }
+
+ @Override
+ public String getColumnName(int column) {
+ switch (column) {
+ case 0:
+ return "abonnement";
+ case 1:
+ return "description";
+ default:
+ return "unknow column";
+ }
+ }
+
+ @Override
+ public void tableChanged(TableModelEvent e) {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ ArrayList<ProfilModel> getProfils() {
+ return profils;
+ }
+
+ }
+
+ @Override
+ public WizardPanelNavResult allowNext(String stepName, Map settings, Wizard wizard) {
+ try {
+ setBusy(true);
+ im.saveInstalledModel();
+ } catch(Exception ex) {
+ logger.error("writing installed-components.xml",ex);
+ } finally {
+ setBusy(false);
+ }
+ return WizardPanelNavResult.PROCEED;
+ }
+
+ @Override
+ public WizardPanelNavResult allowFinish(String stepName, Map settings, Wizard wizard) {
+ return allowNext(stepName, settings, wizard);
+ }
+
+ private class DescCellRenderer extends DefaultTableCellRenderer {
+ private ProfilsTableModel model;
+ public DescCellRenderer(ProfilsTableModel model) {
+ super();
+ this.model=model;
+ }
+
+ @Override
+ public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
+ Component parentComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
+ Component renderer = parentComponent;
+ if(column==1) {
+ ProfilModel pm = model.getProfils().get(row);
+ if(pm.isRequired()) {
+ Font oldFont = renderer.getFont();
+ Font newFont = oldFont.deriveFont(Font.ITALIC | Font.BOLD); // oldFont.getStyle() |
+ renderer.setFont(newFont);
+ }
+
+ }
+ return renderer;
+ }
+
+ }
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.3" maxVersion="1.7" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="cbxUseProxy" alignment="0" min="-2" max="-2" attributes="0"/>
+ <Group type="102" alignment="0" attributes="0">
+ <Component id="rbInTresor" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="rbOutTresor" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <Component id="jLabel1" alignment="0" pref="500" max="32767" attributes="0"/>
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace min="12" pref="12" max="12" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="1" attributes="0">
+ <EmptySpace min="-2" pref="17" max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="lblUser" alignment="0" min="-2" max="-2" attributes="0"/>
+ <Component id="lblPassword" alignment="0" min="-2" max="-2" attributes="0"/>
+ <Component id="lblDomain" alignment="0" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace min="-2" pref="12" max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="dfProxyUser" alignment="0" pref="343" max="32767" attributes="0"/>
+ <Component id="dfProxyPassword" alignment="0" pref="343" max="32767" attributes="0"/>
+ <Component id="dfDomainName" alignment="0" pref="343" max="32767" attributes="0"/>
+ </Group>
+ </Group>
+ <Component id="chkAuthenticationRequired" alignment="0" min="-2" max="-2" attributes="0"/>
+ <Group type="102" alignment="0" attributes="0">
+ <Component id="jLabel2" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="dfProxyServer" pref="336" max="32767" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="jLabel3" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="dfProxyPort" min="-2" pref="40" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </Group>
+ <Component id="pbTest" alignment="0" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="rbInTresor" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="rbOutTresor" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="cbxUseProxy" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="jLabel2" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="dfProxyServer" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="dfProxyPort" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="jLabel3" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="chkAuthenticationRequired" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="lblUser" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="dfProxyUser" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="lblPassword" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="dfProxyPassword" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="lblDomain" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="dfDomainName" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="pbTest" min="-2" max="-2" attributes="0"/>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Component id="jLabel1" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="32767" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Component class="javax.swing.JCheckBox" name="cbxUseProxy">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="J'utilise un proxy pour accéder à internet*"/>
+ <Property name="enabled" type="boolean" value="false"/>
+ <Property name="name" type="java.lang.String" value="is.use.proxy" noResource="true"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="cbxUseProxyActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JLabel" name="jLabel1">
+ <Properties>
+ <Property name="text" type="java.lang.String" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
+ <Connection code="AVAILABILITY" type="code"/>
+ </Property>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JRadioButton" name="rbInTresor">
+ <Properties>
+ <Property name="selected" type="boolean" value="true"/>
+ <Property name="text" type="java.lang.String" value="Je fais partie du réseau du trésor"/>
+ <Property name="name" type="java.lang.String" value="in.tresor" noResource="true"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="rbInTresorActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JRadioButton" name="rbOutTresor">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Je suis en dehors du réseau du trésor"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="rbOutTresorActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JLabel" name="jLabel2">
+ <Properties>
+ <Property name="labelFor" type="java.awt.Component" editor="org.netbeans.modules.form.ComponentChooserEditor">
+ <ComponentRef name="dfProxyServer"/>
+ </Property>
+ <Property name="text" type="java.lang.String" value="Serveur"/>
+ <Property name="enabled" type="boolean" value="false"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JTextField" name="dfProxyServer">
+ <Properties>
+ <Property name="enabled" type="boolean" value="false"/>
+ <Property name="name" type="java.lang.String" value="proxy.server" noResource="true"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JLabel" name="jLabel3">
+ <Properties>
+ <Property name="labelFor" type="java.awt.Component" editor="org.netbeans.modules.form.ComponentChooserEditor">
+ <ComponentRef name="dfProxyPort"/>
+ </Property>
+ <Property name="text" type="java.lang.String" value="Port"/>
+ <Property name="enabled" type="boolean" value="false"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JTextField" name="dfProxyPort">
+ <Properties>
+ <Property name="enabled" type="boolean" value="false"/>
+ <Property name="name" type="java.lang.String" value="proxy.port" noResource="true"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JCheckBox" name="chkAuthenticationRequired">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Mon serveur proxy requiert une authentification"/>
+ <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
+ <Border info="org.netbeans.modules.form.compat2.border.EmptyBorderInfo">
+ <EmptyBorder bottom="0" left="0" right="0" top="0"/>
+ </Border>
+ </Property>
+ <Property name="enabled" type="boolean" value="false"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="chkAuthenticationRequiredActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JLabel" name="lblUser">
+ <Properties>
+ <Property name="labelFor" type="java.awt.Component" editor="org.netbeans.modules.form.ComponentChooserEditor">
+ <ComponentRef name="dfProxyUser"/>
+ </Property>
+ <Property name="text" type="java.lang.String" value="Utilisateur"/>
+ <Property name="enabled" type="boolean" value="false"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JTextField" name="dfProxyUser">
+ <Properties>
+ <Property name="enabled" type="boolean" value="false"/>
+ <Property name="name" type="java.lang.String" value="proxy.user" noResource="true"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JPasswordField" name="dfProxyPassword">
+ <Properties>
+ <Property name="enabled" type="boolean" value="false"/>
+ <Property name="name" type="java.lang.String" value="proxy.password" noResource="true"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JLabel" name="lblPassword">
+ <Properties>
+ <Property name="labelFor" type="java.awt.Component" editor="org.netbeans.modules.form.ComponentChooserEditor">
+ <ComponentRef name="dfProxyPassword"/>
+ </Property>
+ <Property name="text" type="java.lang.String" value="Mot de passe"/>
+ <Property name="enabled" type="boolean" value="false"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JLabel" name="lblDomain">
+ <Properties>
+ <Property name="labelFor" type="java.awt.Component" editor="org.netbeans.modules.form.ComponentChooserEditor">
+ <ComponentRef name="dfDomainName"/>
+ </Property>
+ <Property name="text" type="java.lang.String" value="Domaine Windows"/>
+ <Property name="enabled" type="boolean" value="false"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JTextField" name="dfDomainName">
+ <Properties>
+ <Property name="enabled" type="boolean" value="false"/>
+ <Property name="name" type="java.lang.String" value="proxy.domain" noResource="true"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JButton" name="pbTest">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Tester"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbTestActionPerformed"/>
+ </Events>
+ </Component>
+ </SubComponents>
+</Form>
--- /dev/null
+/*
+ * Copyright
+ * 2010 axYus - http://www.axyus.com
+ * 2010 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS_NB.
+ *
+ * XEMELIOS_NB 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 2 of the License, or
+ * (at your option) any later version.
+ *
+ * XEMELIOS_NB 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 Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with XEMELIOS_NB; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+
+
+package fr.gouv.finances.cp.xemelios.ui.firststart;
+
+import java.net.InetAddress;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Map;
+import javax.swing.ButtonGroup;
+import javax.swing.JOptionPane;
+import org.apache.commons.httpclient.Credentials;
+import org.apache.commons.httpclient.HostConfiguration;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpMethod;
+import org.apache.commons.httpclient.NTCredentials;
+import org.apache.commons.httpclient.UsernamePasswordCredentials;
+import org.apache.commons.httpclient.auth.AuthScope;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.log4j.Logger;
+import org.netbeans.spi.wizard.Wizard;
+import org.netbeans.spi.wizard.WizardPanelNavResult;
+
+/**
+ *
+ * @author cmarchand
+ */
+public class PnlFirstConfigProxy extends org.netbeans.spi.wizard.WizardPage {
+ private static final transient String AVAILABILITY = "<html>* : cette information est disponible auprès de votre assistance utilisateur, de votre SAU ou de votre administrateur réseau.</html>";
+ private static final transient String URL_TO_REACH = "http://xemelios.org/index.html";
+ private static final Logger logger = Logger.getLogger(PnlFirstConfigProxy.class);
+ private ButtonGroup bgInTresor;
+ static HttpClient client;
+
+ /** Creates new form PnlFirstConfigProxy */
+ public PnlFirstConfigProxy() {
+ initComponents();
+ bgInTresor = new ButtonGroup();
+ bgInTresor.add(rbInTresor);
+ bgInTresor.add(rbOutTresor);
+ }
+ public static String getDescription() {
+ return "Configuration de l'accès à internet";
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ @SuppressWarnings("unchecked")
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ cbxUseProxy = new javax.swing.JCheckBox();
+ jLabel1 = new javax.swing.JLabel();
+ rbInTresor = new javax.swing.JRadioButton();
+ rbOutTresor = new javax.swing.JRadioButton();
+ jLabel2 = new javax.swing.JLabel();
+ dfProxyServer = new javax.swing.JTextField();
+ jLabel3 = new javax.swing.JLabel();
+ dfProxyPort = new javax.swing.JTextField();
+ chkAuthenticationRequired = new javax.swing.JCheckBox();
+ lblUser = new javax.swing.JLabel();
+ dfProxyUser = new javax.swing.JTextField();
+ dfProxyPassword = new javax.swing.JPasswordField();
+ lblPassword = new javax.swing.JLabel();
+ lblDomain = new javax.swing.JLabel();
+ dfDomainName = new javax.swing.JTextField();
+ pbTest = new javax.swing.JButton();
+
+ cbxUseProxy.setText("J'utilise un proxy pour accéder à internet*");
+ cbxUseProxy.setEnabled(false);
+ cbxUseProxy.setName("is.use.proxy"); // NOI18N
+ cbxUseProxy.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ cbxUseProxyActionPerformed(evt);
+ }
+ });
+
+ jLabel1.setText(AVAILABILITY);
+
+ rbInTresor.setSelected(true);
+ rbInTresor.setText("Je fais partie du réseau du trésor");
+ rbInTresor.setName("in.tresor"); // NOI18N
+ rbInTresor.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ rbInTresorActionPerformed(evt);
+ }
+ });
+
+ rbOutTresor.setText("Je suis en dehors du réseau du trésor");
+ rbOutTresor.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ rbOutTresorActionPerformed(evt);
+ }
+ });
+
+ jLabel2.setLabelFor(dfProxyServer);
+ jLabel2.setText("Serveur");
+ jLabel2.setEnabled(false);
+
+ dfProxyServer.setEnabled(false);
+ dfProxyServer.setName("proxy.server"); // NOI18N
+
+ jLabel3.setLabelFor(dfProxyPort);
+ jLabel3.setText("Port");
+ jLabel3.setEnabled(false);
+
+ dfProxyPort.setEnabled(false);
+ dfProxyPort.setName("proxy.port"); // NOI18N
+
+ chkAuthenticationRequired.setText("Mon serveur proxy requiert une authentification");
+ chkAuthenticationRequired.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
+ chkAuthenticationRequired.setEnabled(false);
+ chkAuthenticationRequired.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ chkAuthenticationRequiredActionPerformed(evt);
+ }
+ });
+
+ lblUser.setLabelFor(dfProxyUser);
+ lblUser.setText("Utilisateur");
+ lblUser.setEnabled(false);
+
+ dfProxyUser.setEnabled(false);
+ dfProxyUser.setName("proxy.user"); // NOI18N
+
+ dfProxyPassword.setEnabled(false);
+ dfProxyPassword.setName("proxy.password"); // NOI18N
+
+ lblPassword.setLabelFor(dfProxyPassword);
+ lblPassword.setText("Mot de passe");
+ lblPassword.setEnabled(false);
+
+ lblDomain.setLabelFor(dfDomainName);
+ lblDomain.setText("Domaine Windows");
+ lblDomain.setEnabled(false);
+
+ dfDomainName.setEnabled(false);
+ dfDomainName.setName("proxy.domain"); // NOI18N
+
+ pbTest.setText("Tester");
+ pbTest.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbTestActionPerformed(evt);
+ }
+ });
+
+ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
+ this.setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(cbxUseProxy)
+ .addGroup(layout.createSequentialGroup()
+ .addComponent(rbInTresor)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(rbOutTresor))
+ .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)
+ .addGroup(layout.createSequentialGroup()
+ .addGap(12, 12, 12)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
+ .addGap(17, 17, 17)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(lblUser)
+ .addComponent(lblPassword)
+ .addComponent(lblDomain))
+ .addGap(12, 12, 12)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(dfProxyUser, javax.swing.GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE)
+ .addComponent(dfProxyPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE)
+ .addComponent(dfDomainName, javax.swing.GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE)))
+ .addComponent(chkAuthenticationRequired)
+ .addGroup(layout.createSequentialGroup()
+ .addComponent(jLabel2)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(dfProxyServer, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(jLabel3)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(dfProxyPort, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))))
+ .addComponent(pbTest))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(rbInTresor)
+ .addComponent(rbOutTresor))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(cbxUseProxy)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(jLabel2)
+ .addComponent(dfProxyServer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addComponent(dfProxyPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addComponent(jLabel3))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(chkAuthenticationRequired)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(lblUser)
+ .addComponent(dfProxyUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(lblPassword)
+ .addComponent(dfProxyPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(lblDomain)
+ .addComponent(dfDomainName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(pbTest)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(jLabel1)
+ .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ );
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void cbxUseProxyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbxUseProxyActionPerformed
+ enableProxyControls(cbxUseProxy.isSelected());
+ }//GEN-LAST:event_cbxUseProxyActionPerformed
+
+ private void chkAuthenticationRequiredActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkAuthenticationRequiredActionPerformed
+ boolean selected = chkAuthenticationRequired.isSelected();
+ enableAuthenticationControls(selected);
+}//GEN-LAST:event_chkAuthenticationRequiredActionPerformed
+
+ private void pbTestActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbTestActionPerformed
+ runTest();
+}//GEN-LAST:event_pbTestActionPerformed
+
+ private void rbInTresorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbInTresorActionPerformed
+ enableTresor(true);
+ }//GEN-LAST:event_rbInTresorActionPerformed
+
+ private void rbOutTresorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbOutTresorActionPerformed
+ enableTresor(false);
+ }//GEN-LAST:event_rbOutTresorActionPerformed
+
+ private void enableProxyControls(boolean selected) {
+ dfProxyServer.setEnabled(selected);
+ dfProxyPort.setEnabled(selected);
+ chkAuthenticationRequired.setEnabled(selected);
+// enableAuthenticationControls(selected);
+// if(!selected) rbInTresor.doClick();
+// rbInTresor.setEnabled(selected);
+// rbOutTresor.setEnabled(selected);
+ }
+ private void enableTresor(boolean selected) {
+ if(selected) {
+// dfProxyServer.setText("proxy.bercy.cp");
+// dfProxyPort.setText("3128");
+ chkAuthenticationRequired.setSelected(false);
+ chkAuthenticationRequiredActionPerformed(null);
+ }
+// dfProxyServer.setEnabled(!selected);
+// dfProxyPort.setEnabled(!selected);
+ cbxUseProxy.setEnabled(!selected);
+// chkAuthenticationRequired.setEnabled(!selected);
+ }
+ private void enableAuthenticationControls(boolean selected) {
+ dfProxyUser.setEnabled(selected);
+ dfProxyPassword.setEnabled(selected);
+ dfDomainName.setEnabled(selected);
+ if(!selected) {
+ dfProxyUser.setText("");
+ dfProxyPassword.setText("");
+ dfDomainName.setText("");
+ }
+ }
+ private void runTest() {
+ String proxyHost = null;
+ String proxyPort = null;
+ String proxyUser = null;
+ String proxyPasswd = null;
+ String domainName = null;
+ int intProxyPort = 0;
+
+ if(rbInTresor.isSelected()) {
+ proxyHost = "proxy.bercy.cp";
+ proxyPort = "3128";
+ } else {
+ if(dfProxyServer.getText()!=null && dfProxyServer.getText().length()>0) proxyHost = dfProxyServer.getText();
+ if(dfProxyPort.getText()!=null && dfProxyPort.getText().length()>0) proxyPort = dfProxyPort.getText();
+ if(dfProxyUser.getText()!=null && dfProxyUser.getText().length()>0) proxyUser = dfProxyUser.getText();
+ if(dfProxyPassword.getPassword().length>0) proxyPasswd = new String(dfProxyPassword.getPassword());
+ }
+ if(proxyPort!=null) {
+ try {
+ intProxyPort = Integer.parseInt(proxyPort);
+ } catch(NumberFormatException nfEx) {
+ JOptionPane.showMessageDialog(this,proxyPort+" n'est pas un numéro de port valide.","ERREUR",JOptionPane.ERROR_MESSAGE);
+ return;
+ }
+ }
+ if(dfDomainName.getText()!=null && dfDomainName.getText().length()>0) domainName = dfDomainName.getText();
+ URL url = null;
+ try {
+ url = new URL(URL_TO_REACH);
+ } catch(MalformedURLException muEx) {
+ JOptionPane.showMessageDialog(this,"URL non valide : "+URL_TO_REACH,"ERROR",JOptionPane.ERROR_MESSAGE);
+ return;
+ }
+
+// METHOD WITH APACHE COMMONS-HTTPCLIENT
+ HttpClient localClient = new HttpClient();
+ HostConfiguration hc = new HostConfiguration();
+ if(proxyHost!=null) {
+ hc.setProxy(proxyHost,intProxyPort);
+ localClient.setHostConfiguration(hc);
+ }
+ if(proxyUser!=null) {
+ Credentials creds = null;
+ if(domainName!=null && domainName.length()>0) {
+ String hostName = "127.0.0.1";
+ try {
+ InetAddress ip = InetAddress.getByName("127.0.0.1");
+ hostName = ip.getHostName();
+ } catch(Exception ex) {
+ logger.error("",ex);
+ }
+ creds = new NTCredentials(proxyUser, proxyPasswd, hostName, domainName);
+ } else {
+ creds = new UsernamePasswordCredentials(proxyUser, proxyPasswd);
+ }
+ localClient.getState().setProxyCredentials(AuthScope.ANY, creds);
+ }
+ HttpMethod meth = new GetMethod(URL_TO_REACH);
+ int ret = 0;
+ try {
+ setBusy(true);
+ ret = localClient.executeMethod(meth);
+ if(ret>300) {
+ // an error occured
+ JOptionPane.showMessageDialog(this," "+ret+" : "+meth.getStatusText(),"ERREUR",JOptionPane.ERROR_MESSAGE);
+ return;
+ } else {
+ String resp = meth.getResponseBodyAsString();
+ JOptionPane.showMessageDialog(this,"Connexion réussie !","Proxy correctement configuré...",JOptionPane.INFORMATION_MESSAGE);
+ }
+ } catch(Throwable t) {
+ JOptionPane.showMessageDialog(this,t.getMessage(),t.getClass().getName(),JOptionPane.ERROR_MESSAGE);
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ @Override
+ public WizardPanelNavResult allowNext(String stepName, Map settings, Wizard wizard) {
+ // On génère un objet HttpClient correctement paramétré pour la suite
+ String proxyHost = null;
+ String proxyPort = null;
+ String proxyUser = null;
+ String proxyPasswd = null;
+ String domainName = null;
+ int intProxyPort = 80;
+
+ if(rbInTresor.isSelected()) {
+ proxyHost = "proxy.bercy.cp";
+ proxyPort = "3128";
+ getWizardDataMap().put("in.tresor", Boolean.TRUE);
+ } else {
+ if(dfProxyServer.getText()!=null && dfProxyServer.getText().length()>0) {
+ proxyHost = dfProxyServer.getText();
+ getWizardDataMap().put("proxy.server", dfProxyServer.getText());
+ getWizardDataMap().put("is.use.proxy", Boolean.TRUE);
+ } else {
+ getWizardDataMap().remove("proxy.server");
+ }
+ if(dfProxyPort.getText()!=null && dfProxyPort.getText().length()>0) {
+ proxyPort = dfProxyPort.getText();
+ getWizardDataMap().put("proxy.port", dfProxyPort.getText());
+ } else {
+ getWizardDataMap().remove("proxy.port");
+ }
+ if(dfProxyUser.getText()!=null && dfProxyUser.getText().length()>0) {
+ proxyUser = dfProxyUser.getText();
+ getWizardDataMap().put("proxy.user", dfProxyUser.getText());
+ } else {
+ getWizardDataMap().remove("proxy.user");
+ }
+ if(dfProxyPassword.getPassword().length>0) {
+ proxyPasswd = new String(dfProxyPassword.getPassword());
+ getWizardDataMap().put("proxy.password", proxyPasswd);
+ }
+ }
+ if(proxyPort!=null) {
+ try {
+ intProxyPort = Integer.parseInt(proxyPort);
+ } catch(NumberFormatException nfEx) {
+ setProblem(proxyPort+" n'est pas un numéro de port valide.");
+ return WizardPanelNavResult.REMAIN_ON_PAGE;
+ }
+ }
+ if(dfDomainName.getText()!=null && dfDomainName.getText().length()>0) {
+ domainName = dfDomainName.getText();
+ getWizardDataMap().put("proxy.domain", dfDomainName.getText());
+ } else {
+ getWizardDataMap().remove("proxy.domain");
+ }
+
+// METHOD WITH APACHE COMMONS-HTTPCLIENT
+ HttpClient httpClient = new HttpClient();
+ HostConfiguration hc = new HostConfiguration();
+ if(proxyHost!=null) {
+ hc.setProxy(proxyHost,intProxyPort);
+ httpClient.setHostConfiguration(hc);
+ }
+ if(proxyUser!=null) {
+ Credentials creds = null;
+ if(domainName!=null && domainName.length()>0) {
+ String hostName = "127.0.0.1";
+ try {
+ InetAddress ip = InetAddress.getByName("127.0.0.1");
+ hostName = ip.getHostName();
+ } catch(Exception ex) {
+ logger.error("",ex);
+ }
+ creds = new NTCredentials(proxyUser, proxyPasswd, hostName, domainName);
+ } else {
+ creds = new UsernamePasswordCredentials(proxyUser, proxyPasswd);
+ }
+ httpClient.getState().setProxyCredentials(AuthScope.ANY, creds);
+ }
+ getWizardDataMap().put("http.client", httpClient);
+ client=httpClient;
+ if(PnlFirstAbo.instance!=null)
+ PnlFirstAbo.instance.testProfilsLoaded();
+ return WizardPanelNavResult.PROCEED;
+ }
+
+ @Override
+ public WizardPanelNavResult allowFinish(String stepName, Map settings, Wizard wizard) {
+ return allowNext(stepName, settings, wizard);
+ }
+
+
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JCheckBox cbxUseProxy;
+ private javax.swing.JCheckBox chkAuthenticationRequired;
+ private javax.swing.JTextField dfDomainName;
+ private javax.swing.JPasswordField dfProxyPassword;
+ private javax.swing.JTextField dfProxyPort;
+ private javax.swing.JTextField dfProxyServer;
+ private javax.swing.JTextField dfProxyUser;
+ private javax.swing.JLabel jLabel1;
+ private javax.swing.JLabel jLabel2;
+ private javax.swing.JLabel jLabel3;
+ private javax.swing.JLabel lblDomain;
+ private javax.swing.JLabel lblPassword;
+ private javax.swing.JLabel lblUser;
+ private javax.swing.JButton pbTest;
+ private javax.swing.JRadioButton rbInTresor;
+ private javax.swing.JRadioButton rbOutTresor;
+ // End of variables declaration//GEN-END:variables
+
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.3" maxVersion="1.7" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="jLabel1" pref="507" max="32767" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Component id="jLabel1" min="-2" max="-2" attributes="0"/>
+ <EmptySpace pref="106" max="32767" attributes="1"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Component class="javax.swing.JLabel" name="jLabel1">
+ <Properties>
+ <Property name="text" type="java.lang.String" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
+ <Connection code="MSG" type="code"/>
+ </Property>
+ </Properties>
+ </Component>
+ </SubComponents>
+</Form>
--- /dev/null
+/*
+ * Copyright
+ * 2010 axYus - http://www.axyus.com
+ * 2010 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS_NB.
+ *
+ * XEMELIOS_NB 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 2 of the License, or
+ * (at your option) any later version.
+ *
+ * XEMELIOS_NB 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 Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with XEMELIOS_NB; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.firststart;
+
+import java.util.Map;
+import org.netbeans.spi.wizard.Wizard;
+import org.netbeans.spi.wizard.WizardPanelNavResult;
+
+/**
+ * Présente ce qui va se passer
+ * @author cmarchand
+ */
+public class PnlPresentation extends org.netbeans.spi.wizard.WizardPage {
+ private static final transient String MSG = "<html>Bienvenue dans XéMéLios !<br/><br/>" +
+ "C'est votre premier démarrage de XéMéLios. Pour pouvoir " +
+ "travailler efficacement avec XéMéLios, il vous vaut " +
+ "configurer certaines choses :<ul>" +
+ "<li>la façon dont vous accédez à internet,</li>" +
+ "<li>l'usage que vous prévoyez de faire de XéMéLios,</li>" +
+ "<li>et quelques informations sur votre environnement...</li></ul>"+
+ "Bon démarrage !</html>";
+
+ /** Creates new form PnlPresentation */
+ public PnlPresentation() {
+ initComponents();
+ }
+ public static String getDescription() {
+ return "Présentation de la configuration";
+ }
+
+ @Override
+ public WizardPanelNavResult allowFinish(String stepName, Map settings, Wizard wizard) {
+ return WizardPanelNavResult.REMAIN_ON_PAGE;
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ @SuppressWarnings("unchecked")
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ jLabel1 = new javax.swing.JLabel();
+
+ jLabel1.setText(MSG);
+
+ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
+ this.setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 507, Short.MAX_VALUE)
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(jLabel1)
+ .addContainerGap(106, Short.MAX_VALUE))
+ );
+ }// </editor-fold>//GEN-END:initComponents
+
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JLabel jLabel1;
+ // End of variables declaration//GEN-END:variables
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.ia;
+
+import java.awt.Color;
+import java.awt.Font;
+import java.awt.FontMetrics;
+import java.awt.Graphics;
+import java.awt.Image;
+
+import javax.swing.ImageIcon;
+import javax.swing.JComponent;
+
+import fr.gouv.finances.cp.utils.ui.IhmFactory;
+import fr.gouv.finances.dgfip.xemelios.ui.ImageResources;
+
+/**
+ * Draws results
+ *
+ * @author chm
+ */
+public class DisplayScore extends JComponent {
+
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 3256725091285872945L;
+
+ private Grille laGrille;
+
+ private Font laFont = new Font("Arial", Font.BOLD, 16);
+
+ private FontMetrics fm = getFontMetrics(laFont);
+
+ private Image offscreenImg;
+
+ private Graphics offscreenG;
+
+ private static final String POINTS = "POINTS";
+
+ private static final String LINES = "LIGNES";
+
+ private static final String LEVEL = "NIVEAU";
+
+ private static final String NEXT = "SUIVANTE";
+
+ public DisplayScore(Grille pGrille) {
+ super();
+ setBackground(Color.black);
+ laGrille = pGrille;
+ laGrille.ds = this;
+ setPreferredSize(pGrille.getPreferredSize());
+ }
+ @Override
+ public void update(Graphics g) {
+ paint(g);
+ }
+ @Override
+ public void paint(Graphics g) {
+ if (laGrille == null)
+ return;
+
+ if (offscreenImg == null) {
+ offscreenImg = createImage(this.getSize().width, this.getSize().height);
+ offscreenG = offscreenImg.getGraphics();
+ }
+
+ String s;
+
+ offscreenG.setColor(Color.black);
+ offscreenG.fillRect(0, 0, this.getSize().width, this.getSize().height);
+
+ offscreenG.setFont(laFont);
+
+ // Affichage des Points
+ offscreenG.setColor(new Color(0, 128, 224));
+ offscreenG.drawString(POINTS, (this.getSize().width - fm.stringWidth(POINTS)) / 2, 15);
+ s = "" + laGrille.cptPoints;
+ offscreenG.drawString(s, (this.getSize().width - fm.stringWidth(s)) / 2, 30);
+
+ // Affichage des Lignes
+ offscreenG.setColor(new Color(0, 192, 0));
+ offscreenG.drawString(LINES, (this.getSize().width - fm.stringWidth(LINES)) / 2, 50);
+ s = "" + laGrille.cptLines;
+ offscreenG.drawString(s, (this.getSize().width - fm.stringWidth(s)) / 2, 65);
+
+ // Affichage du niveau
+ offscreenG.setColor(Color.yellow);
+ offscreenG.drawString(LEVEL, (this.getSize().width - fm.stringWidth(LEVEL)) / 2, 85);
+ s = "" + laGrille.level;
+ offscreenG.drawString(s, (this.getSize().width - fm.stringWidth(s)) / 2, 100);
+
+ if (laGrille.gameFinished) {
+ ImageIcon ii = IhmFactory.getIconFromResource(ImageResources.EDITEUR);
+ offscreenG.drawImage(ii.getImage(), (getWidth() - ii.getIconWidth()) / 2, getHeight()-ii.getIconHeight()-5, ii.getIconWidth(), ii.getIconHeight(), this);
+ } else {
+ // Affichage de la prochaine pièce
+ offscreenG.setColor(Color.white);
+ offscreenG.drawString(NEXT, (this.getSize().width - fm.stringWidth(NEXT)) / 2, 140);
+ // La pièce est créée et centrée
+ Piece p = new Piece(laGrille.nextOne);
+ p.firstRotation();
+ p.reset((this.getSize().width - p.getWidth() * Piece.SQUARE_SIZE) / 2, 155);
+ p.display(offscreenG);
+ }
+
+ // Transfert du buffer vers l'écran
+ g.drawImage(offscreenImg, 0, 0, this);
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui.ia;
+
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.FontMetrics;
+import java.awt.Graphics;
+import java.awt.Image;
+import java.awt.event.FocusEvent;
+import java.awt.event.FocusListener;
+import java.awt.event.KeyEvent;
+import java.awt.event.KeyListener;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+
+import javax.swing.JComponent;
+
+/**
+ * The board
+ */
+public class Grille extends JComponent implements Runnable, FocusListener, KeyListener {
+
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 3257291348414771511L;
+ public static final int DEFAULT_WIDTH=10, DEFAULT_HEIGHT=20;
+ public static final int DIRECTION_UP=-1, DIRECTION_DOWN=1;
+
+ private Thread m_Grille; // for animation
+ private Color[][] grids;
+ private Color backColor;
+ private Piece[] pieces; // pieces that can move down
+ private Piece currentPiece;
+ public Piece nextOne;
+ private int posX, posY; // position of currentPiece
+ private int gridWidth, gridHeight;
+ private int idCurrent, idNextOne;
+ private boolean paintAll;
+ private boolean paintPiece;
+ private boolean gameRunning;
+ private boolean gameOverPainted;
+ public boolean gameFinished;
+ public int cptLines, cptPoints;
+ public int bonus, level;
+ private int direction; // +1 : down, -1 : up
+
+ protected DisplayScore ds = null; // the score displayer, to notify it
+
+ private boolean finished=false; // controls thread execution
+
+ // double-buffering
+ private Image offscreenImg;
+ private Image backImg;
+ private Graphics offscreenG;
+
+ public Grille(Piece[] lp) {
+ this(lp,DEFAULT_WIDTH, DEFAULT_HEIGHT);
+ }
+ /**
+ * Creates a new Grid
+ * @param lp
+ * @param w grid width
+ * @param h grid height
+ */
+ public Grille(Piece[] lp,int w, int h) {
+ super();
+ gridWidth = w;
+ gridHeight = h;
+ direction = DIRECTION_DOWN;
+ grids = new Color[gridHeight][gridWidth];
+ pieces = lp;
+ selectPiece();
+ gameRunning = false;
+ gameFinished = false;
+ paintAll = false;
+ cptLines = cptPoints = 0;
+ level = 1;
+ backColor = Color.darkGray;
+ gameOverPainted = false;
+ initListeners();
+ }
+
+ /**
+ * Selects next piece
+ */
+ private void selectPiece() {
+ if (nextOne == null) {
+ // creates 2 new pieces
+ idCurrent = (int)(Math.random() * pieces.length);
+ idNextOne = (int)(Math.random() * pieces.length);
+ currentPiece = new Piece(pieces[idCurrent]);
+ nextOne = new Piece(pieces[idNextOne]);
+ } else {
+ // switches next to current
+ currentPiece = nextOne;
+ idCurrent = idNextOne;
+ // creates the next one
+ idNextOne = (int)(Math.random() * pieces.length);
+ nextOne = new Piece(pieces[idNextOne]);
+ }
+ resetPiece();
+ bonus = 20;
+ paintPiece = true;
+ }
+
+ /**
+ * Calculates if piece <p>p</p> can be displayed at<p>(x,y)</p>
+ * @param x
+ * @param y
+ * @param p
+ * @return
+ */
+ private boolean canDisplayAt(int x, int y, Piece p) {
+ if (y < 0 || y + p.getHeight() > gridHeight)
+ return false;
+ if (x < 0 || x + p.getWidth() > gridWidth)
+ return false;
+
+ int mask = 0x8000;
+
+ for (int i = 0; i < p.getHeight(); i++) {
+ for (int j = 0; j < p.getWidth(); j++, mask >>= 1)
+ if (((p.getVal() & mask) != 0) && grids[y + i][x + j] != null)
+ return false;
+ // move mask to next line
+ mask >>= 4 - p.getWidth();
+ }
+ return true;
+
+ }
+
+ /**
+ * Calculates if current piece can be displayed at <p>(x,y)</p>
+ * @param x
+ * @param y
+ * @return
+ */
+ private boolean canDisplayAt(int x, int y) {
+ return canDisplayAt(x, y, currentPiece);
+ }
+
+ /**
+ * Reverses game direction
+ */
+ private void reverseGame() {
+ Color buffer;
+ int i, j;
+
+ for (i = 0; i < gridHeight / 2; i++) {
+ for (j = 0; j < gridWidth; j++) {
+ buffer = grids[i][j];
+ grids[i][j] = grids[gridHeight - 1 - i][j];
+ grids[gridHeight - 1 - i][j] = buffer;
+ }
+ }
+ }
+
+ private void resetPiece() {
+ posX = (gridWidth / 2) - (currentPiece.getWidth() / 2);
+ if (direction == 1) {
+ posY = 0;
+ } else {
+ posY = gridHeight - currentPiece.getHeight();
+ }
+ currentPiece.reset(posX * Piece.SQUARE_SIZE, posY * Piece.SQUARE_SIZE);
+ }
+
+ /**
+ * Drops filled lines, computes score, etc...
+ */
+ private void pieceStop() {
+ int i, j, mask = 0x8000;
+ int scr_i, scr_j;
+ int oldCptLines = cptLines;
+
+ // update grid
+ for (i = 0; i < currentPiece.getHeight(); i++) {
+ for (j = 0; j < currentPiece.getWidth(); j++, mask >>= 1) {
+ if ((currentPiece.getVal() & mask) != 0)
+ grids[posY + i][posX + j] = pieces[idCurrent].getColor();
+ }
+ // move mask to next line
+ mask >>= 4 - currentPiece.getWidth();
+ }
+
+ // incs score
+ cptPoints += 5;
+
+ if (direction == DIRECTION_DOWN) {
+ // check lines
+ for (i = posY; i < posY + currentPiece.getHeight(); i++) {
+ for (j = 0; j < gridWidth; j++) {
+ if (grids[i][j] == null)
+ break;
+ }
+ // line is filled
+ if (j == gridWidth) {
+ // scrolls down
+ for (scr_i = i; scr_i > 0; scr_i--) {
+ for (scr_j = 0; scr_j < gridWidth; scr_j++) {
+ grids[scr_i][scr_j] = grids[scr_i - 1][scr_j];
+ }
+ }
+ for (scr_j = 0; scr_j < gridWidth; scr_j++) {
+ grids[0][scr_j] = null;
+ }
+ cptLines++;
+ }
+ }
+ } else {
+ for (i = posY + currentPiece.getHeight() - 1; i >= posY; i--) {
+ for (j = 0; j < gridWidth; j++) {
+ if (grids[i][j] == null)
+ break;
+ }
+ if (j == gridWidth) {
+ for (scr_i = i; scr_i < gridHeight - 1; scr_i++) {
+ for (scr_j = 0; scr_j < gridWidth; scr_j++) {
+ grids[scr_i][scr_j] = grids[scr_i + 1][scr_j];
+ }
+ }
+ for (scr_j = 0; scr_j < gridWidth; scr_j++) {
+ grids[gridHeight - 1][scr_j] = null;
+ }
+ cptLines++;
+ }
+ }
+ }
+ if (oldCptLines != cptLines) {
+ // 10 points a line
+ cptPoints += (cptLines - oldCptLines) * 10;
+ // 100 points a four
+ if (cptLines - oldCptLines == 4)
+ cptPoints += 100;
+ }
+
+ // max level = 12
+ if (level < 12 && cptPoints >= 1000 * level)
+ level++;
+
+ paintAll = true;
+ paintPiece = false;
+ repaint();
+ }
+ @Override
+ public Dimension getMinimumSize() {
+ return getPreferredSize();
+ }
+ @Override
+ public Dimension getPreferredSize() {
+ return new Dimension(Piece.SQUARE_SIZE*gridWidth,Piece.SQUARE_SIZE*gridHeight);
+ }
+ public void restartGame() {
+ selectPiece();
+ gameRunning = true;
+ gameFinished = false;
+ paintAll = true;
+ cptLines = cptPoints = 0;
+ level = 1;
+ gameOverPainted = false;
+ int i, j;
+ for (i = 0; i < gridHeight; i++)
+ for (j = 0; j < gridWidth; j++)
+ grids[i][j] = null;
+ }
+
+ public void start() {
+ if (m_Grille == null) {
+ m_Grille = new Thread(this);
+ finished=false;
+ m_Grille.start();
+ }
+ }
+
+ public void stop() {
+ if (m_Grille != null) {
+ finished=true;
+ m_Grille = null;
+ }
+ }
+ @Override
+ public synchronized void update(Graphics g) {
+ paint(g);
+ }
+
+ public synchronized void paintPiece(boolean effPiece) {
+ if (offscreenImg == null)
+ return;
+
+ if (effPiece)
+ currentPiece.erase(offscreenG, backColor);
+ currentPiece.display(offscreenG);
+ }
+
+ private synchronized void paintGameOver() {
+ Font laFont = new Font("Arial", Font.BOLD, 20);
+ FontMetrics fm = getFontMetrics(laFont);
+ Color c = new Color(0, 128, 224);
+
+ for (int i = 0; i < gridHeight; i++)
+ for (int j = 0; j < gridWidth; j++) {
+ offscreenG.setColor(c);
+ offscreenG.fill3DRect(j * Piece.SQUARE_SIZE, i * Piece.SQUARE_SIZE, Piece.SQUARE_SIZE, Piece.SQUARE_SIZE, true);
+ }
+
+ offscreenG.setColor(Color.yellow);
+ offscreenG.setFont(laFont);
+ offscreenG.drawString("Partie", (this.getSize().width - fm.stringWidth("Partie")) / 2, 32);
+ offscreenG.drawString("terminée", (this.getSize().width - fm.stringWidth("terminée")) / 2, 64);
+
+ String s;
+ laFont = new Font("Arial", Font.BOLD, 14);
+ fm = getFontMetrics(laFont);
+ offscreenG.setColor(Color.white);
+ offscreenG.setFont(laFont);
+ s = "cliquez pour rejouer";
+ offscreenG.drawString(s, (this.getSize().width - fm.stringWidth(s)) / 2, 220);
+
+ gameOverPainted = true;
+ }
+ @Override
+ public void paint(Graphics g) {
+ if (offscreenImg == null) {
+ offscreenImg = createImage(gridWidth * Piece.SQUARE_SIZE, gridHeight * Piece.SQUARE_SIZE);
+ backImg = createImage(gridWidth * Piece.SQUARE_SIZE, gridHeight * Piece.SQUARE_SIZE);
+ offscreenG = backImg.getGraphics();
+ offscreenG.setColor(backColor);
+ for (int i = 0; i < gridHeight; i++)
+ for (int j = 0; j < gridWidth; j++)
+ offscreenG.fill3DRect(j * Piece.SQUARE_SIZE, i * Piece.SQUARE_SIZE, Piece.SQUARE_SIZE, Piece.SQUARE_SIZE, true);
+ offscreenG = offscreenImg.getGraphics();
+ offscreenG.drawImage(backImg, 0, 0, this);
+ }
+
+ if (!gameFinished) {
+ // do we need to paint everything ?
+ if (paintAll) {
+ offscreenG.drawImage(backImg, 0, 0, this);
+ for (int i = 0; i < gridHeight; i++) {
+ for (int j = 0; j < gridWidth; j++) {
+ if (grids[i][j] != null) {
+ offscreenG.setColor(grids[i][j]);
+ offscreenG.fill3DRect(j * Piece.SQUARE_SIZE, i * Piece.SQUARE_SIZE, Piece.SQUARE_SIZE, Piece.SQUARE_SIZE, true);
+ }
+ }
+ }
+ paintAll = false;
+
+ if (paintPiece)
+ paintPiece(false);
+ } else {
+ paintPiece(true);
+ }
+ } else if (!gameOverPainted) {
+ paintGameOver();
+ paintAll = false; // do not erase the gameOver screen
+ }
+
+ // paint double-buffer
+ g.drawImage(offscreenImg, 0, 0, this);
+ ds.repaint();
+ }
+
+ /**
+ * Moves current piece to its lowest position
+ */
+ public synchronized void goDown() {
+ int cpt = 1;
+
+ posY++;
+
+ while(true) {
+ // outside ?
+ if (posY < 0 || posY + currentPiece.getHeight() > gridHeight) {
+ posY--;
+ currentPiece.goDown(cpt - 1);
+ return;
+ }
+
+ int mask = 0x8000;
+
+ // try to move down one line
+ for (int i = 0; i < currentPiece.getHeight(); i++) {
+ for (int j = 0; j < currentPiece.getWidth(); j++, mask >>= 1) {
+ if (((currentPiece.getVal() & mask) != 0) && grids[posY + i][posX + j] != null) {
+ posY--;
+ currentPiece.goDown(cpt - 1);
+ return;
+ }
+ }
+ // ok, moves it
+ mask >>= 4 - currentPiece.getWidth();
+ }
+ cpt++;
+ posY++;
+ }
+ }
+
+ /**
+ * Moves piece up to its highest position
+ *
+ */
+ public synchronized void goUp() {
+ int cpt = 1;
+ posY--;
+
+ while(true) {
+ if (posY < 0 || posY + currentPiece.getHeight() > gridHeight) {
+ posY++;
+ currentPiece.goUp(cpt - 1);
+ return;
+ }
+ int mask = 0x8000;
+ for (int i = 0; i < currentPiece.getHeight(); i++) {
+ for (int j = 0; j < currentPiece.getWidth(); j++, mask >>= 1) {
+ if (((currentPiece.getVal() & mask) != 0) && grids[posY + i][posX + j] != null) {
+ posY++;
+ currentPiece.goUp(cpt - 1);
+ return;
+ }
+ }
+ mask >>= 4 - currentPiece.getWidth();
+ }
+ cpt++;
+ posY--;
+ }
+ }
+
+ /**
+ * plays the animation
+ */
+ public void run() {
+ while(!finished) {
+ if (!gameOverPainted) {
+ repaint();
+
+ if (gameRunning && !gameFinished) {
+ bonus--;
+
+ if (direction == DIRECTION_DOWN) {
+ if (canDisplayAt(posX, posY + 1)) {
+ posY++;
+ currentPiece.goDown();
+ } else {
+ pieceStop();
+ selectPiece();
+ if (!canDisplayAt(posX, posY)) gameFinished = true;
+ }
+ } else {
+ if (canDisplayAt(posX, posY - 1)) {
+ posY--;
+ currentPiece.goUp();
+ } else {
+ pieceStop();
+ selectPiece();
+ if (!canDisplayAt(posX, posY)) gameFinished = true;
+ }
+ }
+ }
+ }
+
+ try {
+ Thread.sleep(300 - ((level - 1) * 20));
+ } catch (InterruptedException e) {
+ stop();
+ }
+ }
+ }
+
+ public void keyPressed(KeyEvent e) {
+ int key = e.getKeyCode();
+
+ if (key == 'p' || key == 'P') {
+ gameRunning = !gameRunning;
+ } else if (gameRunning) {
+ switch (key) {
+ case KeyEvent.VK_LEFT:
+ if (canDisplayAt(posX - 1, posY)) {
+ posX--;
+ currentPiece.goLeft();
+ }
+ break;
+ case KeyEvent.VK_RIGHT:
+ if (canDisplayAt(posX + 1, posY)) {
+ posX++;
+ currentPiece.goRight();
+ }
+ break;
+ case KeyEvent.VK_UP:
+ if (canDisplayAt(posX, posY, currentPiece.getNextPiece()))
+ currentPiece.rotate();
+ break;
+ case KeyEvent.VK_DOWN:
+ if (bonus > 0)
+ cptPoints += bonus;
+ if (direction == 1)
+ goDown();
+ else goUp();
+ break;
+ case 'i':
+ case 'I':
+ reverseGame();
+ direction = -direction;
+ resetPiece();
+ bonus = 0;
+ paintAll = true;
+ break;
+ default:
+ return;
+ }
+ }
+ repaint();
+ }
+ public void keyTyped(KeyEvent e) {}
+ public void keyReleased(KeyEvent e) {}
+
+ public void focusLost(FocusEvent e) {
+ gameRunning = false;
+ }
+ public void focusGained(FocusEvent e) {}
+
+ public boolean mouseDown() {
+ gameRunning = true;
+ if (gameFinished) {
+ restartGame();
+ repaint();
+ }
+ return true;
+ }
+
+ private void initListeners() {
+ addMouseListener(new MouseListener() {
+ public void mouseClicked(MouseEvent e) {mouseDown();}
+ public void mousePressed(MouseEvent e) {}
+ public void mouseReleased(MouseEvent e) {}
+ public void mouseEntered(MouseEvent e) {}
+ public void mouseExited(MouseEvent e) {}
+ });
+ // listeners moves to JTRIS
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui.ia;
+
+import java.awt.Color;
+import java.awt.Graphics;
+import java.awt.GridLayout;
+import java.awt.event.KeyEvent;
+import java.awt.event.KeyListener;
+
+import javax.swing.JDialog;
+import javax.swing.JFrame;
+import javax.swing.JPanel;
+
+
+public class JTRIS extends JDialog implements Runnable, KeyListener {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 3256721801408099890L;
+ private Grille laGrille;
+ private DisplayScore dspScore;
+ private Piece[] listePieces;
+ private boolean finished = false;
+
+ public JTRIS(JFrame parent) {
+ super(parent);
+ listePieces = new Piece[7];
+ listePieces[0] = new Piece(0x88C0, 0x2E00, 0xC440, 0xE800, new Color(0, 192, 192)); // cyan
+ listePieces[1] = new Piece(0x44C0, 0xE200, 0xC880, 0x8E00, new Color(255, 230, 0)); // jaune
+ listePieces[2] = new Piece(0xCC00, 0xCC00, 0xCC00, 0xCC00, new Color(0, 192, 0)); // vert
+ listePieces[3] = new Piece(0x8888, 0xF000, 0x8888, 0xF000, new Color(230, 0, 0)); // rouge
+ listePieces[4] = new Piece(0x8C40, 0x6C00, 0x8C40, 0x6C00, new Color(0, 128, 224)); // bleu
+ listePieces[5] = new Piece(0x4C80, 0xC600, 0x4C80, 0xC600, Color.orange);
+ listePieces[6] = new Piece(0x8C80, 0x4E00, 0x4C40, 0xE400, Color.lightGray);
+ init();
+ }
+
+ public void init() {
+ JPanel mainPane = new JPanel(new GridLayout(1, 2, 10, 0));
+
+ laGrille = new Grille(listePieces);
+ laGrille.setBackground(Color.black);
+ mainPane.add(laGrille);
+
+ dspScore = new DisplayScore(laGrille);
+ mainPane.add(dspScore);
+
+ setContentPane(mainPane);
+ addKeyListener(this);
+ pack();
+ }
+ @Override
+ public void setVisible(boolean b) {
+ super.setVisible(b);
+ if(b) {
+ laGrille.start();
+ start();
+ } else {
+ stop();
+ laGrille.stop();
+ }
+ }
+ @Override
+ public void paint(Graphics g) {
+ g.setColor(Color.orange);
+ g.fill3DRect(0, 0, this.getSize().width, this.getSize().height, true);
+
+ if (dspScore != null)
+ dspScore.repaint();
+ }
+
+ public void start() {
+ finished=false;
+ }
+
+ public void stop() {
+ finished=true;
+ }
+
+ public void run() {
+ while(!finished) {
+ repaint();
+ try {
+ Thread.sleep(300);
+ }
+ catch (InterruptedException e) {}
+ }
+ }
+ public void keyPressed(KeyEvent e) {
+ laGrille.keyPressed(e);
+ }
+ public void keyReleased(KeyEvent e) {
+ laGrille.keyReleased(e);
+ }
+ public void keyTyped(KeyEvent e) {
+ laGrille.keyTyped(e);
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.ia;
+
+import javax.swing.Icon;
+import javax.swing.JButton;
+import javax.swing.JPanel;
+
+public class Joueur {
+
+ private static int vrx[][] = new int[3][3];
+ private static int vry[][] = new int[3][3];
+
+ static {
+ for (int i = 0; i < 9; i++) {
+ vrx[i % 3][i / 3] = 4 * ((i % 3) - 1);
+ vry[i % 3][i / 3] = 4 * ((i / 3) - 1);
+ }
+ }
+
+ private int rep[][] = new int[10][10];
+ private int val[][] = new int[10][10];
+
+ private String marque;
+ private Icon icon;
+
+ public Joueur(String s, Icon icon) {
+ super();
+ this.marque = s;
+ this.icon = icon;
+ }
+
+ public void joue(JPanel jPanelJeu) {
+ modelise(jPanelJeu);
+ decide(jPanelJeu);
+ }
+
+ public int sgn(int i) {
+ return i == 0 ? 0 : i < 0 ? -1 : 1;
+ }
+
+ public int compte_pion(int dx, int dy, int fx, int fy, int v) {
+ boolean cnt = true;
+ int cpt = 0;
+ while (((dx != fx) || (dy != fy)) && cnt) {
+ dx += sgn(fx - dx);
+ dy += sgn(fy - dy);
+ if ((dx >= 0) && (dx <= 9) && (dy >= 0) && (dy <= 9) && (rep[dx][dy] == v)) {
+ cpt++;
+ } else cnt = false;
+ }
+ return cpt;
+ }
+
+ public int compte_case(int dx, int dy, int fx, int fy) {
+// boolean cnt = true;
+ int cpt = 0;
+ if ((dx >= 0) && (dx <= 9) && (dy >= 0) && (dy <= 9))
+ cpt++;
+ while ((dx != fx) || (dy != fy)) {
+ dx += sgn(fx - dx);
+ dy += sgn(fy - dy);
+ if ((dx >= 0) && (dx <= 9) && (dy >= 0) && (dy <= 9))
+ cpt++;
+ }
+ return cpt;
+ }
+
+ public int evalue(int dx, int dy, int fx, int fy, int v) {
+ boolean cnt = true;
+ int cpt = 0, ind = 0;
+ while (((dx != fx) || (dy != fy)) && cnt) {
+ dx += sgn(fx - dx);
+ dy += sgn(fy - dy);
+ ind++;
+ if ((dx >= 0) && (dx <= 9) && (dy >= 0) && (dy <= 9) && (rep[dx][dy] == v)) {
+ cpt += rep[dx][dy] * (5 - ind);
+ } else if ((dx >= 0) && (dx <= 9) && (dy >= 0) && (dy <= 9)) {
+ cnt = (rep[dx][dy] == 0);
+ cpt += rep[dx][dy] * (5 - ind);
+ } else cnt = false;
+ }
+ return cpt;
+ }
+
+ public void valorise(int x, int y) {
+ int cpt;
+
+ for (int i = 0; i < 4; i++) {
+ cpt = 1;
+ cpt += compte_pion(x, y, vrx[i % 3][i / 3] + x, vry[i % 3][i / 3] + y, rep[x][y]);
+ cpt += compte_pion(x, y, vrx[(8 - i) % 3][(8 - i) / 3] + x, vry[(8 - i) % 3][(8 - i) / 3] + y, rep[x][y]);
+ if (cpt > Math.abs(val[x][y])) {
+ val[x][y] = cpt;
+ }
+ }
+ }
+
+ public void modelise(JPanel jp) {
+// java.awt.Color c = new java.awt.Color(212, 208, 200);
+ for (int i = 0; i < jp.getComponentCount(); i++) {
+ ((JButton)jp.getComponent(i)).setBackground(Plateau.BACK_COLOR);
+ rep[i % 10][i / 10] = ((JButton)jp.getComponent(i)).getActionCommand() == "" ? 0 : ((JButton)jp.getComponent(i)).getActionCommand() == marque ? 1 : -1;
+ }
+
+ for (int i = 0; i < 10; i++)
+ java.util.Arrays.fill(val[i], 0);
+ }
+
+ public void projete(int x, int y) {
+ int pls, mns;
+ for (int i = 0; i < 4; i++) {
+ pls = 0;
+ mns = 0;
+ if (compte_case(vrx[i % 3][i / 3] + x, vry[i % 3][i / 3] + y, vrx[(8 - i) % 3][(8 - i) / 3] + x, vry[(8 - i) % 3][(8 - i) / 3] + y) >= 5) {
+ mns += evalue(x, y, vrx[i % 3][i / 3] + x, vry[i % 3][i / 3] + y, -1);
+ mns += evalue(x, y, vrx[(8 - i) % 3][(8 - i) / 3] + x, vry[(8 - i) % 3][(8 - i) / 3] + y, -1);
+ pls += evalue(x, y, vrx[i % 3][i / 3] + x, vry[i % 3][i / 3] + y, 1);
+ pls += evalue(x, y, vrx[(8 - i) % 3][(8 - i) / 3] + x, vry[(8 - i) % 3][(8 - i) / 3] + y, 1);
+ }
+ if (Math.abs(mns) > Math.abs(val[x][y]))
+ val[x][y] = mns;
+ if (Math.abs(pls) > Math.abs(val[x][y]))
+ val[x][y] = pls;
+ }
+ }
+
+ public void decide(JPanel jPanelJeu) {
+ int scr = 0, scp = 50;
+
+ for (int i = 0; i < 10; i++)
+ for (int j = 0; j < 10; j++)
+ if (rep[j][i] == 0)
+ projete(j, i);
+
+ for (int i = 0; i < 10; i++)
+ for (int j = 0; j < 10; j++)
+ if (rep[j][i] == 0) {
+ if (Math.abs(val[j][i]) > scr) {
+ scr = Math.abs(val[j][i]);
+ scp = j + i * 10;
+ } else {
+ if (Math.abs(rep[j][i]) == scr) {
+ if (val[j][i] >= val[scp % 10][scp / 10]) {
+ scp = j + i * 10;
+ }
+ }
+ }
+ }
+
+ rep[scp % 10][scp / 10] = 1;
+ ((JButton)jPanelJeu.getComponent(scp)).setActionCommand(marque);
+ ((JButton)jPanelJeu.getComponent(scp)).setIcon(icon);
+ ((JButton)jPanelJeu.getComponent(scp)).setForeground(java.awt.Color.red);
+ ((JButton)jPanelJeu.getComponent(scp)).setBackground(java.awt.Color.white);
+ }
+
+ public boolean victoire(JPanel jp) {
+ boolean cnt = false;
+
+ for (int i = 0; i < jp.getComponentCount(); i++) {
+ rep[i % 10][i / 10] = ((JButton)jp.getComponent(i)).getActionCommand() == "" ? 0 : ((JButton)jp.getComponent(i)).getActionCommand() == marque ? 1 : -1;
+ }
+
+ for (int i = 0; i < 10; i++)
+ java.util.Arrays.fill(val[i], 0);
+
+ for (int i = 0; i < 10; i++)
+ for (int j = 0; j < 10; j++)
+ if (rep[j][i] != 0)
+ valorise(j, i);
+
+ for (int i = 0; i < 10; i++)
+ for (int j = 0; j < 10; j++)
+ if (Math.abs(val[j][i]) == 5) {
+ ((JButton)jp.getComponent(j + i * 10)).setBackground(java.awt.Color.white);
+ cnt = true;
+ }
+
+ return cnt;
+ }
+
+// public void dump(JTextArea jTextArea) {
+// for (int i = 0; i < 10; i++) {
+// for (int j = 0; j < 10; j++)
+// jTextArea.append("\t" + rep[j][i] + "(" + val[j][i] + ")");
+// jTextArea.append("\n");
+// }
+// jTextArea.append("\n");
+// }
+
+ public String getMarque() {
+ return marque;
+ }
+ public Icon getIcon() {
+ return icon;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui.ia;
+
+import java.awt.Color;
+import java.awt.Graphics;
+import java.util.Arrays;
+
+/**
+ * Describes a piece on the board
+ * @author chm
+ */
+public class Piece {
+ // contains a representation of the 4 rotations
+ private int[] images = new int[4];
+ // contains the height 4 rotations
+ private int[] heights = new int[4];
+ // contains the width des 4 rotations
+ private int[] widths = new int[4];
+ // Position
+ private int x, y;
+ // last state
+ private int lastX, lastY, lastRotation;
+ private Color color;
+ // current rotation
+ private int idRotation;
+ // unitary size of a square
+ public final static int SQUARE_SIZE = 15;
+
+ // Constructors
+ public Piece(int r1, int r2, int r3, int r4, Color color) {
+ images[0] = r1;
+ images[1] = r2;
+ images[2] = r3;
+ images[3] = r4;
+ this.color = color;
+ x = y = idRotation = 0;
+ lastX = lastY = -1;
+ computesWH();
+ }
+
+ public Piece(int r1, int r2, int r3, int r4, Color color, int p_x, int p_y) {
+ this(r1, r2, r3, r4, color);
+ x = p_x;
+ y = p_y;
+ }
+
+ public Piece(int[] r, Color color) {
+ System.arraycopy(r,0,images,0,4);
+ x = y = idRotation = 0;
+ lastX = lastY = -1;
+ this.color = color;
+ computesWH();
+ }
+
+ public Piece(int[] r, Color color, int p_x, int p_y) {
+ this(r, color);
+ x = p_x;
+ y = p_y;
+ }
+
+ public Piece(Piece src) {
+ System.arraycopy(src.images,0,images,0,4);
+ System.arraycopy(src.widths,0,widths,0,4);
+ System.arraycopy(src.heights,0,heights,0,4);
+ idRotation = src.idRotation;
+ lastX = src.lastX;
+ lastY = src.lastY;
+ lastRotation = src.lastRotation;
+ x = src.x;
+ y = src.y;
+ color = src.color;
+ }
+
+ public void reset() {
+ reset(0, 0);
+ }
+
+ public void reset(int p_x, int p_y) {
+ x = p_x;
+ y = p_y;
+ idRotation = 0;
+ lastX = lastY = -1;
+ }
+
+ public void firstRotation() {
+ idRotation = 0;
+ }
+
+ private void computesWH() {
+ Arrays.fill(widths,0);
+ Arrays.fill(heights,0);
+
+ for (int cptRotations = 0; cptRotations < heights.length; cptRotations++) {
+ int mask = 0x8000;
+ for (int i = 0; i < 4; i++) {
+ boolean lineOK = false;
+ for (int j = 0; j < 4; j++, mask >>= 1)
+ if ((mask & images[cptRotations]) != 0) {
+ if (!lineOK) {
+ lineOK = true;
+ heights[cptRotations]++;
+ }
+ if (widths[cptRotations] < j + 1)
+ widths[cptRotations] = j + 1;
+ }
+ }
+ }
+
+ }
+
+ public void rotate() {
+// if (idRotation >= 3) idRotation = 0;
+// else idRotation++;
+ idRotation = ((idRotation+1) % 4);
+ }
+
+
+ public void goDown() {
+ y += SQUARE_SIZE;
+ }
+
+ public void goDown(int lines) {
+ y += (SQUARE_SIZE * lines);
+ }
+
+ public void goLeft() {
+ x -= SQUARE_SIZE;
+ }
+
+ public void goRight() {
+ x += SQUARE_SIZE;
+ }
+
+ public void goUp() {
+ y -= SQUARE_SIZE;
+ }
+
+ public void goUp(int lines) {
+ y -= (SQUARE_SIZE * lines);
+ }
+
+ public int getX() {
+ return x;
+ }
+
+ public int getY() {
+ return y;
+ }
+
+ public int paintx() {
+ return lastX;
+ }
+
+ public int painty() {
+ return lastY;
+ }
+
+ public Color getColor() {
+ return color;
+ }
+
+ public int getHeight() {
+ return heights[idRotation];
+ }
+
+ public int getHeight(int id) {
+ return id >= 0 && id < 4 ? heights[id] : 0;
+ }
+
+ public int nextHeight() {
+ return heights[idRotation >= 3 ? 0 : idRotation + 1];
+ }
+
+ public int getWidth() {
+ return widths[idRotation];
+ }
+
+ public int getWidth(int id) {
+ return id >= 0 && id < 4 ? widths[id] : 0;
+ }
+
+ public int nextWidth() {
+ return widths[idRotation >= 3 ? 0 : idRotation + 1];
+ }
+
+ public int getVal() {
+ return images[idRotation];
+ }
+
+ public int getVal(int id) {
+ return id >= 0 && id < 4 ? images[id] : 0;
+ }
+
+ public int getNextVal() {
+ return images[idRotation >= 3 ? 0 : idRotation + 1];
+ }
+
+ public Piece getNextPiece() {
+ Piece np = new Piece(this);
+ np.rotate();
+ return np;
+ }
+
+ public synchronized void display(Graphics g) {
+ int mask = 0x8000, i, j;
+
+ lastX = x;
+ lastY = y;
+ lastRotation = idRotation;
+ g.setColor(color);
+ for (i = 0; i < 4; i++)
+ for (j = 0; j < 4; j++, mask >>= 1)
+ if ((mask & images[idRotation]) != 0)
+ g.fill3DRect(x + (j * SQUARE_SIZE), y + (i * SQUARE_SIZE), SQUARE_SIZE, SQUARE_SIZE, true);
+ }
+
+ public synchronized void erase(Graphics g, Color fond) {
+ int mask = 0x8000, i, j;
+
+ if (lastX == -1 || lastY == -1)
+ return;
+
+ g.setColor(fond);
+ for (i = 0; i < 4; i++)
+ for (j = 0; j < 4; j++, mask >>= 1)
+ if ((mask & images[lastRotation]) != 0)
+ g.fill3DRect(lastX + (j * SQUARE_SIZE), lastY + (i * SQUARE_SIZE), SQUARE_SIZE, SQUARE_SIZE, true);
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.ia;
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.GridLayout;
+import java.awt.Toolkit;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+
+import javax.swing.JButton;
+import javax.swing.JFrame;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+
+import fr.gouv.finances.cp.utils.ui.IhmFactory;
+import fr.gouv.finances.dgfip.xemelios.ui.ImageResources;
+
+public class Plateau extends JFrame {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 3258413915443704633L;
+
+ protected static Color BACK_COLOR = new Color(212, 208, 200);
+// private static IhmFactory iF = IhmFactory.newInstance();
+
+ JPanel contentPane;
+
+ JPanel buttonPane = new JPanel();
+
+ JButton jButtonEffacer;
+ JButton pbOrdi;
+
+ JPanel jPanelJeu = new JPanel();
+
+ Joueur joueur = new Joueur("X",IhmFactory.getIconFromResource(ImageResources.ICON_X));
+ Joueur ordi = new Joueur("O",IhmFactory.getIconFromResource(ImageResources.ICON_O));
+
+
+ public Plateau() {
+ super("Faire une ligne de 5 pions...");
+ try {
+ jbInit();
+ for (int i = 0; i < 100; i++) {
+ JButton jbt = new JButton();
+ jbt.setBackground(BACK_COLOR);
+ jbt.setFont(new java.awt.Font("Dialog", 1, 8));
+ jbt.addActionListener(new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ jButton_actionPerformed(e);
+ }
+ });
+ jPanelJeu.add(jbt, null);
+ }
+ Dimension sSz = Toolkit.getDefaultToolkit().getScreenSize();
+ Dimension fSz = getSize();
+ setLocation((sSz.width - fSz.width) / 2, (sSz.height - fSz.height) / 2);
+ setVisible(true);
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ private void jbInit() throws Exception {
+ contentPane = (JPanel)this.getContentPane();
+ contentPane.setLayout(new BorderLayout());
+ jButtonEffacer = new JButton("Effacer");
+ jButtonEffacer.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ jButtonEffacer_actionPerformed(e);
+ }
+ });
+ jPanelJeu.setLayout(new GridLayout(10,10));
+
+ jPanelJeu.setMaximumSize(new Dimension(300, 2147483647));
+ jPanelJeu.setMinimumSize(new Dimension(300, 100));
+ jPanelJeu.setPreferredSize(new Dimension(300,300));
+ contentPane.add(buttonPane, BorderLayout.EAST);
+ buttonPane.add(jButtonEffacer, null);
+ contentPane.add(jPanelJeu, BorderLayout.CENTER);
+ pack();
+ }
+
+ void jButton_actionPerformed(ActionEvent e) {
+ JButton source = ((JButton)e.getSource());
+ if(source.getActionCommand().length()!=0) {
+ JOptionPane.showMessageDialog(this,"Tricheur !");
+ return;
+ }
+ source.setActionCommand(joueur.getMarque());
+ source.setIcon(joueur.getIcon());
+ joueur.modelise(jPanelJeu);
+ if (joueur.victoire(jPanelJeu))
+ termine(joueur.getMarque());
+ else {
+ // c'est a l'autre de jouer
+ ordi.joue(jPanelJeu);
+ if (ordi.victoire(jPanelJeu))
+ termine(ordi.getMarque());
+ }
+ }
+
+ void jButtonEffacer_actionPerformed(ActionEvent e) {
+ for (int i = 0; i < jPanelJeu.getComponentCount(); i++) {
+ ((JButton)jPanelJeu.getComponent(i)).setActionCommand("");
+ ((JButton)jPanelJeu.getComponent(i)).setIcon(null);
+ ((JButton)jPanelJeu.getComponent(i)).setForeground(Color.black);
+ ((JButton)jPanelJeu.getComponent(i)).setBackground(BACK_COLOR);
+ }
+ }
+
+ public void termine(String s) {
+ String msg;
+ if("X".equals(s)) msg = "Bravo, vous avez gagné.";
+ else msg = "Yeap ! J'ai gagné !";
+ JOptionPane.showMessageDialog(this,msg,"Morpion",JOptionPane.INFORMATION_MESSAGE);
+ }
+
+ void pbOrdi_actionPerformed(ActionEvent e) {
+ ordi.joue(jPanelJeu);
+ if (ordi.victoire(jPanelJeu))
+ termine(ordi.getMarque());
+ }
+
+ void pbJoueur_actionPerformed(ActionEvent e) {
+ joueur.joue(jPanelJeu);
+ if (joueur.victoire(jPanelJeu))
+ termine(joueur.getMarque());
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui.ia.core;
+
+import java.util.ArrayList;
+
+/**
+ * New game builder.
+ * </BR>Initialize a position then:
+ * <NL><LI>add a move to original position if it has more than one solution
+ * <LI>remove a move from original position if it has no solution
+ * </NL></BR>
+ * until a solution is found....
+ *
+ * @author Tchok
+ */
+public class Builder extends RandomTool implements ISolverListener {
+ // Initial position
+ State _initialPosition = null;
+
+ // Solution
+ State _solution;
+
+ // No remove flag
+ private boolean _noRemove;
+
+ // Current count
+ private int _count;
+
+ // Solve number of ops
+ private int _opsCount;
+
+ // Max value
+ private int _maxValue;
+
+ // Max index
+ private int _maxIndex;
+
+ // Symetrizer
+ private Symetrizer _symetrizer;
+
+ /** Get one. */
+ public Builder() {
+ // NOP
+ }
+
+ /**
+ * @return initial state.
+ */
+ public State buildOne(Template tpl_p) {
+ // Initialize
+ _initialPosition = new State(tpl_p);
+ _maxIndex = _initialPosition.getTemplate().maxIndex;
+ _maxValue = _initialPosition.getTemplate().maxValue;
+ _symetrizer = tpl_p.symetrical ?
+ new Symetrizer(tpl_p) :
+ new NoSymetrizer(tpl_p);
+
+ // Feed it
+ initializeState();
+
+ // Clear solution
+ _solution = null;
+ //
+ // // Say it
+
+ // Start it
+ Solver solver = new Solver(this);
+ while (_solution == null) {
+ // Look for a solution
+ _noRemove = false;
+ _opsCount = getMaxOpsCount(tpl_p);
+ solver.solve(_initialPosition);
+
+ // If no solution was found, remove one of the original values
+ if ((_solution == null) && (!_noRemove)) {
+ removeFromInitialPosition();
+ }
+ //
+ // // Say it
+ }
+
+ // Found a solution, mark it
+ State output = new State(_initialPosition);
+ output.registerOriginalPosition();
+
+ // OK
+ return output;
+ }
+
+ /**
+ * Get the max operations count allowed according to template.
+ * This is because some configurations just takes too much time...
+ *
+ * @param tpl_p
+ * target template
+ * @return a max number of operation
+ */
+ private int getMaxOpsCount(Template tpl_p) {
+ // Get size
+ int size = tpl_p.maxValue;
+
+ // Fix answer...
+ int base = 1000000;
+ // TODO Get values from resource ?
+ if (size < 10) {
+ return base;
+ } else if (size < 13) {
+ return base * 10;
+ } else {
+ return base * 100;
+ }
+ }
+
+ /**
+ * Initialize the starting state.
+ * The <code>_initialPosition</code> should be clean.
+ */
+ private void initializeState() {
+ // Clean a bit
+ _count = 0;
+
+ //
+ // Let's begin with at least one per row/column
+ //
+
+ // Build two list [0, _maxValue[
+ ArrayList<Integer> columns = new ArrayList<Integer>();
+ ArrayList<Integer> rows = new ArrayList<Integer>();
+ for (int i = 0; i < _maxValue; i++) {
+ columns.add(new Integer(i));
+ rows.add(new Integer(i));
+ }
+
+ // TODO - Perf - _maxValue - 1 is enought.. Study for speed !!!
+ // Insert values...
+ // select a random (line, column) and a random value
+ for (int i = 0; i < _maxValue; i++) {
+ // Get an index
+ int l = random(rows);
+ int c = random(columns);
+ int index = l * _maxValue + c;
+ int symIndex = _symetrizer.getIndex(index);
+
+ // It is free ! (we know it)
+ // Find a playable value
+ int dontRunAllNight = _maxValue;
+ while (_initialPosition.isFree(index)
+ && _initialPosition.isFree(symIndex)
+ && (dontRunAllNight-- > 0)) {
+
+ // Try a value
+ int value = random(_maxValue);
+ if (_initialPosition.isAllowed(index, value)) {
+ // Play it
+ if (_initialPosition.playWhilePossible(index, value)) {
+ _count++;
+
+ // Try for the other one
+ if (symIndex != index) {
+ boolean rewind = true;
+ for (int maxTry = _maxValue * 2; maxTry > 0; maxTry--) {
+ value = random(_maxValue);
+
+ // Try it
+ if (_initialPosition.isAllowed(symIndex, value)) {
+ // Play it
+ if (_initialPosition.playWhilePossible(
+ symIndex, value)) {
+ _count++;
+ rewind = false;
+ break;
+ } else {
+ _initialPosition.clean(symIndex);
+ }
+ }
+ } // endloop - on maxTry (sym move)
+
+ // Rewind ?
+ if (rewind) {
+ // Clear it
+ _initialPosition.clean(index);
+ _initialPosition.clearMarks();
+ _count--;
+ }
+ } // endif - symIndex != index
+ } // endif - index was all right
+ else {
+ _initialPosition.clean(index);
+ }
+ } // endif - initial position allowed index
+ } // endloop - while it's alowed
+ } // endloop - insert a few (one per line/col)
+ }
+
+ /**
+ * Just remove any from the original position
+ */
+ private void removeFromInitialPosition() {
+ // Debug
+ // System.out.print(" --- " + _count); //$NON-NLS-1$
+
+ // Scan for different values
+ ArrayList<Integer> candidates = new ArrayList<Integer>();
+
+ // Start searchin
+ for (int i = 0; i < _maxIndex; i++) {
+ if (!_initialPosition.isFree(i)) {
+ // Store it
+ candidates.add(new Integer(i));
+ }
+ }
+
+ // Select one
+ int index = random(candidates);
+
+ // Remove it
+ _count--;
+ _initialPosition.clean(index);
+
+ // Remove symetrical
+ int symIndex = _symetrizer.getIndex(index);
+ if (symIndex != index) {
+ _count--;
+ _initialPosition.clean(symIndex);
+ }
+
+ // Clear marks
+ _initialPosition.clearMarks();
+ }
+
+ /**
+ * Overriden for a builder...
+ * Store first solution (and keep searching).
+ * add a value to the initial position and stop searching if another solution is found.
+ * @see tchok.sudoku.core.ISolverListener#foundASolution(tchok.sudoku.core.State)
+ */
+ public boolean foundASolution(State state_p) {
+ // Is it the first one ?
+ if (_solution == null) {
+ // Yes it is, store it and look for another one
+ _solution = new State(state_p);
+
+ // Keep searching
+ return true;
+ }
+
+ // No it's not, add a move to the original position and replay
+ addAMoveToOriginalPosition(state_p);
+
+ _solution = null;
+ _noRemove = true;
+ return false;
+ }
+
+ /**
+ * Called when more than one solution is found.
+ * Selects a value that differs in <code>_solution</code> and <code>state_p</code>.
+ *
+ * @param state_p another solution to the original position.
+ */
+ private void addAMoveToOriginalPosition(State state_p) {
+ // Debug
+ // System.out.print(" +++ " + _count); //$NON-NLS-1$
+
+ //
+ // Scan for different values
+ //
+ ArrayList<Integer> candidates = new ArrayList<Integer>();
+
+ // Start searching
+ for (int i = 0; i < _maxIndex; i++) {
+ if (state_p.getValue(i) != _solution.getValue(i)) {
+ // Store it
+ candidates.add(new Integer(i));
+ }
+ }
+
+ // Select one
+ int index = random(candidates);
+
+ // Play it
+ _count++;
+ _initialPosition.play(index, state_p.getValue(index));
+
+ // Play the symetrical one
+ int symIndex = _symetrizer.getIndex(index);
+ if (symIndex != index) {
+ _count++;
+ _initialPosition.play(symIndex, state_p.getValue(symIndex));
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ * Overriden to limit building time...
+ * @see tchok.sudoku.core.ISolverListener#levelIs(int,
+ * tchok.sudoku.core.State)
+ */
+ public boolean levelIs(int level_p, State state_p) {
+ // Watch for time limit !
+ _opsCount--;
+
+ // Debug stuff
+ if ((_opsCount % 1000000) == 0) {
+ // System.out.print("."); //$NON-NLS-1$
+ }
+
+ // Give up ?
+ boolean giveUp = (_opsCount < 0) && (_solution == null);
+ return !giveUp;
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright
+ * 2008 axYus - www.axyus.com
+ * 2008 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.ia.core;
+
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.Graphics;
+import java.awt.GridLayout;
+import java.awt.Rectangle;
+import java.awt.event.ActionEvent;
+import java.awt.event.FocusAdapter;
+import java.awt.event.FocusEvent;
+import java.awt.event.KeyAdapter;
+import java.awt.event.KeyEvent;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.awt.geom.Rectangle2D;
+import javax.swing.AbstractAction;
+import javax.swing.Action;
+import javax.swing.JComponent;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.UIManager;
+
+/**
+ *
+ * @author christophe.marchand
+ */
+public class DlgCore extends javax.swing.JDialog {
+ private Action actNew, actClose;
+// private Icon iconNew = IhmFactory.getIconFromResource(ImageResources.NEW);
+// private Icon iconClose = IhmFactory.getIconFromResource(ImageResources.CLOSE);
+ private SGrid grid;
+
+ /** Creates new form DlgCore */
+ public DlgCore(java.awt.Frame parent) {
+ super(parent, false);
+ initActions();
+ newGame();
+ initComponents();
+ }
+ protected void initActions() {
+ actNew = new AbstractAction() {
+ public void actionPerformed(ActionEvent e) {
+ newGame();
+ }
+ };
+ actClose = new AbstractAction() {
+ public void actionPerformed(ActionEvent e) {
+ setVisible(false);
+ }
+ };
+ }
+ protected void newGame(){
+ Builder bd = new Builder();
+ grid = new SGrid(new StateModel(bd.buildOne(TemplateFactory.getTemplate(3,3))));
+ };
+
+ /**
+ * @param args the command line arguments
+ */
+ public static void main(String args[]) {
+ java.awt.EventQueue.invokeLater(new Runnable() {
+ public void run() {
+ DlgCore dialog = new DlgCore(new javax.swing.JFrame());
+ dialog.addWindowListener(new java.awt.event.WindowAdapter() {
+ @Override
+ public void windowClosing(java.awt.event.WindowEvent e) {
+ System.exit(0);
+ }
+ });
+ dialog.setVisible(true);
+ }
+ });
+ }
+
+ private static boolean isInSameSquare(int i, int j, int row, int col) {
+ return Math.floor(i/3.0f)==Math.floor(row/3.0f) && Math.floor(j/3.0f)==Math.floor(col/3.0f);
+ }
+ private void initComponents() {
+
+
+ setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+ StringBuffer sb = new StringBuffer();
+ sb.append(Constants.NOM_APP).append(" S").append("u").append("d").append("o").append("k").append("u");
+ setTitle(sb.toString());
+
+
+ org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(grid, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(grid, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 320, Short.MAX_VALUE)
+ .addContainerGap())
+ );
+
+ pack();
+ }
+
+ /**
+ * @param args the command line arguments
+ */
+ // Variables declaration - do not modify
+ private class SGrid extends JPanel {
+ SCase grid[][];
+ private StateModel sm;
+ public SGrid(StateModel sm) {
+ super();
+ this.sm=sm;
+ initComponents();
+ }
+
+ @Override
+ public int getHeight() {
+ return super.getWidth();
+ }
+ protected void initComponents() {
+ setLayout(new GridLayout(9,9,0,0));
+ grid = new SCase[9][9];
+ for(int i=0;i<9;i++) {
+ for(int j=0;j<9;j++) {
+ grid[i][j]=new SCase(sm,this,i,j);
+ add(grid[i][j]);
+ }
+ }
+ }
+ public void notifyFocusGained(int row, int col) {
+ for(int i=0;i<9;i++) {
+ for(int j=0;j<9;j++) {
+ grid[i][j].setSelected(i==row || j==col || isInSameSquare(i,j,row,col));
+ grid[i][j].setHadFocus(row==i && col==j);
+ }
+ }
+ paintImmediately(new Rectangle(0,0,getWidth(),getHeight()));
+ }
+ public void checkGridFinished() {
+ boolean gridFilled = true;
+ for(int i=0; i<9; i++) {
+ if(!gridFilled) break;
+ for(int j=0; j<9; j++) {
+ String s = sm.getValueAt(i,j);
+ if(s==null) {
+ gridFilled = false;
+ break;
+ }
+ }
+ }
+ if(gridFilled) {
+ JOptionPane.showMessageDialog(getParent(), "Félicitations !");
+ }
+ }
+ public void highLight(String s) {
+ for(int i=0; i<9; i++) {
+ for(int j=0;j<9;j++) {
+ grid[i][j].setSelected(sm.getValueAt(i,j) == null);
+ }
+ }
+ for(int i=0; i<9; i++) {
+ for(int j=0;j<9;j++) {
+ if(s.equals(sm.getValueAt(i, j))) {
+ for(int k=0;k<9;k++) {
+ grid[i][k].setSelected(false);
+ grid[k][j].setSelected(false);
+ }
+ int xStart = (int)Math.floor(i/3.0f)*3;
+ int yStart = (int)Math.floor(j/3.0f)*3;
+ int xEnd = xStart + 3;
+ int yEnd = yStart + 3;
+ for(int i1=xStart;i1<xEnd;i1++) {
+ for(int j1=yStart;j1<yEnd;j1++) {
+ grid[i1][j1].setSelected(false);
+ }
+ }
+ }
+ }
+ }
+ paintImmediately(new Rectangle(0,0,getWidth(),getHeight()));
+ }
+ }
+ private class SCase extends JComponent {
+ private StateModel sm;
+ private int row, col;
+ private boolean selected = false;
+ private boolean hadFocus = false;
+ private SGrid grid;
+ public SCase(final StateModel sm,final SGrid grid, final int row, final int col) {
+ super();
+ this.sm=sm;
+ this.grid=grid;
+ this.row=row;
+ this.col=col;
+ addKeyListener(new KeyAdapter() {
+ @Override
+ public void keyTyped(KeyEvent e) {
+ if((e.getModifiersEx() & KeyEvent.CTRL_DOWN_MASK) > 0) {
+ char c = e.getKeyChar();
+ if('1' <= c && c <= '9') {
+ grid.highLight(Character.toString(c));
+ }
+
+ } else if(sm.isWritable(row, col)) {
+ if(sm.isValueAllowed(row, col, Character.toString(e.getKeyChar()))) {
+ sm.setValueAt(row, col, Character.toString(e.getKeyChar()));
+ e.consume();
+ repaint();
+ grid.checkGridFinished();
+ } else if(e.getKeyChar()==' ' || (int)e.getKeyChar()==127 || (int)e.getKeyChar()==8) {
+ sm.setValueAt(row, col, " ");
+ e.consume();
+ repaint();
+ }
+ }
+ }
+
+ @Override
+ public void keyPressed(KeyEvent e) {
+ if(e.getKeyCode()==KeyEvent.VK_LEFT) {
+ if(col>0) {
+ grid.grid[row][col-1].grabFocus();
+ e.consume();
+ }
+ } else if(e.getKeyCode()==KeyEvent.VK_RIGHT) {
+ if(col<8) {
+ grid.grid[row][col+1].grabFocus();
+ e.consume();
+ }
+ } else if(e.getKeyCode()==KeyEvent.VK_UP) {
+ if(row>0) {
+ grid.grid[row-1][col].grabFocus();
+ e.consume();
+ }
+ } else if(e.getKeyCode()==KeyEvent.VK_DOWN) {
+ if(row<8) {
+ grid.grid[row+1][col].grabFocus();
+ e.consume();
+ }
+ }
+ }
+ });
+ addMouseListener(new MouseAdapter() {
+
+ @Override
+ public void mouseClicked(MouseEvent e) {
+ requestFocus();
+ }
+ });
+ addFocusListener(new FocusAdapter() {
+ @Override
+ public void focusGained(FocusEvent e) {
+ grid.notifyFocusGained(row,col);
+ }
+ });
+ }
+ @Override
+ public void paint(Graphics g) {
+ if(selected) g.setColor(UIManager.getColor("TextField.selectionBackground")); //
+ else g.setColor(UIManager.getColor("TextField.background")); // UIManager.getColor("background")
+ g.fillRect(1,1,getWidth()-1,getHeight()-1);
+ if(hasFocus() | isTopComponentFocused()) g.setColor(Color.GRAY);
+ else g.setColor(Color.BLACK);
+ // cadre supérieur
+ g.drawLine(0,0, getWidth()-1,0);
+ if(hasFocus() | isLeftComponentFocused()) g.setColor(Color.GRAY);
+ else g.setColor(Color.BLACK);
+ // cadre gauche
+ g.drawLine(0,0,0, getHeight()-1);
+ if(row % 3 == 2) {
+ if(isRightComponentFocused())
+ g.setColor(Color.GRAY);
+ else
+ g.setColor(Color.BLACK);
+ g.drawLine(0,getHeight()-1,getWidth()-1,getHeight()-1);
+ }
+ if(col % 3 == 2) {
+ if(isBottomComponentFocused())
+ g.setColor(Color.GRAY);
+ else
+ g.setColor(Color.BLACK);
+ g.drawLine(getWidth()-1,0,getWidth()-1,getHeight()-1);
+ }
+ if(sm.getValueAt(row, col)!=null) {
+ Font originalF = g.getFont();
+ g.setColor(Color.BLACK);
+ Font ft = g.getFont();
+ Font nf = ft.deriveFont(getHeight()*0.5f);
+ if(sm.isWritable(row, col)) {
+ nf = nf.deriveFont(Font.ITALIC);
+ }
+ g.setFont(nf);
+ String s = sm.getValueAt(row, col);
+ Rectangle2D rect = g.getFontMetrics().getStringBounds(s, g);
+ g.drawString(s,
+ (int)((getWidth()-rect.getWidth())/2),
+ (int)((getHeight()-rect.getHeight()/2)));
+ g.setFont(originalF);
+ }
+ }
+ public void setSelected(boolean selected) {
+ this.selected=selected;
+ }
+ public void setHadFocus(boolean hadFocus) {
+ this.hadFocus=hadFocus;
+ }
+ public boolean isBottomComponentFocused() {
+ if(row==8) return false;
+ return grid.grid[row+1][col].hasFocus();
+ }
+ public boolean isRightComponentFocused() {
+ if(col==8) return false;
+ return grid.grid[row][col+1].hasFocus();
+ }
+ public boolean isLeftComponentFocused() {
+ if(col==0) return false;
+ return grid.grid[row][col-1].hasFocus();
+ }
+ public boolean isTopComponentFocused() {
+ if(row==0) return false;
+ return grid.grid[row-1][col].hasFocus();
+ }
+ @Override
+ public Dimension getMinimumSize() {
+ return new Dimension(20,20);
+ }
+
+ }
+}
--- /dev/null
+package fr.gouv.finances.cp.xemelios.ui.ia.core;
+
+/**
+ * @author Tchok
+ */
+public interface ISolverListener {
+ /** Called when a solution is found.
+ * @param state_p the solution
+ * @return true to keep searching, false to stop
+ */
+ public boolean foundASolution(State state_p);
+
+ /** Called when level changes.
+ * return false to stop scanning.
+ */
+ public boolean levelIs(int level_p, State state_p);
+}
--- /dev/null
+package fr.gouv.finances.cp.xemelios.ui.ia.core;
+
+/**
+ * Dummy case, no symetrie at all...
+ * @author Tchok
+ */
+public class NoSymetrizer extends Symetrizer {
+
+ public NoSymetrizer(Template template_p) {
+ super(template_p);
+ }
+
+ @Override
+ public int getIndex(int index_p) {
+ return index_p;
+ }
+}
--- /dev/null
+package fr.gouv.finances.cp.xemelios.ui.ia.core;
+
+import java.util.ArrayList;
+
+/**
+ * @author Tchok
+ */
+public class RandomTool {
+
+ /**
+ * Just select, remove and return a value from a list
+ * @param list_p of Integer !
+ * @return
+ */
+ int random(ArrayList<Integer> list_p) {
+ // Get it
+ Integer value = list_p.remove(random(list_p.size()));
+ return value.intValue();
+ }
+
+ /**
+ * Just get a random number...
+ * @param max_p
+ * @return
+ */
+ int random(int max_p) {
+ return (int)(Math.random() * max_p);
+ }
+
+}
--- /dev/null
+package fr.gouv.finances.cp.xemelios.ui.ia.core;
+
+
+/**
+ * @author Tchok
+ */
+public class Solver {
+ // All the states
+ State _states[];
+
+ // The listener
+ ISolverListener _listener;
+
+ // Limits
+ private int _maxIndex;
+ private int _maxValue;
+
+ /** Give it a listener. */
+ public Solver(ISolverListener listener_p) {
+ _listener = listener_p;
+ }
+
+ /** Do solve it. */
+ public void solve(State state_p) {
+ // get template
+ _maxIndex = state_p.getTemplate().maxIndex;
+ _maxValue = state_p.getTemplate().maxValue;
+
+ // Let's alocate a few..
+ _states = new State[_maxIndex+1];
+ for(int i=0; i<_states.length; i++) {
+ _states[i] = new State(state_p.getTemplate());
+ }
+
+ // And get going
+ _states[0].loadFrom(state_p);
+ study(0);
+ }
+
+ /**
+ * Study a specific index
+ * @param index_p
+ * @return true to keep going, false to stop
+ */
+ private boolean study(int index_p) {
+
+ // Get it
+ State state = _states[index_p];
+
+ // Not too far
+ if(index_p == _maxIndex) {
+ return _listener.foundASolution(state);
+ }
+
+ // Warn listener
+ if(!_listener.levelIs(index_p, state)) {
+ return false;
+ }
+
+ // is it free ?
+ if(state.isFree(index_p)) {
+ // We'll have to study it all
+ for(int value=0; value<_maxValue; value++) {
+ // is it allowed ?
+ if(state.isAvailable(index_p, value)) {
+ // Let's try it
+ _states[index_p + 1].loadFrom(state);
+ boolean answer = _states[index_p + 1].playWhilePossible(index_p, value);
+
+ // Recurse ?
+ if(!answer) {
+ continue;
+ }
+
+ // Recurse
+ answer = study(index_p+1);
+ if(!_listener.levelIs(index_p, state)) {
+ return false;
+ }
+
+ // So what ?
+ if(!answer) {
+ return false;
+ }
+ } // endif - it's allowed
+ } // endloop on values
+
+ // Keep going
+ return true;
+ } // endif - it's free
+
+ // Just call the next one
+ _states[index_p+1].loadFrom(state);
+ return study(index_p+1);
+ }
+}
--- /dev/null
+package fr.gouv.finances.cp.xemelios.ui.ia.core;
+
+import java.io.IOException;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
+
+
+/**
+ * @author Tchok
+ */
+public class State implements Serializable {
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+
+ /** basic states.
+ * Bit use:
+ * 1-4 : value
+ * // 5 : free tag ( 1 means free)
+ * 5 : start position marker (1 means yes)
+ * 6-14 : possibility to play a value (4 is for 0)
+ * 15-23: mark 1
+ * 24-32: mark 2
+ */
+ private int _states[];
+
+ /** This board's template.*/
+ protected Template _template = Template.T33;
+
+ /** Creates an emty board.*/
+ public State(Template template_p) {
+ // Store
+ _template = template_p;
+
+ // Allocate
+ _states = _template.allocate();
+
+ // All clear
+ for (int i = 0; i < _template.maxIndex; i++) {
+ _states[i] = _template.INITIAL_VALUE;
+ }
+ }
+
+ public State(State state_p) {
+ // Init
+ _template = state_p._template;
+
+ // Allocate
+ _states = _template.allocate();
+
+ // And copy
+ loadFrom(state_p);
+ }
+
+ /** Load values. */
+ public void loadFrom(State state_p) {
+ // Just copy it
+ System.arraycopy(state_p._states, 0, _states, 0, _states.length);
+ }
+
+ /**
+ * Play by modifying this state.
+ * @param index_p
+ * @param value_p
+ */
+ public void play(int index_p, int value_p) {
+ // Mark the new position.
+ clearBits(index_p, _template.VALUE_MASK);
+ clearBits(index_p, _template.ALL_AVAILABLE_EXTRACTOR);
+ markBits(index_p, value_p);
+
+ // Propagate forbidden move to neighborhood
+ int [][] indexes = _template.NEIGHBOURGHOODS[index_p];
+ int extractor = _template.VALUE_AVAILABLE_EXTRACTOR[value_p];
+ for(int value=0; value<_template.maxValue; value++) {
+ for(int cIndex=0; cIndex<3; cIndex++) { // LINE/COL/BOXES
+ clearBits(indexes[cIndex][value], extractor);
+ }
+ }
+ }
+
+ /**
+ * Play by modifying this state.
+ * Stops when a position without allowed move is detected.
+ * @param index_p
+ * @param value_p
+ */
+ public boolean playWhilePossible(int index_p, int value_p) {
+ // TODO - define CONNECTED_INDEX (summing line, row and boxe) for every index (in Template)
+ // and rewrite in one loop
+
+ // Mark the new position.
+ clearBits(index_p, _template.VALUE_MASK | _template.ALL_AVAILABLE_EXTRACTOR);
+ markBits(index_p, value_p);
+
+ // Propagate forbidden move to neighborhood
+ int [][] indexes = _template.NEIGHBOURGHOODS[index_p];
+ int extractor = _template.VALUE_AVAILABLE_EXTRACTOR[value_p];
+ for(int value=0; value<_template.maxValue; value++) {
+ for(int cIndex=0; cIndex<3; cIndex++) { // LINE/COL/BOXES
+ int finalIndex = indexes[cIndex][value];
+ clearBits(finalIndex, extractor);
+ // Stop if...
+ // the target cell (the one we're clearing marks) is free but shows
+ // no more available values.
+ if(isFree(finalIndex) && ((_states[finalIndex] & _template.ALL_AVAILABLE_EXTRACTOR) == 0)) {
+ return false;
+ }
+ }
+ }
+
+ // OK
+ return true;
+ }
+
+ public void clean(int index_p) {
+ // Let's get a copy of the current position
+ State clean = new State(_template);
+
+ // Let's clean the requested position
+ markBits(index_p, _template.FREE_VALUE);
+
+ // And start rebuilding
+ for(int i = 0; i<_template.maxIndex; i++) {
+ // Check it
+ if(!isFree(i)) {
+ clean.play(i, getValue(i));
+ }
+
+ // Copy marks
+ clean.markBits(i, _states[i] & _template.ORIGINAL_POSITION);
+ clean.markBits(i + _template.MARK1_OFFSET, _states[i + _template.MARK1_OFFSET] & _template.MARK_MASK);
+ clean.markBits(i + _template.MARK2_OFFSET, _states[i + _template.MARK2_OFFSET] & _template.MARK_MASK);
+ }
+
+ // get new values
+ _states = clean._states;
+ }
+
+ /** Check if free.*/
+ public boolean isFree(int index_p) {
+ return checkBit(index_p, _template.FREE_VALUE);
+ }
+
+ /** Check if a move is allowed. */
+ public boolean isAllowed(int index_p, int value_p) {
+ return checkBit(index_p, _template.VALUE_AVAILABLE_EXTRACTOR[value_p]);
+ }
+
+ /** Get a value.
+ * @param index_p
+ * @return the value but 0 if it's free !
+ */
+ public int getValue(int index_p) {
+ return _states[index_p] & _template.VALUE_MASK;
+ }
+
+ /**
+ * @param index case
+ * @param value to scan for
+ * @return the mark state 0, 1, 2 or 3 for both marks
+ */
+ public int getMark(int index_p, int value_p) {
+ // Output
+ int output = 0;
+
+ // Read mark 1
+ if(checkBit(index_p + _template.MARK1_OFFSET, _template.MARK1_EXTRACTOR[value_p])) {
+ output = Template.STRIKE;
+ }
+
+ // Read mark 2
+ if(checkBit(index_p + _template.MARK2_OFFSET, _template.MARK2_EXTRACTOR[value_p])) {
+ output += Template.HIGHLIGHT;
+ }
+
+ // Ok
+ return output;
+ }
+
+ public void setMark(int index_p, int value_p, int mark_p) {
+ // Mark 1
+ if((mark_p & 1) != 0) {
+ markBits(index_p + _template.MARK1_OFFSET, _template.MARK1_EXTRACTOR[value_p]);
+ } else {
+ clearBits(index_p + _template.MARK1_OFFSET, _template.MARK1_EXTRACTOR[value_p]);
+ }
+
+ // Mark 2
+ if((mark_p & 2) != 0) {
+ markBits(index_p + _template.MARK2_OFFSET, _template.MARK2_EXTRACTOR[value_p]);
+ } else {
+ clearBits(index_p + _template.MARK2_OFFSET, _template.MARK2_EXTRACTOR[value_p]);
+ }
+ }
+
+ /** Mark this has the original position .*/
+ public void registerOriginalPosition() {
+ for(int index=0; index<_template.maxIndex; index++) {
+ // If free
+ if(isFree(index)) {
+ clearBits(index, _template.ORIGINAL_POSITION);
+ } else {
+ markBits(index, _template.ORIGINAL_POSITION);
+ }
+ }
+ }
+
+ public boolean isOriginalPosition(int index_p) {
+ return checkBit(index_p, _template.ORIGINAL_POSITION);
+ }
+
+ public Template getTemplate() {
+ return _template;
+ }
+
+
+ /** Convenience method to check a given bit. */
+ private boolean checkBit(int index_p, int bit_p) {
+ return (_states[index_p] & bit_p) == bit_p;
+ }
+
+ /** clear bits .*/
+ private void clearBits(int index_p, int bits_p) {
+ _states[index_p] = _states[index_p] & ~bits_p;
+ }
+
+ /** Mark a position. */
+ private void markBits(int index, int bits_p) {
+ _states[index] = _states[index] | bits_p;
+ }
+
+ int[] getRaw() {
+ return _states;
+ }
+
+
+ /**
+ * Convenience method to test a value.
+ * @param index_p
+ * @param value_p
+ * @return true if free, allowed, not striked
+ */
+ public boolean isAvailable(int index_p, int value_p) {
+ return isFree(index_p) && isAllowed(index_p, value_p) &&
+ ((getMark(index_p, value_p) & Template.STRIKE) == 0);
+ }
+
+ /**
+ * Clear all marks
+ */
+ public void clearMarks() {
+ for(int index=0; index<_template.maxIndex; index++) {
+ clearBits(index + _template.MARK1_OFFSET, _template.MARK_MASK);
+ clearBits(index + _template.MARK2_OFFSET, _template.MARK_MASK);
+ }
+
+ }
+
+ /**
+ * This is a custom Serialization (for the fun of it).
+ * @param out_p output stream
+ * @throws IOException
+ */
+ private void writeObject(ObjectOutputStream out_p) throws IOException {
+ // We'll write template, then states
+ // Template
+ out_p.writeShort(_template.rows);
+ out_p.writeShort(_template.columns);
+
+ // And states
+ for (int i = 0; i < _states.length; i++) {
+ int aValue = _states[i];
+ out_p.writeInt(aValue);
+ }
+ }
+
+ /**
+ * This is a custom serialization.
+ * @param in_p stream to read from.
+ * @throws IOException
+ * @throws ClassNotFoundException
+ */
+ @SuppressWarnings("unused")
+ private void readObject(java.io.ObjectInputStream in_p) throws IOException, ClassNotFoundException {
+ // Read template
+ int rows = in_p.readShort();
+ int columns = in_p.readShort();
+ _template = TemplateFactory.getTemplate(rows, columns);
+
+ // Allocate
+ _states = _template.allocate();
+
+ // read state
+ for (int i = 0; i < _states.length; i++) {
+ _states[i] = in_p.readInt();
+ }
+ }
+
+ // For serialization purpose
+ @SuppressWarnings("unused")
+ private State() {
+ // Empty block
+ }
+
+// public String toString() {
+// StringBuffer sb = new StringBuffer();
+// for(int y=0;y<_template.rows;y++) {
+// for(int x=0;x<_template.columns;x++) {
+// int index = y*_template.columns+x;
+// int value = _states[index];
+// int v = value & 0xFF;
+// if((value & 0x10) > 0) sb.append(" ");
+// else sb.append(Integer.toString(v));
+// sb.append("|");
+// }
+// sb.append("\n");
+// }
+// return sb.toString();
+// }
+}
--- /dev/null
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.ia.core;
+
+/**
+ *
+ * @author christophe.marchand
+ */
+public class StateModel {
+ private State state;
+ private LocationInformation[][] locations;
+
+ public StateModel(State state) {
+ super();
+ this.state=state;
+ initialize();
+ }
+ protected void initialize() {
+ int size = getGridWidth();
+ locations = new LocationInformation[size][size];
+ Template t = state.getTemplate();
+ String[][] array = new String[t.maxValue][t.maxValue];
+ for(int index=0; index<t.maxIndex; index++) {
+ int row = t.indexToRow(index);
+ int col = t.indexToColumn(index);
+// if(row<)
+ if(!state.isFree(index)) {
+ locations[row][col] = new LocationInformation(state.getValue(index)+1);
+ //Integer.toString(st.getValue(index)+1);
+ } else {
+ locations[row][col] = new LocationInformation(-1);
+ }
+ }
+ }
+ public boolean isWritable(int row, int col) { return !locations[row][col].isOriginal(); }
+// public boolean isFree(int row, int col) { return state.isFree(locations[row][col].getIndex()); }
+ public boolean isValueAllowed(int row, int col, String value) {
+ try {
+// return state.isAllowed(locations[row][col].getIndex(), Integer.valueOf(value));
+ int v = Integer.parseInt(value);
+ if (0 < v && v < 10) {
+ // check if row or col already contains value
+ for(int i=0; i<9; i++) {
+ if(i!=row && value.equals(locations[i][col].getValue())) return false;
+ if(i!=col && value.equals(locations[row][i].getValue())) return false;
+ }
+ int sqStartRow = (row / 3)*3;
+ int sqStartCol = (col / 3)*3;
+ for(int i=sqStartRow;i<sqStartRow+3;i++) {
+ for(int j=sqStartCol;j<sqStartCol+3;j++) {
+ if(i!=row && j!= col && value.equals(locations[i][j].getValue())) return false;
+ }
+ }
+ return true;
+ } else return false;
+ } catch(Exception ex) {
+ return false;
+ }
+ }
+ public void setValueAt(int row, int col, String value) {
+ locations[row][col].setValue(value);
+ }
+ public String getValueAt(int row, int col) { return locations[row][col].getValue(); }
+ public int getGridWidth() { return state.getTemplate().maxValue; }
+ public int getGridHeight() { return getGridWidth(); }
+
+ private class LocationInformation {
+// private int stateIndex;
+ private boolean original = false;
+ private int value = -1;
+ public LocationInformation(final int value) {
+ super();
+ this.value=value;
+ original = (value!= -1);
+ }
+ public boolean isOriginal() { return original; }
+ public boolean isWrittable() { return !isOriginal(); }
+ public String getValue() { if(value!= -1) return Integer.toString(value); return null; }
+ public void setValue(String v) {
+ try {
+ value = Integer.parseInt(v);
+ } catch(Exception ex) {
+ value = -1;
+ }
+ }
+ }
+}
--- /dev/null
+package fr.gouv.finances.cp.xemelios.ui.ia.core;
+
+/**
+ * Given an index, gives back the symetrical index.
+ * @author Tchok
+ */
+public class Symetrizer {
+ Template _template;
+
+ public Symetrizer(Template template_p) {
+ _template = template_p;
+ }
+
+ /**
+ * Computes the symetrical index.
+ * @param index_p source index
+ * @return target index.
+ */
+ public int getIndex(int index_p) {
+ //return index_p;
+ return _template.maxIndex - (index_p + 1);
+ }
+}
--- /dev/null
+package fr.gouv.finances.cp.xemelios.ui.ia.core;
+
+
+/**
+ * Template for the data encoding. Handles sudoku up to 9x9
+ * A bit complex, I admit it!
+ * Bit use:
+ * <PRE>
+ * 1-4 : value
+ * // 5 : free tag ( 1 means free)
+ * 5 : start position marker (1 means yes)
+ * 6-14 : possibility to play a value (1 is for yes)
+ * 15-23: mark 1
+ * 24-32: mark 2
+ * </PRE>
+ * @author Tchok.
+ */
+public class Template {
+ // Predefined
+ public static final Template T22 = new Template(2, 2, false, false);
+ public static final Template T23 = new Template(2, 3, true, true);
+// public static final Template T32 = new Template(3, 2);
+ public static final Template T33 = new Template(3, 3, true, true);
+
+ /** The strike mark. */
+ static public final int STRIKE = 1;
+
+ /** The Highlight mark */
+ static public final int HIGHLIGHT = 2;
+
+ /** Number of columns. */
+ public final int columns;
+
+ /** Number of row; */
+ public final int rows;
+
+ /** Max value. */
+ public final int maxValue;
+
+ /** Max square index */
+ public final int maxIndex;
+
+ /** True for a symetrical board. */
+ public final boolean symetrical;
+
+ /** True if reducer is allowed. */
+ public final boolean reducable;
+
+ // Common name
+ public final String name;
+
+ // Initial value
+ int INITIAL_VALUE;
+
+ // Empty indicator (1111)
+ int FREE_VALUE;
+
+ // All marks mask
+ int MARK_MASK;
+
+ // First mark extractors
+ int MARK1_EXTRACTOR[];
+
+ // Secondary marks extractors
+ int MARK2_EXTRACTOR[];
+
+ // To check if a value is allowed
+ int VALUE_AVAILABLE_EXTRACTOR[];
+
+ // Available extractor
+ int ALL_AVAILABLE_EXTRACTOR;
+
+ // Value mask
+ int VALUE_MASK;
+
+ // Original position marker
+ int ORIGINAL_POSITION;
+
+ // Offset to reach the int with mark 1 bits
+ int MARK1_OFFSET;
+
+ // Offset to reach mark 2 bits
+ int MARK2_OFFSET;
+
+ // The column neighbourhood
+ public int COLUMNS_NEIGBOURGHOOD[][];
+ public int INDEX_TO_COLUMN[];
+
+ // The lines
+ public int LINE_NEIGHBOURGHOOD[][];
+ public int INDEX_TO_LINE[];
+
+ // The boxes
+ public int BOXES_NEIGBOURGHOOD[][];
+ public int INDEX_TO_BOX[];
+
+ /** The neighbourghoods
+ * <P>Say for box with index i, you may get
+ * <PRE>
+ * NEIGHBOURGHOODS[i][0] for the whole line
+ * NEIGHBOURGHOODS[i][1] for the whole column
+ * NEIGHBOURGHOODS[i][2] for the whole box
+ * </PRE>
+ * </P>
+ **/
+ public int NEIGHBOURGHOODS[][][];
+
+ /**
+ * Set the internal constants.
+ */
+ protected void fillBaseFields() {
+ // Values are in bits 1-4
+ VALUE_MASK = 15;
+
+ // Max value is 9 so we may use 15
+ FREE_VALUE = 15;
+
+ // Bit 5 is for the 'original position' marker
+ ORIGINAL_POSITION = 1 << 4;
+
+ // Byte offset to reach markers
+ MARK1_OFFSET = 0;
+ MARK2_OFFSET = 0;
+ }
+
+ /** Get one
+ * @param row_p rows in a big square
+ * @param column_p columns in a big square
+ * @param symetrical_p true for a symetrical board
+ */
+ protected Template(int row_p, int column_p, boolean symetrical_p, boolean reducable_p) {
+ // Store shape
+ columns = column_p;
+ rows = row_p;
+ symetrical = symetrical_p;
+ reducable = reducable_p;
+
+ // Build name
+ name = new String(column_p + "x" + row_p); //$NON-NLS-1$
+
+ // Simple extra computation
+ maxValue = row_p * column_p;
+ maxIndex = maxValue * maxValue;
+
+ // Fill constants
+ fillBaseFields();
+
+ // Fill value extractors
+ fillValueExtractors();
+
+ // Fill mark extractor
+ fillMarkExtractors();
+
+ // Fill neighbourghoods
+ fillNeigbourghoods();
+ }
+
+ protected void fillMarkExtractors() {
+ MARK1_EXTRACTOR = new int[maxValue];
+ MARK2_EXTRACTOR = new int[maxValue];
+ MARK_MASK = 0;
+ for(int i=0; i<maxValue; i++) {
+ MARK1_EXTRACTOR[i] = 1 << (14 + i);
+ MARK2_EXTRACTOR[i] = 1 << (23 + i);
+ MARK_MASK |= MARK1_EXTRACTOR[i];
+ MARK_MASK |= MARK2_EXTRACTOR[i];
+ }
+ }
+
+ protected void fillValueExtractors() {
+ // Fill Extractors
+ INITIAL_VALUE = FREE_VALUE;
+ ALL_AVAILABLE_EXTRACTOR = 0;
+ VALUE_AVAILABLE_EXTRACTOR = new int[maxValue];
+ for(int i=0; i<VALUE_AVAILABLE_EXTRACTOR.length; i++) {
+ VALUE_AVAILABLE_EXTRACTOR[i] = 1 << (i + 5);
+ INITIAL_VALUE |= VALUE_AVAILABLE_EXTRACTOR[i];
+ ALL_AVAILABLE_EXTRACTOR |= VALUE_AVAILABLE_EXTRACTOR[i];
+ }
+ }
+
+ private void fillNeigbourghoods() {
+ // Fill line neighbourghood
+ LINE_NEIGHBOURGHOOD = new int[maxValue][maxValue];
+ INDEX_TO_LINE = new int[maxIndex];
+ for(int line=0; line<maxValue; line++) {
+ for(int col=0; col<maxValue; col++) {
+ int index = line * maxValue + col;
+ LINE_NEIGHBOURGHOOD[line][col] = index;
+ INDEX_TO_LINE[index] = line;
+ }
+ }
+
+ // Fill columns neighbourghood
+ COLUMNS_NEIGBOURGHOOD = new int[maxValue][maxValue];
+ INDEX_TO_COLUMN = new int[maxIndex];
+ for(int line=0; line<maxValue; line++) {
+ for(int col=0; col<maxValue; col++) {
+ int index = line * maxValue + col;
+ COLUMNS_NEIGBOURGHOOD[col][line] = index;
+ INDEX_TO_COLUMN[index] = col;
+ }
+ }
+
+ // Fill boxes neighbourghood
+ BOXES_NEIGBOURGHOOD = new int[maxValue][maxValue];
+ INDEX_TO_BOX = new int[maxIndex];
+ for(int boxLine=0; boxLine<columns; boxLine++) {
+ for(int boxCol=0; boxCol<rows; boxCol++) {
+ // Loop in box
+ int boxIndex = boxLine * rows + boxCol;
+ for(int line=0; line<rows; line++) {
+ for(int col=0; col<columns; col++) {
+ // value in box
+ int indexInBox = line * columns + col;
+ int index = (boxLine * rows + line) * maxValue +
+ boxCol * columns + col;
+ BOXES_NEIGBOURGHOOD[boxIndex][indexInBox] = index;
+ INDEX_TO_BOX[index] = boxIndex;
+ }
+ }
+
+ }
+ }
+
+ // Fill neighbourhoods
+ NEIGHBOURGHOODS = new int[maxIndex][3][maxValue];
+ for(int index=0; index<maxIndex; index++) {
+ NEIGHBOURGHOODS[index][0] = LINE_NEIGHBOURGHOOD[INDEX_TO_LINE[index]];
+ NEIGHBOURGHOODS[index][1] = COLUMNS_NEIGBOURGHOOD[INDEX_TO_COLUMN[index]];
+ NEIGHBOURGHOODS[index][2] = BOXES_NEIGBOURGHOOD[INDEX_TO_BOX[index]];
+ }
+ }
+
+ /**
+ * Convert index to row
+ * @param index_p
+ * @return the row index
+ */
+ public int indexToRow(int index_p) {
+ return index_p / maxValue;
+ }
+
+ /**
+ * Convert index to column
+ * @param index_p
+ * @return
+ */
+ public int indexToColumn(int index_p) {
+ return index_p % maxValue;
+ }
+
+ /**
+ * Convert index to box index.
+ * @param index_p
+ * @return
+ */
+ public int indexToBox(int index_p) {
+ // Get basic
+ int line = indexToRow(index_p);
+ int col = indexToColumn(index_p);
+
+ // Transform to box indexes
+ line = line / rows;
+ col = col / columns;
+
+ // Compute box index
+ return line * rows + col;
+ }
+
+ /**
+ * @return memory to keep a state.
+ */
+ public int [] allocate() {
+ return new int[maxIndex];
+ }
+}
--- /dev/null
+package fr.gouv.finances.cp.xemelios.ui.ia.core;
+
+/**
+ * handles the available templates
+ * @author Tchok
+ */
+public class TemplateFactory {
+ static public final Template TEMPLATES[] = {
+ Template.T22,
+ Template.T23,
+// Template.T32,
+ Template.T33,
+ WideTemplate.T34
+ };
+
+ /**
+ * Get one by size.
+ * @param row_p number of rows
+ * @param column_p number of columns
+ * @return the Template or null
+ */
+ public static Template getTemplate(int row_p, int column_p) {
+ // Loop on them
+ for (int i = 0; i < TEMPLATES.length; i++) {
+ Template template = TEMPLATES[i];
+ if((template.rows == row_p) && (template.columns == column_p)) {
+ // This is it
+ return template;
+ }
+ }
+
+ // Bad luck !
+ return null;
+ }
+}
--- /dev/null
+package fr.gouv.finances.cp.xemelios.ui.ia.core;
+
+/**
+ * Template for a 'big' Sudoku. Handle Sudoku up to 5x5.
+ *
+ * Bit use (three int for a box): But bytes are entrelaced, soo bits [33-58] off the
+ * first box are in the second stripe, and soo one.
+ * <PRE>
+ * 1-5 : value
+ * 6 : start position marker (1 means yes)
+ * 7-31 : possibility to play a value
+ * 33-58 : mark 1 (stripe 2)
+ * 96-121: mark 2 (stripe 3)
+ * </PRE>
+
+ * @author Tchok
+ */
+public class WideTemplate extends Template {
+ // Predefined
+ public static final Template T34 = new WideTemplate(3, 4);
+ public static final Template T44 = new WideTemplate(4, 4);
+ public static final Template T45 = new WideTemplate(4, 5);
+ public static final Template T55 = new WideTemplate(5, 5);
+
+ // Debug stuff
+ public static final Template WIDE_TEST = new WideTemplate(2, 2);
+ /**
+ * @param row_p
+ * @param column_p
+ */
+ public WideTemplate(int row_p, int column_p) {
+ super(row_p, column_p, true, false);
+ }
+
+
+ /**
+ * Set the internal constants.
+ */
+ @Override
+ protected void fillBaseFields() {
+ // Values are in bits 1-5
+ VALUE_MASK = 31;
+
+ // Max value is 25 so we may use 31
+ FREE_VALUE = 31;
+
+ // Bit 6 is for the 'original position' marker
+ ORIGINAL_POSITION = 1 << 5;
+
+ // Byte offset to reach markers
+ MARK1_OFFSET = maxIndex;
+ MARK2_OFFSET = 2 * maxIndex;
+ }
+
+ @Override
+ protected void fillMarkExtractors() {
+ MARK1_EXTRACTOR = new int[maxValue];
+ MARK2_EXTRACTOR = new int[maxValue];
+ MARK_MASK = 0;
+ for(int i=0; i<maxValue; i++) {
+ MARK1_EXTRACTOR[i] = 1 << i;
+ MARK2_EXTRACTOR[i] = 1 << i;
+ MARK_MASK |= MARK1_EXTRACTOR[i];
+ MARK_MASK |= MARK2_EXTRACTOR[i];
+ }
+ }
+
+ @Override
+ protected void fillValueExtractors() {
+ // Fill Extractors
+ INITIAL_VALUE = FREE_VALUE;
+ ALL_AVAILABLE_EXTRACTOR = 0;
+ VALUE_AVAILABLE_EXTRACTOR = new int[maxValue];
+ for(int i=0; i<VALUE_AVAILABLE_EXTRACTOR.length; i++) {
+ VALUE_AVAILABLE_EXTRACTOR[i] = 1 << (i + 6);
+ INITIAL_VALUE |= VALUE_AVAILABLE_EXTRACTOR[i];
+ ALL_AVAILABLE_EXTRACTOR |= VALUE_AVAILABLE_EXTRACTOR[i];
+ }
+ }
+
+
+ /**
+ * @return memory to keep a state.
+ */
+ @Override
+ public int [] allocate() {
+ return new int[maxIndex * 3];
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 Y.Laurelut - yann.laurelut@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui.importDialog;
+
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.List;
+
+import javax.swing.JButton;
+import javax.swing.JDialog;
+import javax.swing.JFrame;
+import javax.swing.JScrollPane;
+import javax.swing.JToolBar;
+import javax.swing.ScrollPaneConstants;
+import javax.swing.table.TableColumn;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.log4j.Logger;
+import org.jdesktop.swingx.JXTreeTable;
+
+import fr.gouv.finances.cp.utils.ui.IhmFactory;
+import fr.gouv.finances.dgfip.xemelios.ui.ImageResources;
+import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode;
+
+
+/**
+ * Provides the mechanism to call a modal (blocking)
+ * dialog window, that will show the user all the files found in directories,
+ * and let him/her choose which files to really import.
+ * The "Ok" button at the bottom lets the user close the window, and
+ * returns the information in a <code>List<ImportFile></code>.
+ * <br>Note: this class is a wrapper, the actual work is done in InnerImportDialog.
+ *
+ * @author Yann Laurelut
+ */
+public class ImportDialog {
+ private final static Logger logger = Logger.getLogger(ImportDialog.class);
+
+ private JFrame parent = null;
+ private String title = "";
+
+ /** The list of results passed back to the caller of ImportDialog */
+ protected List<ImportFile> resultList = new ArrayList<ImportFile>();
+
+ /**
+ * Constructor.
+ * @param parent The parent frame for this dialog
+ * @param title Title of the dialog window
+ */
+ public ImportDialog(JFrame parent, String title) {
+ this.parent = parent;
+ this.title = title;
+ }
+
+ /**
+ * Displays the modal dialog box.
+ * @return the list of files to be imported
+ */
+ public List<ImportFile> startDialog(File rootDir, String[] extensions) {
+ ImportFileTreeTableModel model = createImportFileModel(rootDir, extensions);
+ InnerImportDialog d = new InnerImportDialog(model, parent, title, true);
+ d.setVisible(true);
+
+ return resultList;
+ }
+
+ /**
+ * Provides a modal dialog window, presenting the user with
+ * all the files found suitable for import, starting from
+ * a given path and drilling down the directories.
+ *
+ * @author Yann Laurelut
+ */
+ class InnerImportDialog extends JDialog implements ActionListener {
+ JButton boutonExpandAll, boutonCollapseAll, boutonSelectAll, boutonSelectNone, boutonOk, boutonAnnuler;
+ // Constants
+ static final long serialVersionUID = 345134599;
+
+ private JXTreeTable treeTable;
+ private ImportFileTreeTableModel importFileTreeTableModel = null;
+
+ /**
+ * Default constructor
+ * @param model The data model for this TreeTable
+ * @param parent The parent of this dialog
+ * @param title The title of the dialog
+ * @param modal To indicate whether this dialog is modal or not
+ */
+ @SuppressWarnings("serial")
+ public InnerImportDialog(ImportFileTreeTableModel model, JFrame parent, String title, boolean modal) {
+ super(parent, title, modal);
+ importFileTreeTableModel = model;
+ treeTable = new JXTreeTable(importFileTreeTableModel);
+ JScrollPane jScrollPane1 = new javax.swing.JScrollPane();
+
+ setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+ jScrollPane1.setViewportView(treeTable);
+ jScrollPane1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
+
+ boutonOk = new JButton("Ok");
+ boutonOk.addActionListener(this);
+ boutonAnnuler = new JButton("Annuler");
+ boutonAnnuler.addActionListener(this);
+
+ JToolBar toolbar = new JToolBar(JToolBar.HORIZONTAL);
+ toolbar.setFloatable(false);
+ toolbar.setRollover(true);
+// IhmFactory ihmFactory = IhmFactory.newInstance();
+ boutonExpandAll = new JButton(IhmFactory.getIconFromResource(ImageResources.EXPAND_ALL));
+ boutonExpandAll.setToolTipText("Déplier l'arborescence");
+ boutonExpandAll.addActionListener(this);
+ toolbar.add(boutonExpandAll);
+ boutonCollapseAll = new JButton(IhmFactory.getIconFromResource(ImageResources.COLLAPSE_ALL));
+ boutonCollapseAll.setToolTipText("Replier l'arborescence");
+ boutonCollapseAll.addActionListener(this);
+ toolbar.add(boutonCollapseAll);
+ boutonSelectAll = new JButton(IhmFactory.getIconFromResource(ImageResources.SELECT_ALL));
+ boutonSelectAll.setToolTipText("Tout sélectionner");
+ boutonSelectAll.addActionListener(this);
+ toolbar.add(boutonSelectAll);
+ boutonSelectNone = new JButton(IhmFactory.getIconFromResource(ImageResources.SELECT_NONE));
+ boutonSelectNone.setToolTipText("Tout désélectionner");
+ boutonSelectNone.addActionListener(this);
+ toolbar.add(boutonSelectNone);
+
+
+ org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
+ .add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 434, Short.MAX_VALUE)
+ .add(layout.createSequentialGroup()
+ .add(boutonAnnuler)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(boutonOk)))
+ .addContainerGap())
+ .add(toolbar, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 458, Short.MAX_VALUE)
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
+ .add(toolbar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 25, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 365, Short.MAX_VALUE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(boutonOk)
+ .add(boutonAnnuler))
+ .addContainerGap())
+ );
+ pack();
+
+ // init for the toolbar
+ setSize(500, 400);
+
+ setLocationRelativeTo(parent);
+
+ // To beautify things, we specify column widths
+ TableColumn col = treeTable.getColumnModel().getColumn(1);
+ col.setPreferredWidth(75);
+ col.setMinWidth(60);
+ col = treeTable.getColumnModel().getColumn(0);
+ col.setMinWidth(200);
+ col.setPreferredWidth(380);
+ }
+
+ /**
+ * Called when a button is clicked
+ */
+ public void actionPerformed(ActionEvent ae) {
+ Object cmd = ae.getSource();
+ if(cmd.equals(boutonExpandAll)) {
+ treeTable.expandAll();
+ } else if(cmd.equals(boutonCollapseAll)) {
+ treeTable.collapseAll();
+ } else if(cmd.equals(boutonSelectAll)) {
+ importFileTreeTableModel.selectAll();
+ } else if(cmd.equals(boutonSelectNone)) {
+ importFileTreeTableModel.selectNone();
+ } else if(cmd.equals(boutonOk)) {
+ resultList = importFileTreeTableModel.getFilesToImportList();
+ setVisible(false);
+ } else if(cmd.equals(boutonAnnuler)) {
+ setVisible(false);
+ }
+ }
+
+ }
+ // end of class InnerImportDialog
+ /**
+ * Drill through the directory tree, starting from the given folder,
+ * and creates a Model of ImportFile to be used for display in the
+ * ImportDialog.
+ * @param rootDir The directory to start searching from
+ * @param extensions The extensions of files we are looking for (eg "xml", "xhl"...)
+ * @return A Model of ImportFile
+ */
+ public ImportFileTreeTableModel createImportFileModel(File rootDir, String[] extensions) {
+ ImportFileTreeTableModel model = null;
+
+ if(!rootDir.isDirectory()) {
+ // jeter une exception
+ return model;
+ }
+ ImportFile racineDir = new ImportFile(rootDir);
+ MyTreeNode racine = splitPath(racineDir, racineDir);
+
+ Iterator iter = FileUtils.iterateFiles(rootDir, extensions, true);
+ ImportFile fichierImport = null;
+ // Pour chaque fichier trouvé, on crée un noeud dans l'arborescence
+ while(iter.hasNext()) {
+ File fichier = (File)iter.next();
+ fichierImport = new ImportFile(fichier);
+ addSorted(racine, splitPath(fichierImport,racineDir));
+ }
+ model = new ImportFileTreeTableModel(racine);
+
+ return model;
+ }
+
+ /**
+ * Creates a tree structure of DefaultMutableTreeNodes to match the structure
+ * of directories in the given ImportFile, up to directory <tt>upToDir</tt>. <br>
+ * For example, if the path of the given ImportFile is "/", only
+ * one TreeNode will be returned.<br>
+ * If the path is "/foo/bar/file1.xml", there will be 3 imbricated
+ * TreeNodes, one for directory "foo", one for directory "bar", and
+ * a final one for file "file1.xml".
+ * @param fichierImport The ImportFile with full path
+ * @return a TreeNode being the root of the directory structure for
+ * this ImportFile, with children TreeNodes accordingly.
+ */
+ private MyTreeNode splitPath(ImportFile fichierImport, ImportFile upToDir) {
+ MyTreeNode currentNode = new MyTreeNode(fichierImport);
+ if(upToDir.getFile().equals(fichierImport.getFile())) return currentNode;
+ File upDir = upToDir.getFile();
+ File parentFile;
+ while( (parentFile=((ImportFile)currentNode.getUserObject()).getFile().getParentFile())!=null) {
+ ImportFile parentImportFile = new ImportFile(parentFile);
+ MyTreeNode parentNode = new MyTreeNode(parentImportFile);
+ parentNode.add(currentNode);
+ currentNode = parentNode;
+ if(parentFile.equals(upDir)) break;
+ }
+
+ return currentNode;
+ }
+
+ /**
+ * Adds a new node to the tree structure under the given root node.
+ * It does not add the node directly under the root, but goes through
+ * the hierarchy of nodes under the root, to insert the new one without
+ * duplicating any directory.
+ * @param racine root node to add the other node to
+ * @param newNode The new leaf node, with complete tree structure to the root, to be added
+ */
+ private void addSorted(MyTreeNode racine, MyTreeNode newNode) {
+ MyTreeNode newNodeBrowser = newNode;
+ MyTreeNode rootBrowser = racine;
+ boolean continuer = true;
+
+ while(continuer) {
+ ImportFile newNodeBrowserFile = (ImportFile)newNodeBrowser.getUserObject();
+ ImportFile rootBrowserFile = (ImportFile)rootBrowser.getUserObject();
+
+ if(newNodeBrowserFile.equals(rootBrowserFile)) {
+ newNodeBrowser = (MyTreeNode)newNodeBrowser.getChildAt(0);
+ MyTreeNode rootSon = matchingChild(newNodeBrowser, rootBrowser);
+ if(rootSon!=null) {
+ // on continue avec ce descendant de root
+ rootBrowser = rootSon;
+ } else {
+ continuer = false;
+ }
+ } else {
+ continuer = false;
+ }
+ }
+ // on ajoute notre noeud à l'emplacement actuel
+ rootBrowser.add(newNodeBrowser);
+ }
+
+ /**
+ * Returns a child of the given rootBrowser if it is equal to the given newNodeBrowser.
+ * The equality is defined as: if there exists a child of rootBrowser, such as:<br>
+ * <code>((ImportFile)child.getUserObject()).equals((ImportFile)newNodeBrowser.getUserObject())</code>
+ * @param newNodeBrowser a DefaultMutableTreeNode that we want to insert in the tree
+ * @param rootBrowser the current node we want to plug the above node to
+ * @return the child of rootBrowser equals to newNodeBrowser if one is found, null otherwise.
+ */
+ private MyTreeNode matchingChild(DefaultMutableTreeTableNode newNodeBrowser, DefaultMutableTreeTableNode rootBrowser) {
+ MyTreeNode result = null;
+ ImportFile newNodeBrowserFile = (ImportFile)newNodeBrowser.getUserObject();
+
+ for(Enumeration enumerator = rootBrowser.children(); enumerator.hasMoreElements() && result==null; ) {
+ MyTreeNode child = (MyTreeNode)enumerator.nextElement();
+ ImportFile childFile = (ImportFile)child.getUserObject();
+ if(childFile.equals(newNodeBrowserFile)) {
+ result = child;
+ }
+ }
+ return result;
+ }
+ public class MyTreeNode extends DefaultMutableTreeTableNode {
+ private ImportFile importFile;
+ public MyTreeNode(ImportFile iFile) {
+ super(iFile);
+ this.importFile=iFile;
+ }
+ @Override
+ public boolean isLeaf() {
+ boolean ret = !(importFile.getFile().isDirectory());
+// logger.debug("isLeaf("+importFile.getFile().getName()+")->"+ret);
+// if(ret) logger.debug("\thas "+getChildCount()+" childs");
+ return ret;
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 Y.Laurelut - yann.laurelut@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui.importDialog;
+
+import java.io.File;
+
+
+/**
+ * Represents a file that is candidate for import.
+ * This class is used in the ImportFileTreeTableModel, in each node.
+ *
+ * @author Yann Laurelut
+ */
+public class ImportFile {
+
+ /** to mark this file for import */
+ private boolean toBeImported = true;
+ /** the underlying file */
+ private File fichier = null;
+
+ public ImportFile(File fic) {
+ this.fichier = fic;
+ }
+
+ public boolean isFile() {
+ return fichier.isFile();
+ }
+ public String getName() {
+ return fichier.getName();
+ }
+ public String getPath() {
+ return fichier.getPath();
+ }
+ public boolean isToBeImported() {
+ return toBeImported;
+ }
+ public void setToBeImported(boolean toBeImported) {
+ this.toBeImported = toBeImported;
+ }
+ public File getFile() {
+ return fichier;
+ }
+ public void setFile(File fic) {
+ this.fichier = fic;
+ }
+
+ /**
+ * Returns the last path element (directory)
+ * of this full path
+ * @return a path, which can be an empty String
+ */
+ public String getRelativePath() {
+ String result = "";
+ String pathSeparator = System.getProperty("file.separator");
+ if(isFile()) {
+ result = this.getName();
+ } else {
+ String path = this.getPath();
+ result = path.substring(path.lastIndexOf(pathSeparator)+1);
+ }
+ return result;
+ }
+
+ @Override
+ public String toString() {
+ return fichier.getName();
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ boolean result = false;
+ if(other instanceof ImportFile) {
+ ImportFile otherFile = (ImportFile)other;
+ result = getFile().equals(otherFile.getFile());
+ }
+ return result;
+ }
+}
+
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 Y.Laurelut - yann.laurelut@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui.importDialog;
+
+import java.util.Enumeration;
+import java.util.List;
+import java.util.Vector;
+
+import javax.swing.event.TreeModelEvent;
+import javax.swing.event.TreeModelListener;
+import javax.swing.tree.DefaultMutableTreeNode;
+//import javax.swing.tree.TreeNode;
+
+import javax.swing.tree.TreePath;
+import org.apache.log4j.Logger;
+import org.jdesktop.swingx.treetable.DefaultTreeTableModel;
+import org.jdesktop.swingx.treetable.TreeTableNode;
+
+/**
+ * Model for the TreeTable used in the ImportDialog.
+ *
+ * @author Yann Laurelut
+ */
+public class ImportFileTreeTableModel extends DefaultTreeTableModel {
+
+ private static final Logger logger = Logger.getLogger(ImportFileTreeTableModel.class);
+ /** Constants for the columns indices */
+ private final static int NOM_FICHIER = 0;
+ private final static int A_IMPORTER = 1;
+
+ public ImportFileTreeTableModel(TreeTableNode node) {
+ super(node);
+ }
+
+ @Override
+ public int getColumnCount() {
+ return 2;
+ }
+
+ @Override
+ public Class getColumnClass(int column) {
+ if (column == A_IMPORTER) {
+ return Boolean.class;
+ } else {
+ return super.getColumnClass(column);
+ }
+ }
+
+ /**
+ * Returns which object is displayed in this column.
+ */
+ @Override
+ public Object getValueAt(Object node, int column) {
+ Object result = null;
+ if (node instanceof DefaultMutableTreeNode) {
+ DefaultMutableTreeNode defNode = (DefaultMutableTreeNode) node;
+ if (defNode.getUserObject() instanceof ImportFile) {
+ ImportFile fichier = (ImportFile) defNode.getUserObject();
+ switch (column) {
+ case NOM_FICHIER:
+ result = fichier.getName();
+ break;
+ case A_IMPORTER:
+ result = new Boolean(fichier.isToBeImported());
+ break;
+ }
+ }
+ }
+ return result;
+ }
+
+ /**
+ * What the TableHeader displays when the Table is in a JScrollPane.
+ */
+ @Override
+ public String getColumnName(int column) {
+ String res = "";
+ switch (column) {
+ case NOM_FICHIER:
+ res = "Nom de fichier";
+ break;
+ case A_IMPORTER:
+ res = "Importer";
+ break;
+ }
+ return res;
+ }
+
+ /**
+ * Tells if a column can be edited.
+ */
+ @Override
+ public boolean isCellEditable(Object node, int column) {
+ if (column == A_IMPORTER) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * Called when done editing a cell.
+ */
+ @Override
+ public void setValueAt(Object value, Object node, int column) {
+ if (node instanceof DefaultMutableTreeNode) {
+ DefaultMutableTreeNode defNode = (DefaultMutableTreeNode) node;
+ if (defNode.getUserObject() instanceof ImportFile) {
+ ImportFile fichier = (ImportFile) defNode.getUserObject();
+ switch (column) {
+ case NOM_FICHIER: // should never happen in our case
+ break;
+ case A_IMPORTER:
+ boolean valeur = ((Boolean) value).booleanValue();
+ // on coche la case pour le fichier ou répertoire cliqué
+ ((ImportFile) defNode.getUserObject()).setToBeImported(valeur);
+ // si c'est pour cocher, on propage au dessus
+ if (valeur) {
+ propagateCheckValueAbove(valeur, defNode);
+ }
+ // dans le cas d'un répertoire, on propage aussi vers le bas
+ if (!fichier.isFile()) {
+ propagateCheckValueBelow(valeur, defNode);
+ }
+ nodesChanged((DefaultMutableTreeNode) getRoot());
+ break;
+ }
+ }
+ }
+ }
+
+ /**
+ * Sets the value of the checkbox to all the nodes above
+ * the given one, up to the root.
+ * @param value To know if this node needs to be imported
+ * @param node The starting node
+ */
+ private void propagateCheckValueAbove(boolean value, DefaultMutableTreeNode node) {
+ ((ImportFile) node.getUserObject()).setToBeImported(value);
+ if (node.getParent() != null) {
+ propagateCheckValueAbove(value, (DefaultMutableTreeNode) node.getParent());
+ }
+ }
+
+ /**
+ * Sets the value of the checkbox to all the nodes below
+ * the given one, every child recursively.
+ * @param value To know if this node needs to be imported
+ * @param node The starting node
+ */
+ private void propagateCheckValueBelow(boolean value, DefaultMutableTreeNode node) {
+ ((ImportFile) node.getUserObject()).setToBeImported(value);
+ if (node.getChildCount() > 0) {
+ for (Enumeration enumerator = node.children(); enumerator.hasMoreElements();) {
+ DefaultMutableTreeNode child = (DefaultMutableTreeNode) enumerator.nextElement();
+ propagateCheckValueBelow(value, child);
+ }
+ }
+ }
+
+ /**
+ * Returns the list of the file to export.
+ * @return A List of files to export
+ */
+ public List<ImportFile> getFilesToImportList() {
+ List<ImportFile> result = new Vector<ImportFile>();
+
+ DefaultMutableTreeNode root = (DefaultMutableTreeNode) this.getRoot();
+ for (Enumeration enumerator = root.depthFirstEnumeration(); enumerator.hasMoreElements();) {
+ DefaultMutableTreeNode node = (DefaultMutableTreeNode) enumerator.nextElement();
+ ImportFile f = (ImportFile) node.getUserObject();
+ if (f.isFile() && f.isToBeImported()) {
+ result.add(f);
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * Selects all the files and directories for import
+ */
+ public void selectAll() {
+ DefaultMutableTreeNode root = (DefaultMutableTreeNode) this.getRoot();
+ for (Enumeration enumerator = root.depthFirstEnumeration(); enumerator.hasMoreElements();) {
+ DefaultMutableTreeNode node = (DefaultMutableTreeNode) enumerator.nextElement();
+ ImportFile f = (ImportFile) node.getUserObject();
+ f.setToBeImported(true);
+ }
+ nodesChanged(root);
+ }
+
+ /**
+ * Uncheck each entry, removing them
+ * from the import list
+ */
+ public void selectNone() {
+ DefaultMutableTreeNode root = (DefaultMutableTreeNode) this.getRoot();
+ for (Enumeration enumerator = root.depthFirstEnumeration(); enumerator.hasMoreElements();) {
+ DefaultMutableTreeNode node = (DefaultMutableTreeNode) enumerator.nextElement();
+ ImportFile f = (ImportFile) node.getUserObject();
+ f.setToBeImported(false);
+ }
+ nodesChanged(root);
+ }
+
+ public boolean isLeaf(TreeTableNode node) {
+ boolean ret = super.isLeaf(node);
+ logger.debug("isLeaf(" + node + ") -> " + ret);
+ return ret;
+ }
+
+ protected void nodesChanged(DefaultMutableTreeNode root) {
+ TreeModelEvent evt = new TreeModelEvent(this, new TreePath(root));
+ for(TreeModelListener l:getTreeModelListeners()) {
+ l.treeNodesChanged(evt);
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2010 axYus - http://www.axyus.com
+ * 2010 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS_NB.
+ *
+ * XEMELIOS_NB 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 2 of the License, or
+ * (at your option) any later version.
+ *
+ * XEMELIOS_NB 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 Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with XEMELIOS_NB; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.navigate;
+
+/**
+ * Définit une classe permettant de déterminer vers quoi on navigue.
+ * Les implémentations de cette interface doivent fournir un constructeur
+ * ayant pour paramètre ( {@link fr.gouv.finances.xemelios.common.config.DocumentModel},
+ * {@link fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser}, {@link fr.gouv.finances.cp.xemelios.ui.MainWindow})
+ * @author cmarchand
+ */
+public interface Navigable {
+ /**
+ * Affiche l'IHM permettant de sélectionner un élément vers lequel naviguer. C'est Ã
+ * l'implémentation de démarrer la navigation.
+ * @return <code>true</code> si l'utilisateur a choisit une destination, <code>false</code> sinon.
+ */
+ public boolean run();
+}
--- /dev/null
+/*
+ * Copyright
+ * 2011 axYus - http://www.axyus.com
+ * 2011 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS_NB.
+ *
+ * XEMELIOS_NB 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 2 of the License, or
+ * (at your option) any later version.
+ *
+ * XEMELIOS_NB 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 Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with XEMELIOS_NB; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.patches;
+
+import fr.gouv.finances.cp.xemelios.updater.AbstractConfigurator;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.util.Properties;
+
+/**
+ * Vérifie la présence de xemelios.date.format dans xemelios.properties
+ * et l'ajoute si manquant
+ * @author cmarchand
+ */
+public class DateFormatPatch extends AbstractConfigurator {
+
+ @Override
+ public void run() throws Exception {
+ if(mw.getEnvProperties().getProperty(Constants.SYS_PROP_DATE_FORMAT)==null) {
+ Properties localProperties = new Properties();
+ File xemeliosPropertiesFile = new File(new File(mw.getEnvProperties().getProperty("xemelios.root")),"xemelios.properties");
+ localProperties.load(new FileInputStream(xemeliosPropertiesFile));
+ localProperties.setProperty(Constants.SYS_PROP_DATE_FORMAT, "dd/MM/yyyy");
+ localProperties.store(new FileOutputStream(xemeliosPropertiesFile), null);
+ mw.getEnvProperties().setProperty(Constants.SYS_PROP_DATE_FORMAT, "dd/MM/yyyy");
+ }
+ }
+
+}
--- /dev/null
+Version 5
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui.resulttable;
+
+import java.text.DecimalFormat;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.TreeSet;
+import java.util.Vector;
+
+import javax.swing.table.AbstractTableModel;
+
+import org.apache.log4j.Logger;
+
+import fr.gouv.finances.dgfip.utils.Amount;
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.dgfip.xemelios.common.config.PjRefHandler;
+import fr.gouv.finances.dgfip.xemelios.common.config.ChampModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.HiddenModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ListeResultatModel;
+import fr.gouv.finances.dgfip.xemelios.data.DataResultSet;
+import fr.gouv.finances.dgfip.xemelios.data.DataHandler;
+
+/**
+ * Represente la tble de resultats de recherche
+ * @author chm
+ */
+public class EtatResultTableModel extends AbstractTableModel {
+
+ private static Logger logger = Logger.getLogger(EtatResultTableModel.class);
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 3546078073121223990L;
+ private ListeResultatModel lrm;
+ private ArrayList<DataHandler> data;
+ private DataResultSet rs;
+ private int orderByCol, sortOrder;
+ private Class[] datatypes = null;
+
+ public EtatResultTableModel(ListeResultatModel lrm, TreeSet<DataHandler> input, DataResultSet rs) {
+ super();
+ this.lrm = lrm;
+ this.data = new ArrayList<DataHandler>();
+ this.rs = rs;
+ for (DataHandler dh : input) {
+ for (int i = 0; i < lrm.getListeChamps().size(); i++) {
+ try {
+ dh.getValueAtColumn(i);
+ } catch (Throwable t) {
+ }
+ }
+ data.add(dh);
+ }
+ if (data.size() > 0) {
+ DataHandler dh = data.get(0);
+ this.orderByCol = dh.getOrderByColumn();
+ this.sortOrder = dh.getSortOrder();
+ } else {
+ this.orderByCol = 0;
+ this.sortOrder = DataHandler.ORDER_ASC;
+ }
+ // on precalcule tout
+ }
+
+ public EtatResultTableModel(ListeResultatModel lrm, Vector<DataHandler> input) {
+ super();
+ this.lrm = lrm;
+ this.data = new ArrayList<DataHandler>();
+ for (DataHandler dh : input) {
+ for (int i = 0; i < lrm.getListeChamps().size(); i++) {
+ try {
+ dh.getValueAtColumn(i);
+ } catch (Throwable t) {
+ }
+ }
+ data.add(dh);
+ }
+ if (data.size() > 0) {
+ DataHandler dh = data.get(0);
+ this.orderByCol = dh.getOrderByColumn();
+ this.sortOrder = dh.getSortOrder();
+ } else {
+ this.orderByCol = 0;
+ this.sortOrder = DataHandler.ORDER_ASC;
+ }
+ // on precalcule tout
+ }
+
+ @Override
+ public int getRowCount() {
+ if (data == null) {
+ return 0;
+ }
+ int ret = data.size();
+ return ret;
+ }
+
+ @Override
+ public int getColumnCount() {
+ return lrm.getListeChamps().size();
+ }
+
+ @Override
+ public String getColumnName(int col) {
+ ChampModel cm = lrm.getListeChamps().elementAt(col);
+ return cm.getLibelle();
+ }
+
+ @Override
+ public Class<?> getColumnClass(int col) {
+ if (datatypes == null) {
+ datatypes = new Class[getColumnCount()];
+ }
+ if (datatypes[col] == null) {
+ ChampModel cm = lrm.getListeChamps().elementAt(col);
+ datatypes[col] = cm.getDataClass();
+ }
+ return datatypes[col];
+ }
+
+ @Override
+ public boolean isCellEditable(int row, int column) {
+ return getColumnClass(column).equals(PjRefHandler.class);
+ }
+
+ @Override
+ public Object getValueAt(int row, int col) {
+// try {
+ Object o = getRowAt(row, col).getValueAtColumn(col);
+ return o;
+// } catch(ParseException t) {
+// ChampModel cm = lrm.getListeChamps().elementAt(col);
+// logger.warn("Type non attendu: "+data+" n'est pas du type "+cm.getDataClass().getName());
+// return null;
+// }
+ }
+
+ public Object getInnerValueAt(int row, int col) {
+ Object ret = getRowAt(row, col).getInnerDataAt(col);
+ return (ret == null ? "" : ret);
+ }
+
+ public DataHandler getRowAt(int row, int col) {
+ DataHandler dh = data.get(row);
+ return dh;
+ }
+
+ @Override
+ public void setValueAt(Object arg0, int arg1, int arg2) {
+ }
+// @Override
+// public void addTableModelListener(TableModelListener arg0) {
+// }
+// @Override
+// public void removeTableModelListener(TableModelListener arg0) {
+// }
+
+ public void setData(TreeSet<DataHandler> input) {
+ this.data = new ArrayList<DataHandler>();
+ for (DataHandler dh : input) {
+ for (int i = 0; i < lrm.getListeChamps().size(); i++) {
+ try {
+ dh.getValueAtColumn(i);
+ } catch (Throwable t) {
+ }
+ }
+ data.add(dh);
+ }
+ if (data.size() > 0) {
+ DataHandler dh = data.get(0);
+ this.orderByCol = dh.getOrderByColumn();
+ this.sortOrder = dh.getSortOrder();
+ } else {
+ this.orderByCol = 0;
+ this.sortOrder = DataHandler.ORDER_ASC;
+ }
+ }
+
+ public int sortRequired(int col) {
+ logger.debug("sort required: " + col);
+ if (data == null || data.size() == 0) {
+ return 0;
+ }
+ int locOrderByCol = 0;
+ int locSortOrder = 0;
+ DataHandler dh = data.get(0);
+ if (dh.getOrderByColumn() == col) {
+ if (dh.getSortOrder() == DataHandler.ORDER_ASC) {
+ locSortOrder = DataHandler.ORDER_DESC;
+ } else {
+ locSortOrder = DataHandler.ORDER_ASC;
+ }
+ locOrderByCol = col;
+ } else {
+ locOrderByCol = col;
+ locSortOrder = DataHandler.ORDER_ASC;
+ }
+ this.orderByCol = locOrderByCol;
+ this.sortOrder = locSortOrder;
+ TreeSet<DataHandler> ts = new TreeSet<DataHandler>();
+ for (DataHandler dh2 : data) {
+ dh2.setOrderByColumn(locOrderByCol, locSortOrder);
+ ts.add(dh2);
+ }
+ setData(ts);
+ fireTableStructureChanged();
+ return locSortOrder;
+ }
+
+ /**
+ * @return Returns the orderByCol.
+ */
+ public int getOrderByCol() {
+ return orderByCol;
+ }
+
+ /**
+ * @return Returns the sortOrder.
+ */
+ public int getSortOrder() {
+ return sortOrder;
+ }
+
+ public String getCsvBuffer(String fieldSeparator, boolean exportAll, int[] selectedRows) {
+ String lineSeparator = System.getProperty("line.separator");
+ DecimalFormat df = new DecimalFormat("#0.00");
+ SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
+ StringBuffer buff = new StringBuffer();
+ for (ChampModel cm : lrm.getListeChamps()) {
+ buff.append(cm.getLibelle()).append(fieldSeparator);
+ }
+ buff.append(lineSeparator);
+ for (int row = 0; row < getRowCount(); row++) {
+ if (exportAll || Arrays.binarySearch(selectedRows, row) >= 0) {
+ for (int col = 0; col < getColumnCount(); col++) {
+ Object value = getValueAt(row, col);
+ String strVal = null;
+ if (value instanceof Float) {
+ //double d = ((Float)value).doubleValue();
+ strVal = df.format((Float) value);
+ strVal = strVal.replaceAll("\\.", ",");
+ logger.debug("double: " + strVal);
+ } else if (value instanceof Amount) {
+ //double d = ((Amount)value).doubleValue();
+ strVal = df.format((Amount) value);
+ strVal = strVal.replaceAll("\\.", ",");
+ logger.debug("amount: " + strVal);
+ } else if (value instanceof Date) {
+ strVal = sdf.format((Date) value);
+ } else {
+ strVal = value == null ? "" : value.toString();
+ boolean shouldQuote = strVal.indexOf("\"") >= 0 || strVal.indexOf(fieldSeparator) >= 0 || strVal.startsWith(" ") || strVal.endsWith(" ");
+ strVal = strVal.replaceAll("\"", "\"\"");
+ if (shouldQuote) {
+ strVal = "\"".concat(strVal).concat("\"");
+ }
+ }
+ buff.append(strVal).append(fieldSeparator);
+ }
+ buff.append(lineSeparator);
+ }
+ }
+ return buff.toString();
+ }
+
+ public String getCsvBuffer(String fieldSeparator, String lineHeader) {
+ String lineSeparator = System.getProperty("line.separator");
+ DecimalFormat df = new DecimalFormat("#0.00");
+ SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
+ StringBuffer buff = new StringBuffer();
+ for (int row = 0; row < getRowCount(); row++) {
+ buff.append(lineHeader);
+ for (int col = 0; col < getColumnCount(); col++) {
+ Object value = getValueAt(row, col);
+ String strVal = null;
+ if (value instanceof Float) {
+ //double d = ((Float)value).doubleValue();
+ strVal = df.format((Float) value);
+ strVal = strVal.replaceAll("\\.", ",");
+ logger.debug("double: " + strVal);
+ } else if (value instanceof Amount) {
+ //double d = ((Amount)value).doubleValue();
+ strVal = df.format((Amount) value);
+ strVal = strVal.replaceAll("\\.", ",");
+ logger.debug("amount: " + strVal);
+ } else if (value instanceof Date) {
+ strVal = sdf.format((Date) value);
+ } else {
+ strVal = value == null ? "" : value.toString();
+ }
+ buff.append(strVal).append(fieldSeparator);
+ }
+ buff.append(lineSeparator);
+ }
+ return buff.toString();
+ }
+
+ public void dispose() {
+ lrm = null;
+ data.clear();
+ data = null;
+ if (datatypes != null) {
+ for (int i = 0; i < datatypes.length; i++) {
+ datatypes[i] = null;
+ }
+ }
+ }
+
+ public DataResultSet getResultSet() {
+ return rs;
+ }
+
+ /**
+ * Indicates whether a column allows the sum operations.
+ * A column permits these operations only if the data is of type {integer, date, decimal}
+ * and the optional attribute "somme-possible" is set to <b>true</b>.
+ * @param columnIndex the index (in the model) of the column
+ * @return <b>true</b> if this column allows sum operations, <b>false</b> otherwise
+ */
+ public boolean isSumOperationPermittedOnColumn(int columnIndex) {
+ boolean result = false;
+ Vector<ChampModel> listeChamps = lrm.getListeChamps();
+ if (columnIndex <= listeChamps.size()) {
+ ChampModel cm = listeChamps.get(columnIndex);
+ if ((cm.getDatatype().equals(ChampModel.DATATYPE_INTEGER) || cm.getDatatype().equals(ChampModel.DATATYPE_DECIMAL) || cm.getDatatype().equals(ChampModel.DATATYPE_AMOUNT)
+ || cm.getDatatype().equals(ChampModel.DATATYPE_DATE)) && cm.isSommePossible()) {
+ result = true;
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Returns the data type of a column, given the column index
+ * @param columnIndex The index of the column we want the data type of
+ * @return A data type, or an empty String if an error occured
+ */
+ public String getColumnDatatype(int columnIndex) {
+ String result = "";
+ Vector<ChampModel> listeChamps = lrm.getListeChamps();
+ if (columnIndex <= listeChamps.size()) {
+ ChampModel cm = listeChamps.get(columnIndex);
+ result = cm.getDatatype();
+ }
+
+ return result;
+ }
+
+ /**
+ * Returns the absolute XPath for the given column index
+ * @param columnIndex The index of the column we want the XPath of
+ * @return an absolute XPath String, or an empty String if an error occured
+ */
+ public String getColumnXPath(int columnIndex) {
+ String result = "";
+ Vector<ChampModel> listeChamps = lrm.getListeChamps();
+ if (columnIndex <= listeChamps.size()) {
+ ChampModel cm = listeChamps.get(columnIndex);
+ result = lrm.getParent().getPath().getFormattedPath() + "/" + cm.getPath().getFormattedPath();
+ }
+//logger.debug("getColumnXPath = "+result);
+ return result;
+ }
+
+ /**
+ * Returns the label for the header of a column, given its index
+ * @param columnIndex The index of the column
+ * @return the header of the column, an empty String if an error occured
+ */
+ public String getColumnHeader(int columnIndex) {
+ String result = "";
+ Vector<ChampModel> listeChamps = lrm.getListeChamps();
+ if (columnIndex <= listeChamps.size()) {
+ ChampModel cm = listeChamps.get(columnIndex);
+ result = cm.getLibelle();
+ }
+ return result;
+ }
+
+ public Vector<ChampModel> getListeChamps() {
+ return lrm.getListeChamps();
+ }
+
+ public Vector<HiddenModel> getHiddens() {
+ return lrm.getHiddens();
+ }
+
+ public ListeResultatModel getListeResultat() {
+ return lrm;
+ }
+
+ public Pair getCollectivite() {
+ return rs.getCollectivite();
+ }
+
+ public Pair getBudget() {
+ return rs.getBudget();
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui.resulttable;
+
+import java.awt.Cursor;
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.ItemEvent;
+import java.awt.event.ItemListener;
+
+import javax.swing.JButton;
+import javax.swing.JComboBox;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.SwingUtilities;
+
+import org.apache.log4j.Logger;
+
+import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
+import fr.gouv.finances.cp.utils.ui.IhmFactory;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ListeResultatModel;
+import fr.gouv.finances.dgfip.xemelios.data.DataAccessException;
+import fr.gouv.finances.dgfip.xemelios.data.DataConfigurationException;
+import fr.gouv.finances.dgfip.xemelios.data.DataResultSet;
+import fr.gouv.finances.cp.xemelios.ui.SearchWindow;
+import fr.gouv.finances.cp.xemelios.ui.search.PnlSearch;
+import fr.gouv.finances.cp.xemelios.ui.search.ResultDisplayerThread;
+import fr.gouv.finances.dgfip.xemelios.ui.ImageResources;
+
+/**
+ * A composant that allows user to change page
+ * @author chm
+ *
+ */
+public class PageSeeker extends JPanel {
+ private static Logger logger = Logger.getLogger(PageSeeker.class);
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 3256725086923863603L;
+ private JButton pbFirstPage = null, pbPreviousPage = null, pbNextPage = null, pbLastPage = null;
+ private JComboBox cbxPages = null;
+ private JLabel label = null;
+ private static Dimension buttonDim = new Dimension(20,20);
+ private int currentPage = 0, pageCount = 0;
+ private PnlSearch pnlSearch=null;
+
+ public PageSeeker(PnlSearch parent) {
+ super();
+ this.pnlSearch=parent;
+ initComponents();
+ }
+ protected void initComponents() {
+ IhmFactory iF = IhmFactory.newInstance();
+ FlowLayout fl = new FlowLayout(FlowLayout.LEFT);
+ fl.setHgap(0); fl.setVgap(0);
+ setLayout(fl);
+ pbFirstPage = new JButton(IhmFactory.getIconFromResource(ImageResources.PAGE_FIRST));
+ pbFirstPage.setPreferredSize(buttonDim);
+ pbFirstPage.setToolTipText("première page");
+ add(pbFirstPage);
+
+ pbPreviousPage = new JButton(IhmFactory.getIconFromResource(ImageResources.PAGE_PREVIOUS));
+ pbPreviousPage.setPreferredSize(buttonDim);
+ add(pbPreviousPage);
+ pbPreviousPage.setToolTipText("page précédente");
+
+ cbxPages = new JComboBox();
+ cbxPages.setEditable(false);
+ cbxPages.setPreferredSize(new Dimension(50,(int)buttonDim.getHeight()));
+ cbxPages.setPrototypeDisplayValue("0000");
+ cbxPages.addItem("");
+ add(cbxPages);
+
+ label = new JLabel("/ ");
+ add(label);
+
+ pbNextPage = new JButton(IhmFactory.getIconFromResource(ImageResources.PAGE_NEXT));
+ pbNextPage.setPreferredSize(buttonDim);
+ pbNextPage.setToolTipText("page suivante");
+ add(pbNextPage);
+
+ pbLastPage = new JButton(IhmFactory.getIconFromResource(ImageResources.PAGE_LAST));
+ pbLastPage.setPreferredSize(buttonDim);
+ pbLastPage.setToolTipText("dernière page");
+ add(pbLastPage);
+
+ reset();
+ }
+ public void updateData(DataResultSet rs) {
+ reset();
+ pageCount = rs.getEstimatedPageCount();
+ cbxPages.removeAllItems();
+ for(int i=1;i<=pageCount;i++) cbxPages.addItem(new Integer(i));
+ currentPage = rs.getCurrentPage();
+ cbxPages.setSelectedItem(new Integer(currentPage+1));
+ StringBuilder sb = new StringBuilder();
+ sb.append("/ ").append(pageCount);
+ while(sb.length()<6) sb.append(" ");
+ label.setText(sb.toString());
+ if(rs.hasPreviousPage()) {
+ pbPreviousPage.setEnabled(true);
+ pbPreviousPage.addActionListener(new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ pnlSearch.setCursor(new Cursor(Cursor.WAIT_CURSOR));
+ pnlSearch.setSearchEnabled(false);
+ MainWindow.getInstance().startWaiter();
+ EtatResultTableModel etrm = (EtatResultTableModel)pnlSearch.getTable().getModel();
+ DataResultSet rs = etrm.getResultSet();
+ OtherPageSeeker ops = new OtherPageSeeker(rs,rs.getListeResultatModel(),pnlSearch.getElementModel(),pnlSearch,OtherPageSeeker.PREVIOUS_PAGE);
+ if(SwingUtilities.isEventDispatchThread()) ops.run();
+ else SwingUtilities.invokeLater(ops);
+ }
+ });
+ pbFirstPage.setEnabled(true);
+ pbFirstPage.addActionListener(new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ pnlSearch.setCursor(new Cursor(Cursor.WAIT_CURSOR));
+ pnlSearch.setSearchEnabled(false);
+ MainWindow.getInstance().startWaiter();
+ EtatResultTableModel etrm = (EtatResultTableModel)pnlSearch.getTable().getModel();
+ DataResultSet rs = etrm.getResultSet();
+ OtherPageSeeker ops = new OtherPageSeeker(rs,rs.getListeResultatModel(),pnlSearch.getElementModel(),pnlSearch,OtherPageSeeker.FIRST_PAGE);
+ if(SwingUtilities.isEventDispatchThread()) ops.run();
+ else SwingUtilities.invokeLater(ops);
+ }
+ });
+ } else {
+ pbPreviousPage.setEnabled(false);
+ pbFirstPage.setEnabled(false);
+ }
+ if(rs.hasNextPage()) {
+ pbNextPage.setEnabled(true);
+ pbNextPage.addActionListener(new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ pnlSearch.setCursor(new Cursor(Cursor.WAIT_CURSOR));
+ pnlSearch.setSearchEnabled(false);
+ MainWindow.getInstance().startWaiter();
+ EtatResultTableModel etrm = (EtatResultTableModel)pnlSearch.getTable().getModel();
+ DataResultSet rs = etrm.getResultSet();
+ OtherPageSeeker ops = new OtherPageSeeker(rs,rs.getListeResultatModel(),pnlSearch.getElementModel(),pnlSearch,OtherPageSeeker.NEXT_PAGE);
+ if(SwingUtilities.isEventDispatchThread()) ops.run();
+ else SwingUtilities.invokeLater(ops);
+ }
+ });
+ pbLastPage.setEnabled(true);
+ pbLastPage.addActionListener(new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ pnlSearch.setCursor(new Cursor(Cursor.WAIT_CURSOR));
+ pnlSearch.setSearchEnabled(false);
+ MainWindow.getInstance().startWaiter();
+ EtatResultTableModel etrm = (EtatResultTableModel)pnlSearch.getTable().getModel();
+ DataResultSet rs = etrm.getResultSet();
+ OtherPageSeeker ops = new OtherPageSeeker(rs,rs.getListeResultatModel(),pnlSearch.getElementModel(),pnlSearch,OtherPageSeeker.LAST_PAGE);
+ if(SwingUtilities.isEventDispatchThread()) ops.run();
+ else SwingUtilities.invokeLater(ops);
+ }
+ });
+ } else {
+ pbNextPage.setEnabled(false);
+ pbLastPage.setEnabled(false);
+ }
+ if(pageCount>0) {
+ cbxPages.setEnabled(true);
+ cbxPages.addItemListener(new ItemListener() {
+ public void itemStateChanged(ItemEvent e) {
+ if(e.getStateChange()==ItemEvent.SELECTED) {
+ logger.debug("ITEM SELECTED");
+ Integer i = (Integer)e.getItem();
+ pnlSearch.setCursor(new Cursor(Cursor.WAIT_CURSOR));
+ pnlSearch.setSearchEnabled(false);
+ MainWindow.getInstance().startWaiter();
+ EtatResultTableModel etrm = (EtatResultTableModel)pnlSearch.getTable().getModel();
+ DataResultSet rs = etrm.getResultSet();
+ OtherPageSeeker ops = new OtherPageSeeker(rs,rs.getListeResultatModel(),pnlSearch.getElementModel(),pnlSearch,OtherPageSeeker.SET_PAGE,i.intValue()-1);
+ if(SwingUtilities.isEventDispatchThread()) ops.run();
+ else SwingUtilities.invokeLater(ops);
+ }
+ }
+ });
+ } else {
+ cbxPages.setEnabled(false);
+ }
+ }
+ public void reset() {
+ pbFirstPage.setEnabled(false);
+ pbPreviousPage.setEnabled(false);
+ pbLastPage.setEnabled(false);
+ pbNextPage.setEnabled(false);
+ cbxPages.setEnabled(false);
+ cbxPages.removeAllItems();
+ for(ActionListener al:pbFirstPage.getActionListeners()) pbFirstPage.removeActionListener(al);
+ for(ActionListener al:pbPreviousPage.getActionListeners()) pbPreviousPage.removeActionListener(al);
+ for(ActionListener al:pbNextPage.getActionListeners()) pbNextPage.removeActionListener(al);
+ for(ActionListener al:pbLastPage.getActionListeners()) pbLastPage.removeActionListener(al);
+ for(ItemListener il:cbxPages.getItemListeners()) cbxPages.removeItemListener(il);
+ }
+
+ private static class OtherPageSeeker implements Runnable {
+ public static final int FIRST_PAGE=-2;
+ public static final int PREVIOUS_PAGE=-1;
+ public static final int SET_PAGE=0;
+ public static final int NEXT_PAGE=1;
+ public static final int LAST_PAGE=2;
+ private DataResultSet rs = null;
+ private ListeResultatModel lrm = null;
+ private ElementModel em = null;;
+ private PnlSearch sw = null;
+ int way = 0;
+ int page = -1;
+ /**
+ *
+ * @param rs
+ * @param way if positive, indicates next page, if negative, indicates previous page
+ */
+ public OtherPageSeeker(DataResultSet rs, ListeResultatModel lrm, ElementModel em, PnlSearch sw, int way) {
+ super();
+ this.rs=rs;
+ this.lrm=lrm;
+ this.em=em;
+ this.sw=sw;
+ this.way=way;
+ }
+ public OtherPageSeeker(DataResultSet rs, ListeResultatModel lrm, ElementModel em, PnlSearch sw, int way, int page) {
+ super();
+ this.rs=rs;
+ this.lrm=lrm;
+ this.em=em;
+ this.sw=sw;
+ this.way=way;
+ this.page=page;
+ }
+ public void run() {
+ long start = System.currentTimeMillis();
+ sw.getPageSeeker().reset();
+ try {
+ switch(way) {
+ case FIRST_PAGE: rs.firstPage(); break;
+ case PREVIOUS_PAGE: rs.previousPage(); break;
+ case NEXT_PAGE: rs.nextPage(); break;
+ case LAST_PAGE: rs.lastPage(); break;
+ case SET_PAGE: rs.setPage(page);
+ }
+ ResultDisplayerThread rdt = new ResultDisplayerThread(rs,lrm,start,em,sw);
+ SwingUtilities.invokeLater(rdt);
+ } catch(DataAccessException daEx) {
+ new DisplayExceptionDlg(SwingUtilities.getWindowAncestor(sw),daEx);
+ } catch(DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(SwingUtilities.getWindowAncestor(sw),dcEx);
+ }
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ * 2008 JP.Tessier - jean-philippe.tessier@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.resulttable;
+
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import java.awt.Component;
+import java.awt.Point;
+import java.awt.Rectangle;
+import java.awt.Toolkit;
+import java.awt.datatransfer.Clipboard;
+import java.awt.datatransfer.StringSelection;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+
+import javax.swing.Box;
+import javax.swing.DefaultCellEditor;
+import javax.swing.Icon;
+import javax.swing.InputMap;
+import javax.swing.JButton;
+import javax.swing.JCheckBox;
+import javax.swing.JDialog;
+import javax.swing.JLabel;
+import javax.swing.JMenuItem;
+import javax.swing.JOptionPane;
+import javax.swing.JPopupMenu;
+import javax.swing.JTable;
+import javax.swing.KeyStroke;
+import javax.swing.SwingConstants;
+import javax.swing.table.DefaultTableCellRenderer;
+import javax.swing.table.TableCellRenderer;
+import javax.swing.table.TableModel;
+import javax.xml.XMLConstants;
+import javax.xml.namespace.NamespaceContext;
+
+import org.apache.log4j.Logger;
+import org.jdesktop.swingx.JXTable;
+
+import fr.gouv.finances.dgfip.utils.Amount;
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.cp.utils.StartUrl;
+import fr.gouv.finances.cp.utils.ui.IhmFactory;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import fr.gouv.finances.dgfip.xemelios.common.PJRef;
+import fr.gouv.finances.dgfip.xemelios.common.ToolException;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.PJRefInfo;
+import fr.gouv.finances.dgfip.xemelios.common.config.PjRefHandler;
+import fr.gouv.finances.dgfip.xemelios.common.config.PluginModel;
+import fr.gouv.finances.dgfip.xemelios.data.DataAccessException;
+import fr.gouv.finances.dgfip.xemelios.data.DataConfigurationException;
+import fr.gouv.finances.dgfip.xemelios.data.DataImpl;
+import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
+import fr.gouv.finances.cp.xemelios.ui.search.PnlSearch;
+import fr.gouv.finances.dgfip.xemelios.utils.XmlUtils;
+import fr.gouv.finances.dgfip.xemelios.auth.UnauthorizedException;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+import fr.gouv.finances.dgfip.xemelios.common.config.ChampModel;
+import fr.gouv.finances.dgfip.xemelios.ui.ImageResources;
+import fr.gouv.finances.dgfip.xemelios.utils.FileUtils;
+import java.awt.Color;
+import org.jdesktop.swingx.decorator.ColorHighlighter;
+import org.jdesktop.swingx.decorator.HighlightPredicate;
+
+/**
+ * La table de résultat de recherche
+ * @author cmarchand
+ */
+public class ResultTable extends JXTable {
+ private static final long serialVersionUID = 3311785168156347546L;
+
+ private static Icon iconPapier = IhmFactory.getIconFromResource(ImageResources.PJ_PAPER);
+ private static Icon iconDvd = IhmFactory.getIconFromResource(ImageResources.PJ_DVD);
+ private static Icon iconOnline = IhmFactory.getIconFromResource(ImageResources.PJ_ONLINE);
+ private static Icon iconAvailable = IhmFactory.getIconFromResource(ImageResources.PJ_AVAILABLE);
+ private static Icon iconUnavailable = IhmFactory.getIconFromResource(ImageResources.PJ_UNAVAILABLE);
+
+ private static Logger logger = Logger.getLogger(ResultTable.class);
+ @SuppressWarnings("unused")
+ private ElementModel em;
+ private PnlSearch searchWindow;
+ private DataImpl impl = null;
+ protected XemeliosUser user;
+ private PropertiesExpansion applicationProperties;
+
+ @SuppressWarnings("serial")
+ public ResultTable(TableModel model, final PnlSearch sw, final ElementModel em,final XemeliosUser user, PropertiesExpansion applicationProperties) {
+ super(model);
+ this.em = em;
+ this.searchWindow = sw;
+ this.user=user;
+ this.applicationProperties = applicationProperties;
+ AmountRenderer amrenderer = new AmountRenderer();
+ setDefaultRenderer(Amount.class,amrenderer);
+ DateRenderer drenderer = new DateRenderer();
+ setDefaultRenderer(Date.class,drenderer);
+ PjRenderer renderer = new PjRenderer();
+ setDefaultRenderer(PjRefHandler.class, renderer);
+ setDefaultEditor(PjRefHandler.class, new PjEditor(sw.getCurrentCollectivite(),sw.getCurrentBudget()));
+ setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
+ setColumnControlVisible(true);
+ setRolloverEnabled(true);
+ if(!"remove".equals(applicationProperties.getProperty("xemelios.jxtable.highlighter"))) {
+ Color selectedColor = new Color(0xB8, 0xCF, 0xE5);
+ ColorHighlighter whiteOne = new ColorHighlighter(HighlightPredicate.EVEN, Color.WHITE, Color.BLACK, selectedColor, Color.BLACK);
+ ColorHighlighter greyOne = new ColorHighlighter(HighlightPredicate.ODD, new Color(0xF0, 0xF0, 0xE0), Color.BLACK, new Color(0xBF, 0xCF, 0xE5), Color.BLACK);
+ setHighlighters(whiteOne,greyOne);
+ } InputMap im = getInputMap();
+ KeyStroke ks = KeyStroke.getKeyStroke("control P");
+ im.put(ks, "print");
+ // pour le menu contextuel
+ MouseListener popupListener = new PopupListener();
+ getTableHeader().addMouseListener(popupListener);
+
+ // double-click sur une ligne pour visualisation dans navigateur
+ addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(MouseEvent evt) {
+ Point p = evt.getPoint();
+ int row = sw.getTable().rowAtPoint(p);
+ if(row>=0 && evt.getClickCount()==2 && evt.getButton()==MouseEvent.BUTTON1) {
+ sw.actionOnRowPerformed(evt, row);
+ } else if(evt.getButton()==MouseEvent.BUTTON2 || evt.getButton()==MouseEvent.BUTTON3) {
+ sw.displayWidgetList(evt);
+ }
+ }
+ });
+ try {
+ impl = DataLayerManager.getImplementation();
+ } catch(Throwable t) {}
+ }
+
+ class PopupListener extends MouseAdapter implements ActionListener {
+ Pair[] operators;
+ HashMap<String, String> operatorList = new HashMap<String, String>();
+ int columnIndex=0;
+
+ @Override
+ public void mouseReleased(MouseEvent e) {
+ if(!e.isConsumed())
+ maybeShowPopup(e);
+ }
+ @Override
+ public void mousePressed(MouseEvent e) {
+ if(!e.isConsumed())
+ maybeShowPopup(e);
+ }
+
+ /**
+ * Décide s'il faut afficher le menu contextuel des opérations sur les colonnes
+ */
+ private void maybeShowPopup(MouseEvent e) {
+ Point p = e.getPoint();
+ JPopupMenu popup;
+
+ if(e.isPopupTrigger()) {
+ e.consume();
+ EtatResultTableModel etrm = (EtatResultTableModel)searchWindow.getTable().getModel();
+ /** il faut vérifier qu'il s'agit bien d'une colonne dont la donnée est de type
+ * integer, decimal ou date */
+ columnIndex = convertColumnIndexToModel(columnAtPoint(p));
+ boolean showPopup = etrm.isSumOperationPermittedOnColumn(columnIndex);
+// logger.debug("showPopup="+(showPopup?"true":"false"));
+ // maintenant on regarde si on est sur un plugin de recherche, et s'il autorise ces opérations (somme, moyenne, ...)
+ PluginModel pm = searchWindow.getPluginModel();
+ if(pm!=null) {
+ showPopup = showPopup && pm.isSumPossible();
+ }
+ try {
+ if(showPopup) {
+ DataImpl impl = DataLayerManager.getImplementation();
+ operators = impl.getAggregateOperators(etrm.getColumnDatatype(columnIndex));
+ if(operators.length>0) {
+ popup = new JPopupMenu();
+ JMenuItem menuItem;
+ for(Pair ope : operators) {
+ menuItem = new JMenuItem(ope.libelle);
+ menuItem.addActionListener(this);
+ popup.add(menuItem);
+ operatorList.put(ope.libelle, ope.key);
+ }
+ popup.show(e.getComponent(), e.getX(), e.getY());
+ }
+ }
+ } catch(DataConfigurationException dce) { dce.printStackTrace(); logger.debug("DataLayer not implemented"); }
+ }
+ }
+
+ /**
+ * Appelée quand un item de menu est sélectionné (dans le menu contextuel sur les colonnes)
+ * @param ae L'ActionEvent à l'origine de cet appel
+ */
+ @Override
+ public void actionPerformed(ActionEvent ae) {
+ JMenuItem item = (JMenuItem)ae.getSource();
+
+ try {
+ EtatResultTableModel etrm = (EtatResultTableModel)searchWindow.getTable().getModel();
+ DocumentModel dm = em.getParent().getParent();
+ String xpath = etrm.getColumnXPath(columnIndex);
+ xpath = XmlUtils.normalizeNS(xpath,dm.getNamespaces());
+ logger.debug(xpath);
+ final String resultat = DataLayerManager.getImplementation().calculateAggregate(searchWindow.getDocumentModel(),
+ em.getParent(),
+ xpath,
+ operatorList.get(item.getText()),
+ etrm.getListeChamps().get(columnIndex),
+ etrm.getResultSet(),user);
+
+ // now we display the result
+ final JDialog dialog = new JDialog();
+ dialog.setTitle(searchWindow.getTitle());
+ JLabel texte = new JLabel(item.getText()+" de "+etrm.getColumnHeader(columnIndex)+" : "+resultat);
+ JButton boutonFermer = new JButton("Fermer");
+ JButton boutonCopier = new JButton("Copier");
+ boutonCopier.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ Clipboard system = Toolkit.getDefaultToolkit().getSystemClipboard();
+ StringSelection ss = new StringSelection(resultat);
+ system.setContents(ss, ss);
+ }
+ });
+ boutonFermer.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ dialog.setVisible(false);
+ dialog.dispose();
+ }
+ });
+
+ Box haut = Box.createVerticalBox();
+ Box bas = Box.createHorizontalBox();
+ bas.add(boutonFermer);
+ bas.add(Box.createHorizontalStrut(20));
+ bas.add(boutonCopier);
+ texte.setAlignmentX(Component.CENTER_ALIGNMENT);
+ bas.setAlignmentX(Component.CENTER_ALIGNMENT);
+ haut.add(texte);
+ haut.add(Box.createVerticalStrut(20));
+ haut.add(bas);
+ dialog.add(haut);
+ //dialog.setSize(250,100);
+ dialog.pack();
+ dialog.setLocation(600,500);
+ dialog.setVisible(true);
+ } catch(UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(getParent(), ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch(DataConfigurationException dce) {
+ dce.printStackTrace();
+ } catch(DataAccessException dae) { }
+ }
+ }
+
+ @SuppressWarnings("serial")
+ class PjRenderer extends JButton implements TableCellRenderer {
+
+ public PjRenderer() {
+ setOpaque(true);
+ setText("...");
+ }
+
+ @Override
+ public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
+ setForeground(table.getSelectionForeground());
+ setBackground(table.getSelectionBackground());
+ if(value!=null && value instanceof PjRefHandler) {
+ PjRefHandler h =(PjRefHandler)value;
+ setToolTipText(Integer.toString(h.getPjCount())+" PJ");
+ } else {
+ setToolTipText(null);
+ }
+ return this;
+ }
+ }
+
+ @SuppressWarnings("serial")
+ class AmountRenderer extends DefaultTableCellRenderer {
+ public AmountRenderer() {
+ super();
+ }
+
+ @Override
+ public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
+ Component parent = super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
+ JLabel lbl = (JLabel)parent;
+ if(value!=null && value instanceof Amount) {
+ Amount am = (Amount)value;
+ lbl.setText(am.stringRepresentation());
+ lbl.setHorizontalAlignment(SwingConstants.RIGHT);
+ }
+ return parent;
+ }
+ }
+
+ class DateRenderer extends DefaultTableCellRenderer {
+ public DateRenderer() {
+ super();
+ }
+ @Override
+ public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
+ Component parent = super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
+ // on cherche le ChampModel associé
+ int modelColumn = convertColumnIndexToModel(column);
+ EtatResultTableModel etrm = (EtatResultTableModel)table.getModel();
+ ChampModel cm = etrm.getListeChamps().get(modelColumn);
+//logger.debug("column="+column+" modelColumn="+modelColumn+" id="+cm.getId());
+ JLabel lbl = (JLabel)parent;
+ if(value!=null && value instanceof Date) {
+ Date d = (Date)value;
+ String date_format = cm.getDateFormat();
+ if(date_format==null)
+ date_format = applicationProperties.getProperty(Constants.SYS_PROP_DATE_FORMAT);
+ if(date_format==null)
+ date_format = "yyyy-MM-dd";
+ SimpleDateFormat sdf = new SimpleDateFormat(date_format);
+ lbl.setText(sdf.format(d));
+ lbl.setHorizontalAlignment(SwingConstants.LEFT);
+ }
+ return parent;
+ }
+ }
+
+ @SuppressWarnings("serial")
+ class PjEditor extends DefaultCellEditor {
+ protected JButton button;
+ private Object data;
+ private boolean isPushed;
+ private Pair collectivite, budget;
+ private Point point;
+ private JTable table;
+
+ public PjEditor(final Pair collectivite, final Pair budget) {
+ super(new JCheckBox());
+ this.collectivite=collectivite;
+ this.budget=budget;
+ button = new JButton("...");
+ button.setOpaque(true);
+ button.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ fireEditingStopped();
+ }
+ });
+ }
+
+ @Override
+ public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
+ button.setForeground(table.getSelectionForeground());
+ button.setBackground(table.getSelectionBackground());
+ data=value;
+ Rectangle rect = table.getCellRect(row,column,false);
+ point = rect.getLocation();
+ this.table=table;
+ isPushed = true;
+ return button;
+ }
+
+ @Override
+ public Object getCellEditorValue() {
+ if (isPushed) {
+ JPopupMenu popup = new JPopupMenu("Pièces jointes");
+ if(data instanceof PjRefHandler) {
+ PjRefHandler pjs = (PjRefHandler)data;
+ int count = 0;
+ for(PJRefInfo pj:pjs.getPjs()) {
+ count++;
+ // modifs
+ Icon icon = null;
+ boolean available = false;
+ if(PJRefInfo.SUPPORT_PAPIER.equals(pj.getSupport())) icon = iconPapier;
+ else if(PJRefInfo.SUPPORT_ONLINE.equals(pj.getSupport())) icon = iconOnline;
+ else if(PJRefInfo.SUPPORT_LOCAL1.equals(pj.getSupport()) || PJRefInfo.SUPPORT_LOCAL2.equals(pj.getSupport()) || PJRefInfo.SUPPORT_CD_DVD.equals(pj.getSupport())) {
+ try {
+ available = impl.isPjAvailable(collectivite,pj.getNom(),user);
+ } catch(Throwable t) {}
+ if(available) {
+ icon = iconAvailable;
+ } else {
+ icon = iconUnavailable;
+ }
+ }
+ JMenuItem mnu=new JMenuItem(pj.getNom(),icon);
+ if(available) {
+ mnu.addActionListener(new PjDisplayAction(collectivite,budget,pj));
+ }
+ // fin modifs
+ popup.add(mnu);
+ }
+ } else {
+ logger.debug(data.getClass().getName()+" --> "+data.toString());
+ }
+ popup.show(table,point.x,point.y);
+ }
+ isPushed = false;
+ return "...";
+ }
+
+ @Override
+ public boolean stopCellEditing() {
+ isPushed = false;
+ return super.stopCellEditing();
+ }
+
+ @Override
+ protected void fireEditingStopped() {
+ super.fireEditingStopped();
+ }
+
+ }
+ private class PjDisplayAction implements ActionListener {
+ private Pair collectivite, budget;
+ private PJRefInfo pj;
+ public PjDisplayAction(Pair collectivite, Pair budget, PJRefInfo pj) {
+ super();
+ this.collectivite=collectivite;
+ this.budget=budget;
+ this.pj=pj;
+ }
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ try {
+ DataImpl impl = DataLayerManager.getImplementation();
+ PJRef pjRef = impl.getPj(collectivite,pj.getNom(),user);
+ if(pjRef!=null) {
+ File tmpFile = File.createTempFile("tmp-",pjRef.getFileName(),FileUtils.getTempDir());
+ FileOutputStream fos = new FileOutputStream(tmpFile);
+ fos.write(pjRef.getData());
+ fos.flush();
+ fos.close();
+ StartUrl.startUrl(tmpFile.toURI().toURL().toExternalForm());
+ } else {
+ JOptionPane.showMessageDialog(null,"Pièce non trouvée.");
+ }
+ } catch(UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(getParent(), ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (DataConfigurationException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch(DataAccessException daEx) {
+ // TODO
+ daEx.printStackTrace();
+ } catch(IOException ioEx) {
+ // TODO
+ ioEx.printStackTrace();
+ } catch(ToolException tEx) {
+ // TODO
+ tEx.printStackTrace();
+ }
+ }
+ }
+// private class WidgetAction extends AbstractAction {
+// private AbstractWidget aw;
+// private EtatResultTableModel etrm;
+// private int row;
+// public WidgetAction(AbstractWidget aw,EtatResultTableModel etrm,int row) {
+// super(aw.getWidgetModel().getLibelle());
+// this.aw=aw;
+// this.etrm=etrm;
+// this.row=row;
+// }
+// public void actionPerformed(ActionEvent evt) {
+// aw.run(etrm,row);
+// }
+// }
+ private static class LocalNSCtx implements NamespaceContext {
+ private static String URI;
+
+ public LocalNSCtx(String uri){
+ URI=uri;
+ }
+
+ @Override
+ public String getNamespaceURI(String prefix) {
+ if("".equals(prefix)) return XMLConstants.NULL_NS_URI;
+ else if("n".equals(prefix)) return URI;
+ else if(XMLConstants.XML_NS_PREFIX.equals(prefix)) return XMLConstants.XML_NS_URI;
+ else if(XMLConstants.XMLNS_ATTRIBUTE.equals(prefix)) return XMLConstants.XMLNS_ATTRIBUTE_NS_URI;
+ else return XMLConstants.NULL_NS_URI;
+ }
+
+ @Override
+ public String getPrefix(String namespaceURI) {
+ if(URI.equals(namespaceURI)) return "n";
+ else if(XMLConstants.XML_NS_URI.equals(namespaceURI)) return XMLConstants.XML_NS_PREFIX;
+ else if(XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespaceURI)) return XMLConstants.XMLNS_ATTRIBUTE;
+ else return XMLConstants.DEFAULT_NS_PREFIX;
+ }
+
+ @Override
+ public Iterator getPrefixes(String namespaceURI) {
+ return new StringIterator(getPrefix(namespaceURI));
+ }
+ }
+ private static class StringIterator<String> implements Iterator<String> {
+ private String s;
+ private boolean get = false;
+ public StringIterator(String s) {
+ super();
+ this.s=s;
+ }
+
+ @Override
+ public boolean hasNext() {
+ return !get;
+ }
+
+ @Override
+ public String next() {
+ get = true;
+ return s;
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2010 axYus - http://www.axyus.com
+ * 2010 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.search;
+
+import fr.gouv.finances.cp.xemelios.ui.CriteriaViewer;
+import fr.gouv.finances.cp.xemelios.ui.CriteriaViewer.InputData;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.cp.xemelios.ui.resulttable.EtatResultTableModel;
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.dgfip.xemelios.common.ToolException;
+import fr.gouv.finances.dgfip.xemelios.common.config.SourceTargetModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.CritereModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.EtatModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.HiddenModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.Loader;
+import fr.gouv.finances.dgfip.xemelios.common.config.RequiredCritereModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.SearchHelperModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.SearchHelperParameterModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ValueModel;
+import fr.gouv.finances.dgfip.xemelios.data.DataConfigurationException;
+import fr.gouv.finances.dgfip.xemelios.data.DataHandler;
+import fr.gouv.finances.dgfip.xemelios.swing.InfiniteGlassPane;
+import java.awt.Rectangle;
+import java.awt.Window;
+import java.awt.event.MouseEvent;
+import java.io.IOException;
+import javax.swing.JDialog;
+import javax.xml.parsers.ParserConfigurationException;
+import org.apache.log4j.Logger;
+import org.jdesktop.swingx.JXTable;
+import org.xml.sax.SAXException;
+
+/**
+ *
+ * @author cmarchand
+ */
+public class DlgSearchHelper extends JDialog {
+ private static final Logger logger = Logger.getLogger(DlgSearchHelper.class);
+
+ private SearchHelperModel shm;
+ private SearchContext sCtx;
+
+ private PnlSearch pnl;
+ private Object returnValue;
+ private InputData inputField;
+ private DocumentModel documentModel;
+ private EtatModel etatModel;
+ private ElementModel elementModel;
+
+ public DlgSearchHelper(Window parent, InputData inputField, SearchHelperModel shm, SearchContext sCtx) {
+ super(parent, ModalityType.APPLICATION_MODAL);
+ this.shm=shm;
+ this.inputField = inputField;
+ this.sCtx = sCtx;
+ try {
+ documentModel = Loader.getDocumentsInfos(null).getDocumentById(shm.getDocumentId());
+ etatModel = documentModel.getEtatById(shm.getEtatId());
+ elementModel = etatModel.getElementById(shm.getElementId());
+
+ PnlSearch.DisplayParameters dp = new PnlSearch.DisplayParameters();
+ dp.setSearchBackgroundVisible(false);
+ dp.setExportPluginsIncluded(false);
+ dp.setSaveRequestVisible(false);
+ dp.setShowRepositoryVisible(false);
+ dp.setWidgetsVisible(false);
+ dp.setSummableVisible(false);
+ if(shm.getCollectivite()!=null) dp.setCollectiviteEditable(shm.getCollectivite().isEditable());
+ if(shm.getBudget()!=null) dp.setBudgetEditable(shm.getBudget().isEditable());
+
+ pnl = new PnlSearch(documentModel, etatModel, elementModel, dp, sCtx.getUser(), MainWindow.getInstance().getEnvProperties()) {
+ @Override
+ public void resizeParent(Rectangle bounds) {
+ // pour le moment, on ne fait rien, Ã voir si il faut
+ }
+ @Override
+ public String getTitle() {
+ return "";
+ }
+ @Override
+ public void notifyParentStateChanged() {
+ // on ne fait rien ici
+ }
+ @Override
+ public void iconify(boolean iconified) {
+ // on ne fait rien
+ }
+ @Override
+ public void setTitle(String newTitle) {
+ // rien
+ }
+ @Override
+ public void redisplayTitle() {
+ // on ne fait rien
+ }
+ @Override
+ public void startWaiter() {
+ getGlassPane().setVisible(true);
+ }
+ @Override
+ public void stopWaiter() {
+ getGlassPane().setVisible(false);
+ }
+ @Override
+ public boolean canExport() {
+ return false;
+ }
+
+ @Override
+ public void actionOnRowPerformed(MouseEvent evt, int row) {
+ String columnId = DlgSearchHelper.this.shm.getReturnValueColumnId();
+ row=((JXTable)getTable()).convertRowIndexToModel(row);
+ EtatResultTableModel etrm = (EtatResultTableModel)getTable().getModel();
+ DataHandler dh = etrm.getRowAt(row,0);
+ for(int pos=0;pos<etrm.getHiddens().size();pos++) {
+ HiddenModel hm = etrm.getHiddens().get(pos);
+ if(hm.getName().equals(columnId)) {
+ Object paramValue = dh.getValueAtColumn(etrm.getListeChamps().size()+pos);
+ if(paramValue!=null)
+ DlgSearchHelper.this.returnValue = paramValue;
+ }
+ }
+ if(DlgSearchHelper.this.returnValue!=null) {
+ setReturnedValue();
+ } else {
+ logger.error("",new DataConfigurationException(getDocumentModel().getId()+"."+getElementModel().getParent().getId()+"."+getElementModel().getId()+"."+columnId+" is not a hidden !"));
+ }
+ }
+
+ };
+ } catch(SAXException saxEx) {
+ // ça peut même pas arriver ici
+ } catch(ParserConfigurationException pcEx) {
+ // encore moins !
+ } catch(IOException ioEx) {
+ // ça, pourquoi pas !
+ logger.error("<init>",ioEx);
+ } catch(ToolException tEx) {
+ // ça, c'est probable
+ logger.error("<init>",tEx);
+ }
+ setGlassPane(new InfiniteGlassPane());
+ if(shm.getCollectivite()!=null) {
+ Pair collectivite = null;
+ String value = shm.getCollectivite().getValue();
+ if(SearchHelperParameterModel.CURRENT_COLLECTIVITE.equals(value))
+ collectivite = sCtx.getCollectivite();
+ else
+ collectivite = new Pair(value,value);
+ pnl.setCollectivite(collectivite);
+ }
+ if(shm.getBudget()!=null) {
+ Pair budget = null;
+ String value = shm.getBudget().getValue();
+ if(SearchHelperParameterModel.CURRENT_BUDGET.equals(value))
+ budget = sCtx.getBudget();
+ else
+ budget = new Pair(value,value);
+ pnl.setBudget(budget);
+ }
+
+ if(sCtx.getCriteres().size()>0) pnl.clearAll();
+ for(RequiredCritereModel rcm: shm.getRequiredCriteres()) {
+ // TODO
+ CriteriaViewer cv = pnl.addLineNoCriteria();
+ CritereModel cm = elementModel.getCritere(rcm.getRefId());
+ cv.changeCritereModel(cm);
+ for(ValueModel vm:rcm.getValues().values())
+ cv.setInputValue(vm.getKey(), vm.getValue());
+ }
+ for(CritereModel cm:sCtx.getCriteres()) {
+ String critereToAddId = cm.getId();
+ boolean skipThisCriteria = false;
+ for(SourceTargetModel stm: shm.getExcludedCriteres()) {
+ if(critereToAddId.equals(stm.getSource())) {
+ skipThisCriteria = true;
+ break;
+ }
+ }
+ SourceTargetModel cmm = shm.getCritereMappingBySource(critereToAddId);
+ if(cmm!=null) {
+ // on vérifie que le critère existe dans cet élément
+ critereToAddId = cmm.getTarget();
+ }
+ for(SourceTargetModel stm: shm.getExcludedCriteres()) {
+ if(critereToAddId.equals(stm.getTarget())) {
+ skipThisCriteria = true;
+ break;
+ }
+ }
+ if(!skipThisCriteria) {
+ CritereModel localCm = pnl.getElementModel().getCritere(critereToAddId);
+ if(localCm!=null) {
+ localCm.setValeurs(cm.getValeurs());
+ CriteriaViewer cv = pnl.addLine();
+ cv.changeCritereModel(localCm);
+ }
+ }
+ }
+ getContentPane().add(pnl);
+ pack();
+ setLocationRelativeTo(parent);
+ }
+
+ private void setReturnedValue() {
+ inputField.setInputValue(returnValue.toString());
+ setVisible(false);
+ }
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2010 axYus - http://www.axyus.com
+ * 2010 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+package fr.gouv.finances.cp.xemelios.ui.search;
+
+import com.jgoodies.forms.builder.PanelBuilder;
+import com.jgoodies.forms.layout.CellConstraints;
+import com.jgoodies.forms.layout.FormLayout;
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
+import fr.gouv.finances.cp.utils.ui.IhmFactory;
+import fr.gouv.finances.cp.utils.ui.VerticalFlowLayout;
+import fr.gouv.finances.cp.xemelios.ui.CriteriaViewer;
+import fr.gouv.finances.cp.xemelios.ui.DlgEditEnvironment;
+import fr.gouv.finances.cp.xemelios.ui.DlgSelectRequest;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.cp.xemelios.ui.collectivites.DlgSelectCollectivite;
+import fr.gouv.finances.cp.xemelios.ui.export.DlgSearchConfig;
+import fr.gouv.finances.cp.xemelios.ui.resulttable.EtatResultTableModel;
+import fr.gouv.finances.cp.xemelios.ui.resulttable.PageSeeker;
+import fr.gouv.finances.cp.xemelios.ui.searchParams.DlgSearchParams;
+import fr.gouv.finances.cp.xemelios.widgets.AbstractWidget;
+import fr.gouv.finances.dgfip.utils.IoUtils;
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
+import fr.gouv.finances.dgfip.utils.xml.transform.CustomURIResolver;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import fr.gouv.finances.dgfip.xemelios.common.ToolException;
+import fr.gouv.finances.dgfip.xemelios.common.config.CritereModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.CritereRefModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentsModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.EnvironmentDomain;
+import fr.gouv.finances.dgfip.xemelios.common.config.EtatModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.PluginModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.RechercheModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.SavedRequestsModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.WidgetModel;
+import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
+import fr.gouv.finances.dgfip.xemelios.ui.ImageResources;
+import fr.gouv.finances.dgfip.xemelios.ui.ListDisplayable;
+import java.awt.BorderLayout;
+import java.awt.Component;
+import java.awt.Cursor;
+import java.awt.Frame;
+import java.awt.Point;
+import java.awt.Rectangle;
+import java.awt.Window;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.MouseEvent;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.reflect.Constructor;
+import java.util.HashMap;
+import java.util.TreeSet;
+import java.util.Vector;
+import javax.swing.AbstractAction;
+import javax.swing.BorderFactory;
+import javax.swing.ButtonGroup;
+import javax.swing.JButton;
+import javax.swing.JComboBox;
+import javax.swing.JDialog;
+import javax.swing.JFileChooser;
+import javax.swing.JFrame;
+import javax.swing.JMenuItem;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JPopupMenu;
+import javax.swing.JRadioButton;
+import javax.swing.JScrollPane;
+import javax.swing.JSplitPane;
+import javax.swing.JTable;
+import javax.swing.JTextField;
+import javax.swing.JToolBar;
+import javax.swing.ScrollPaneConstants;
+import javax.swing.SwingUtilities;
+import javax.swing.filechooser.FileFilter;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathConstants;
+import javax.xml.xpath.XPathFactory;
+import org.apache.log4j.Logger;
+import org.jdesktop.swingx.JXTable;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.xml.sax.SAXException;
+
+/**
+ *
+ * @author cmarchand
+ */
+public abstract class PnlSearch extends JPanel {
+
+ private static final Logger logger = Logger.getLogger(PnlSearch.class);
+ // qui suis-je
+ private XemeliosUser user;
+ // sur quoi travaille-t-on
+ private DocumentModel documentModel;
+ private EtatModel etatModel;
+ private ElementModel elementModel;
+ private Pair currentCollectivite, currentBudget;
+ // IHM
+ private JButton pbSearch, pbValidateHeader, pbSearchBackground;
+ private JButton pbClear, pbSaveRequest, pbExport;
+ private JComboBox colls, budgets;
+ private final JTextField dfCollectivite = new JTextField();
+ private Vector<CriteriaViewer> criterias;
+ private JPanel scroller;
+ private JScrollPane sc;
+ private JSplitPane splitter = null;
+ private JTextField bottomField;
+ private PageSeeker ps = null;
+ private JTable table = null;
+ private AbstractAction actSearch = null;
+ // controles de l'IHM
+ private boolean pluginSearchEnabled = false;
+ protected boolean canExport = false;
+ private PluginModel plugin;
+ private DisplayParameters dp;
+// private String originalTitle;
+ private MODE_COLLECTIVITES modeCollectivite = MODE_COLLECTIVITES.MODE_FIELD;
+ // les critères optionnels pour les plugins
+ private Vector<CritereModel> criteresOp;
+
+ private enum MODE_COLLECTIVITES { MODE_FIELD, MODE_LIST};
+ private PropertiesExpansion applicationProperties;
+
+ public PnlSearch(DocumentModel documentModel, EtatModel etatModel, ElementModel elementModel, DisplayParameters dp, XemeliosUser user, PropertiesExpansion applicationProperties) throws ToolException {
+ super();
+ this.documentModel = documentModel;
+ this.etatModel = etatModel;
+ this.elementModel = elementModel;
+ this.dp=dp;
+ this.user = user;
+ this.applicationProperties = applicationProperties;
+ initComponents();
+ }
+
+ /**
+ * Permet d'activer ou de désactiver la possibilité de recherche
+ * @param enableIt
+ */
+ public void setSearchEnabled(boolean enableIt) {
+ pbSearch.setEnabled(enableIt);
+ pbSearchBackground.setEnabled(enableIt);
+ }
+
+ /**
+ * Permet de libérer la mémoire avant fermeture. Attention, ne pas appeler n'importe comment !
+ */
+ public void clearResources() {
+ elementModel = null;
+ etatModel = null;
+ documentModel = null;
+ if(table!=null) {
+ JXTable latable = (JXTable)table;
+ EtatResultTableModel etrm = (EtatResultTableModel)latable.getModel();
+ etrm.getResultSet().clear();
+ etrm.dispose();
+ }
+ }
+ /**
+ * Supprime tous les critères saisis, et réinitialise la fenêtre de recherche
+ */
+ public void clearAll() {
+ plugin = null;
+ pbValidateHeader.setEnabled(true);
+ if (criterias == null) {
+ return;
+ }
+ while (criterias.size() > 0) {
+ removeLine(criterias.elementAt(criterias.size() - 1));
+ }
+ }
+
+ public void removeLine(CriteriaViewer whichOne) {
+ scroller.remove(whichOne);
+ criterias.remove(whichOne);
+ if (criterias.size() == 0) {
+ setSearchEnabled(false);
+ }
+ repaintCriterias();
+ }
+
+ public void repaintCriterias() {
+ if (!isVisible()) {
+ return;
+ }
+ scroller.getSize();
+ sc.setViewportView(scroller);
+ resizeParent(getBounds());
+// getDesktopPane().getDesktopManager().beginResizingFrame(this,0);
+// Rectangle r = getBounds();
+// getDesktopPane().getDesktopManager().resizeFrame(this,r.x,r.y,r.width,r.height);
+// getDesktopPane().getDesktopManager().endResizingFrame(this);
+ }
+
+ /**
+ * Fait semblant de redimmensionner le parent pour provoquer le réaffichage
+ * @param bounds
+ */
+ public abstract void resizeParent(Rectangle bounds);
+
+ /**
+ * Ajoute une nouvelle ligne de critère, mais sans critère
+ * @return
+ */
+ protected CriteriaViewer addLineNoCriteria() {
+ CriteriaViewer cv = new CriteriaViewer(this, elementModel, currentCollectivite, currentBudget, true, true);
+ CriteriaViewer lastCrit = (criterias.size() > 0 ? criterias.get(criterias.size() - 1) : cv);
+ criterias.add(cv);
+ if (pbClear != null) {
+ pbClear.setEnabled(true);
+ setSearchEnabled(true);
+ }
+ if (scroller != null) {
+ scroller.add(cv);
+ }
+ if (isVisible()) {
+ cv.setVisible(true);
+ scroller.validate();
+ Rectangle rect = lastCrit.getBounds();
+ Point p = new Point(0, (int) ((criterias.size()) * rect.getHeight()) - 1);
+ sc.getViewport().setViewPosition(p);
+ repaintCriterias();
+ }
+ return cv;
+ }
+
+ /**
+ * Ajoute un nouveau critère
+ * @return
+ */
+ public CriteriaViewer addLine() {
+ CriteriaViewer cv = null;
+ if (pluginSearchEnabled) {
+ cv = new CriteriaViewer(this, elementModel, currentCollectivite, currentBudget, (criterias.size() == 0), criteresOp);
+ } else {
+ cv = new CriteriaViewer(this, elementModel, currentCollectivite, currentBudget, (criterias.size() == 0));
+ }
+ criterias.add(cv);
+ if (pbClear != null) {
+ pbClear.setEnabled(true);
+ setSearchEnabled(true);
+ }
+ if (scroller != null) {
+ scroller.add(cv);
+ }
+ if (isVisible()) {
+ cv.setVisible(true);
+ scroller.validate();
+ Rectangle rect = cv.getBounds();
+ Point p = new Point(0, (int) ((criterias.size()) * rect.getHeight()) - 1);
+ sc.getViewport().setViewPosition(p);
+ repaintCriterias();
+ }
+ return cv;
+ }
+
+ /**
+ * Construit le panel
+ * @throws ToolException
+ */
+ protected void initComponents() throws ToolException {
+ setLayout(new BorderLayout());
+ IhmFactory iF = IhmFactory.newInstance();
+
+ pbValidateHeader = new JButton(IhmFactory.getIconFromResource(ImageResources.ADD));
+ pbValidateHeader.setToolTipText("Ajouter un critère de recherche");
+ pbValidateHeader.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ addLine();
+ }
+ });
+ pbSearch = new JButton(IhmFactory.getIconFromResource(ImageResources.SEARCH)) {
+ private static final long serialVersionUID = 1L;
+ @Override
+ public void fireActionPerformed(ActionEvent event) {
+ startWaiter();
+ super.fireActionPerformed(event);
+ }
+ };
+ pbSearch.setToolTipText("Chercher");
+ pbSearch.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ search();
+ }
+ });
+ pbSearch.setEnabled(false);
+ budgets = new JComboBox();
+
+ int collCount = 0;
+ try {
+ collCount = DataLayerManager.getImplementation().getCollectivitesCount(documentModel, user);
+ } catch (Exception ex) {
+ logger.error("while getting collectivites count:", ex);
+ }
+
+
+ if (documentModel.getCollectivitePath().getParentsCount() == 0 || collCount < Constants.MAX_DISPLAYED_COLLECTIVITES) { // Constants.MAX_DISPLAYED_COLLECTIVITES
+ modeCollectivite = MODE_COLLECTIVITES.MODE_LIST;
+ try {
+ Vector<Pair> collectivites = DataLayerManager.getImplementation().getCollectivites(documentModel, null, user);
+ colls = new JComboBox(collectivites);
+ colls.setSelectedIndex(0);
+ colls.addActionListener(new ActionListener() {
+
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ Pair bd = (Pair) colls.getSelectedItem();
+ currentCollectivite = bd;
+ Vector<Pair> data = new Vector<Pair>();
+ try {
+ data = DataLayerManager.getImplementation().getBudgets(documentModel, currentCollectivite, user);
+ } catch (Exception ex) {
+ Window ancestor = SwingUtilities.getWindowAncestor(PnlSearch.this);
+ if (ancestor instanceof JDialog) {
+ new DisplayExceptionDlg((JDialog) ancestor, ex);
+ } else {
+ new DisplayExceptionDlg((JFrame) ancestor, ex);
+ }
+ }
+ budgets.removeAllItems();
+ for (Pair c : data) {
+ budgets.addItem(c);
+ }
+ if (data.size() > 0) {
+ budgets.setSelectedIndex(0);
+ }
+ clearAll();
+ pluginSearchEnabled = false;
+ addLine();
+ pbSaveRequest.setEnabled(true);
+ }
+ });
+ currentCollectivite = (Pair) colls.getItemAt(0);
+ } catch (Exception ex) {
+ Window ancestor = SwingUtilities.getWindowAncestor(PnlSearch.this);
+ if (ancestor instanceof JDialog) {
+ new DisplayExceptionDlg((JDialog) ancestor, ex);
+ } else {
+ new DisplayExceptionDlg((JFrame) ancestor, ex);
+ }
+ throw new ToolException(ToolException.ERROR_NO_DATA);
+ }
+ colls.setEnabled(dp.isCollectiviteEditable());
+ } else {
+ modeCollectivite = MODE_COLLECTIVITES.MODE_FIELD;
+ // more than Constants.MAX_DISPLAYED_COLLECTIVITES collectivites
+ dfCollectivite.setColumns(15);
+ dfCollectivite.setEditable(false);
+ pbValidateHeader.setEnabled(false);
+ }
+ criterias = new Vector<CriteriaViewer>();
+ pbSaveRequest = new JButton(IhmFactory.getIconFromResource(ImageResources.SAVE));
+ pbSaveRequest.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ saveRequest();
+ }
+ });
+ pbSaveRequest.setToolTipText("Enregistrer les critères de recherche");
+ JButton pbOpenRequest = new JButton(IhmFactory.getIconFromResource(ImageResources.OPEN_REQUEST));
+ pbOpenRequest.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ openRequest();
+ }
+ });
+ pbOpenRequest.setToolTipText("Ouvrir une recherche pré-enregistrée");
+ pbSearchBackground = new JButton(IhmFactory.getIconFromResource(ImageResources.SEARCH_BG));
+ pbSearchBackground.setToolTipText("Rechercher en tâche de fond");
+ pbSearchBackground.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ searchBackground();
+ }
+ });
+ pbSearchBackground.setEnabled(false);
+
+ JToolBar tb = new JToolBar();
+ tb.setRollover(true);
+ tb.setFloatable(false);
+ tb.add(iF.newLabel(documentModel.getLibelleCollectivite(), "normal"));
+ if (modeCollectivite==MODE_COLLECTIVITES.MODE_LIST) {
+ tb.add(colls);
+ } else {
+ tb.add(dfCollectivite);
+ JButton pbChooseCollectivite = new JButton("...");
+ pbChooseCollectivite.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ DlgSelectCollectivite dlg = new DlgSelectCollectivite(documentModel, user, (JFrame) SwingUtilities.getWindowAncestor(PnlSearch.this));
+ if (dlg.run()) {
+ currentCollectivite = dlg.getCollectivite();
+ dfCollectivite.setText(currentCollectivite.libelle);
+ Vector<Pair> data = new Vector<Pair>();
+ try {
+ data = DataLayerManager.getImplementation().getBudgets(documentModel, currentCollectivite, user);
+ } catch (Exception ex) {
+ Window ancestor = SwingUtilities.getWindowAncestor(PnlSearch.this);
+ if (ancestor instanceof JDialog) {
+ new DisplayExceptionDlg((JDialog) ancestor, ex);
+ } else {
+ new DisplayExceptionDlg((JFrame) ancestor, ex);
+ }
+ }
+ budgets.removeAllItems();
+ for (Pair c : data) {
+ budgets.addItem(c);
+ }
+ if (data.size() > 0) {
+ budgets.setSelectedIndex(0);
+ }
+ clearAll();
+ pluginSearchEnabled = false;
+ addLine();
+ pbSaveRequest.setEnabled(true);
+ pbValidateHeader.setEnabled(true);
+ }
+ }
+ });
+ tb.add(pbChooseCollectivite);
+ pbChooseCollectivite.setEnabled(dp.isCollectiviteEditable());
+ }
+ tb.addSeparator();
+ tb.add(iF.newLabel("Code Budget ", "normal"));
+ tb.add(budgets);
+ budgets.setEnabled(dp.isBudgetEditable());
+ add(tb, BorderLayout.PAGE_START);
+
+ tb = new JToolBar(JToolBar.VERTICAL);
+ tb.setRollover(true);
+// tb.addSeparator();
+ if(dp.isAddCriteriaVisible())
+ tb.add(pbValidateHeader);
+ tb.add(pbSearch);
+ if(dp.isSearchBackgroundVisible())
+ tb.add(pbSearchBackground);
+ pbClear = new JButton(IhmFactory.getIconFromResource(ImageResources.CLEAR_ALL));
+ if(dp.isClearAllVisible())
+ tb.add(pbClear);
+ if (documentModel.getReferentielXsltFile() != null && dp.isShowRepositoryVisible()) {
+ JButton pbShowReferentiel;
+ tb.addSeparator();
+ tb.add(pbShowReferentiel = new JButton(IhmFactory.getIconFromResource(ImageResources.REFERENTIEL)));
+ pbShowReferentiel.setToolTipText("Afficher la nomenclature");
+ pbShowReferentiel.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ showReferentiel();
+ }
+ });
+ }
+ tb.addSeparator();
+ if(dp.isSaveRequestVisible())
+ tb.add(pbSaveRequest);
+ if(dp.isOpenRequestVisible())
+ tb.add(pbOpenRequest);
+ tb.addSeparator();
+
+ JButton pbEnvironment = new JButton(IhmFactory.getIconFromResource(ImageResources.ENVIRONMENT));
+ pbEnvironment.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ DlgEditEnvironment dee = new DlgEditEnvironment((Frame) SwingUtilities.getWindowAncestor(PnlSearch.this), elementModel, EnvironmentDomain.DOMAIN_ELEMENT, getUser());
+ dee.setVisible(true);
+ }
+ });
+ pbEnvironment.setToolTipText("Modifier les paramètres d'environnement de recherche.");
+ if(dp.isEnvironmentVisible())
+ tb.add(pbEnvironment);
+
+ JButton pbSortFields = new JButton(IhmFactory.getIconFromResource(ImageResources.SORT_FIELDS));
+ pbSortFields.setToolTipText("Champs et tris");
+ pbSortFields.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ DlgSearchParams dsp = new DlgSearchParams(MainWindow.getInstance(), true, elementModel.getListeResultat());
+ dsp.setVisible(true);
+ }
+ });
+ tb.addSeparator();
+ if(dp.isSortFieldsVisible())
+ tb.add(pbSortFields);
+ add(tb, BorderLayout.BEFORE_LINE_BEGINS);
+
+ pbClear.setEnabled(false);
+ pbClear.setToolTipText("Supprimer tous les critères");
+ pbClear.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ clearAll();
+ pluginSearchEnabled = false;
+ addLine();
+ pbSaveRequest.setEnabled(true);
+ }
+ });
+ if(dp.isExportVisible()) {
+ pbExport = new JButton(IhmFactory.getIconFromResource(ImageResources.ACT_EXPORT));
+ pbExport.setToolTipText("Exporter le résultat de recherche");
+ pbExport.setEnabled(false);
+ pbExport.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ JPopupMenu popup = new JPopupMenu();
+ AbstractAction actExportTable = new AbstractAction("Exporter la page courante") {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ exportCSV();
+ }
+ };
+ JMenuItem mnuExportResult = new JMenuItem(actExportTable);
+ AbstractAction actAdvancedExport = new AbstractAction("Export avancé") {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ exportXLS();
+ }
+ };
+ JMenuItem mnuAdvanced = new JMenuItem(actAdvancedExport);
+ popup.add(mnuExportResult);
+ popup.add(mnuAdvanced);
+ JButton source = (JButton)e.getSource();
+ popup.show(source.getParent(), source.getLocation().x+source.getWidth()+3, source.getLocation().y);
+ }
+ });
+ tb.add(pbExport);
+ }
+
+// ajout de la zone pour les criteres
+ scroller = new JPanel(new VerticalFlowLayout(VerticalFlowLayout.TOP, 0, 0));
+ sc = new JScrollPane(scroller);
+ validateHeader();
+ sc.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
+
+ splitter = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
+ splitter.setLeftComponent(sc);
+ splitter.setRightComponent(new JPanel());
+ add(splitter, BorderLayout.CENTER);
+
+ JPanel bottomPane = new JPanel(new BorderLayout());
+ bottomField = new JTextField();
+ bottomField.setEditable(false);
+ bottomField.setBackground(bottomPane.getBackground());
+ bottomField.setBorder(BorderFactory.createEmptyBorder());
+ bottomField.setColumns(75);
+ bottomPane.add(bottomField, BorderLayout.WEST);
+
+ ps = new PageSeeker(this);
+ bottomPane.add(ps, BorderLayout.EAST);
+ add(bottomPane, BorderLayout.SOUTH);
+
+// InputMap im = getInputMap();
+// KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0);
+// im.put(ks, "search");
+// getActionMap().put("search", new AbstractAction() {
+// @Override
+// public void actionPerformed(ActionEvent e) {
+// pbSearch.doClick();
+// }
+// });
+
+ actSearch = new AbstractAction() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ pbSearch.doClick();
+ }
+ };
+
+ if (colls != null) {
+ Vector<Pair> data = new Vector<Pair>();
+ try {
+ data = DataLayerManager.getImplementation().getBudgets(documentModel, currentCollectivite, user);
+ } catch (Exception ex) {
+ Window ancestor = SwingUtilities.getWindowAncestor(PnlSearch.this);
+ if (ancestor instanceof JDialog) {
+ new DisplayExceptionDlg((JDialog) ancestor, ex);
+ } else {
+ new DisplayExceptionDlg((JFrame) ancestor, ex);
+ }
+ }
+ budgets.removeAllItems();
+ for (Pair c : data) {
+ budgets.addItem(c);
+ }
+ if (data.size() > 0) {
+ budgets.setSelectedIndex(0);
+ }
+ validateHeader();
+ }
+ budgets.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ clearAll();
+ validateHeader();
+ }
+ });
+
+ splitter.setDividerLocation(100);
+ }
+ /**
+ * Réalise l'export CSV du résultat de recherche
+ */
+ public void exportCSV() {
+ if(!canExport()) return;
+ EtatResultTableModel ertm =(EtatResultTableModel)getTable().getModel();
+ JFileChooser fc = new JFileChooser();
+ fc.setFileFilter(new FileFilter(){
+ @Override
+ public boolean accept(File f) {
+ return f.isDirectory() || f.getName().toUpperCase().endsWith(".CSV");
+ }
+ @Override
+ public String getDescription() { return "Fichier CSV"; }
+ });
+ ExportOptionPane eop = new ExportOptionPane();
+ fc.setAccessory(eop);
+ if(fc.showSaveDialog(this)==JFileChooser.APPROVE_OPTION) {
+ File f = fc.getSelectedFile();
+ // verification de la presence d'une extension
+ // on cherche un '.' aux positions len-1, len-2, len-3, len-4
+ String fileName = f.getAbsolutePath();
+ int len = fileName.length();
+ if(fileName.substring(len-4).indexOf('.')<0) {
+ fileName=fileName+".CSV";
+ f = new File(fileName);
+ }
+ if(f.exists()) {
+ if(JOptionPane.showConfirmDialog(MainWindow.getInstance(),fileName+"\nCe fichier existe déjà . Voulez-vous l'écraser ?","Ecrasement",JOptionPane.YES_NO_OPTION)==JOptionPane.NO_OPTION)
+ return;
+ }
+ MainWindow.fieldSeparator = eop.getSeparator();
+ String out = null;
+ int[] selectedRows = getTable().getSelectedRows();
+ out = ertm.getCsvBuffer(MainWindow.fieldSeparator,eop.getExportAll(),selectedRows);
+ try {
+ FileWriter fw = new FileWriter(f);
+ fw.write(out);
+ fw.flush();
+ fw.close();
+ } catch(IOException ioEx) {
+ Component comp = this;
+ while(comp!=null && !(comp instanceof JFrame))
+ comp = comp.getParent();
+ new DisplayExceptionDlg((JFrame)comp,ioEx);
+ }
+ }
+ }
+
+ public void exportXLS() {
+ if(!canExport()) return;
+ EtatResultTableModel ertm =(EtatResultTableModel)getTable().getModel();
+
+ DocumentsModel dmsTmp = new DocumentsModel(DocumentsModel.QN);
+ DocumentModel dmTmp = getDocumentModel().clone();
+
+ // on ne garde dans dm que l'EtatModel qui a l'ElementModel em
+ HashMap<String, EtatModel> hTmp = dmTmp.getHEtats();
+ HashMap<String, EtatModel> hTmp2 = new HashMap<String, EtatModel> ();
+ Vector<EtatModel> vTmp2 = new Vector<EtatModel>();
+ for (String k:hTmp.keySet()) {
+ EtatModel emTmp = (EtatModel)hTmp.get(k);
+ if (emTmp.getElementById(elementModel.getId()) != null) {
+ hTmp2.put (emTmp.getId(), emTmp);
+ vTmp2.add(emTmp);
+ dmTmp.setVEtats(vTmp2);
+ dmTmp.setHEtats(hTmp2);
+ break;
+ }
+ }
+ try { dmsTmp.addChild(dmTmp, DocumentModel.QN); } catch (Throwable t) {}
+
+ DlgSearchConfig dlgSc = new DlgSearchConfig (MainWindow.getInstance(), dmsTmp,DlgSearchConfig.EXEC_FROM_RECHERCHE,user);
+ dlgSc.setErtm(ertm);
+ dlgSc.setEm(elementModel);
+ dlgSc.setDm(getDocumentModel());
+ dlgSc.setVisible(true);
+ }
+ private void validateHeader() {
+ currentBudget = (Pair)budgets.getSelectedItem();
+ if(currentBudget!=null && currentCollectivite!=null) {
+ pbSearch.setEnabled(true);
+ pbSearchBackground.setEnabled(true);
+ addLine();
+ }
+ }
+
+ /**
+ * Réalise la recherche et affiche l'éventuel résultat
+ */
+ public void search() {
+ SearchThread searcher = null;
+ setSearchEnabled(false);
+ try {
+ setCursor(new Cursor(Cursor.WAIT_CURSOR));
+ searcher = new SearchThread(this, elementModel, currentCollectivite, currentBudget, criterias, plugin);
+ SwingUtilities.invokeLater(searcher);
+ } catch (OutOfMemoryError oomErr) {
+ searcher.exceptionDuringProcess = oomErr;
+ } finally {
+ }
+ }
+
+ /**
+ * Affiche la liste des widgets associés à cette recherche
+ * @param evt
+ */
+ public void displayWidgetList(MouseEvent evt) {
+ if(!dp.isWidgetsVisible()) return;
+ Point p = evt.getPoint();
+ int row = getTable().rowAtPoint(p);
+ EtatResultTableModel etrm = (EtatResultTableModel)getTable().getModel();
+ JPopupMenu pm = new JPopupMenu();
+ for(WidgetModel wm:etrm.getListeResultat().getWidgets()) {
+ AbstractWidget aw = null;
+ try {
+ Class clazz = Class.forName(wm.getClassName());
+ Constructor cc = clazz.getConstructor(WidgetModel.class,ElementModel.class);
+ aw = (AbstractWidget)cc.newInstance(wm,elementModel);
+ } catch(Exception ex) {
+ new DisplayExceptionDlg(SwingUtilities.getWindowAncestor(getTable()),ex);
+ }
+ if(aw!=null) {
+ WidgetAction wa = new WidgetAction(aw,etrm,((JXTable)getTable()).convertRowIndexToModel(row));
+ pm.add(new JMenuItem(wa));
+ }
+ }
+ if(pm.getComponentCount()>0)
+ pm.show(evt.getComponent(), evt.getX(), evt.getY());
+ }
+
+ /**
+ * Une action sur une ligne du résultat de recherche a été émise
+ * @param evt
+ * @param row La ligne (de la table, pas du modèle) sur laquelle l'événement a été lancé
+ */
+ public abstract void actionOnRowPerformed(MouseEvent evt, int row);
+
+ /**
+ * Réalise le recherche en arrière-plan et affiche l'éventuel résultat
+ */
+ public void searchBackground() {
+ SearchThread searcher = null;
+ setSearchEnabled(false);
+ try {
+ searcher = new SearchThread(this, elementModel, currentCollectivite, currentBudget, criterias, plugin, true);
+ SwingUtilities.invokeLater(searcher);
+ } catch (OutOfMemoryError oomErr) {
+ searcher.exceptionDuringProcess = oomErr;
+ } finally {
+ }
+ }
+
+ /**
+ * Renvoie l'utilisateur ayant ouvert ce panneau
+ * @return
+ */
+ public XemeliosUser getUser() {
+ return user;
+ }
+
+ /**
+ * Renvoie l'élément sur lequel on travaille
+ * @return
+ */
+ public ElementModel getElementModel() {
+ return elementModel;
+ }
+
+ /**
+ * Permet de définir la table
+ * @param table
+ */
+ public void setTable(JTable table) {
+ this.table = table;
+ }
+
+ /**
+ * Renvoie la table de résultat
+ * @return
+ */
+ public JTable getTable() {
+ return table;
+ }
+
+ /**
+ * Renvoie le splitter
+ * @return
+ */
+ public JSplitPane getSplitter() {
+ return splitter;
+ }
+
+ /**
+ * Renvoie le PageSeeker
+ * @return
+ */
+ public PageSeeker getPageSeeker() {
+ return ps;
+ }
+
+ /**
+ * Renvoie la collectivite courante
+ * @return
+ */
+ public Pair getCurrentCollectivite() {
+ return currentCollectivite;
+ }
+
+ /**
+ * Renovie le budget courant
+ * @return
+ */
+ public Pair getCurrentBudget() {
+ return currentBudget;
+ }
+
+ /**
+ * Renvoie le plugin utilisé, ou <code>null</code> si pas de plugin utilisé
+ * @return
+ */
+ public PluginModel getPluginModel() {
+ return this.plugin;
+ }
+
+ /**
+ * Renovie le document sur lequel on travaille
+ * Equivalent à {@link #getElementModel()}<code>.getParent().getParent()</code>
+ * @return
+ */
+ public DocumentModel getDocumentModel() {
+ return this.documentModel;
+ }
+
+ /**
+ * Permet de définir le texte affiché en pied
+ * @param text
+ */
+ public void setBottomText(String text) {
+ bottomField.setText(text);
+ }
+
+ /**
+ * Renoive le titre de la fenêtre ou du dialogue parent
+ * @return
+ */
+ public abstract String getTitle();
+
+ /**
+ * Permet de définir si les exports sont possibles ou non
+ * @param how
+ */
+ public void setCanExport(boolean how) {
+ canExport = how;
+ if(pbExport!=null) pbExport.setEnabled(how);
+ }
+
+ /**
+ * Permet de notifier le parent (en fait, principalement la MainWindow) que le statut
+ * de la fenêtre de recherche a changé. Utile pour gérer les menus
+ */
+ public abstract void notifyParentStateChanged();
+
+ /**
+ * Permet d'iconifier le parent
+ * @param iconified Indiwue si il faut iconifier (<code>true</code>) ou désiconifier (<code>false</code>).
+ */
+ public abstract void iconify(boolean iconified);
+
+ /**
+ * Permet d'afficher la boite d'erreur dans l'EDT
+ */
+ public static class DisplayErrorSearchThread implements Runnable {
+
+ private PnlSearch sw;
+ private Object obj;
+ private ToolException tEx;
+
+ public DisplayErrorSearchThread(PnlSearch sw, ToolException tEx, Object objToFocus) {
+ super();
+ this.sw = sw;
+ this.obj = objToFocus;
+ this.tEx = tEx;
+ }
+
+ @Override
+ public void run() {
+ JOptionPane.showMessageDialog(sw, tEx.getMessage(), "", JOptionPane.WARNING_MESSAGE);
+ sw.setSearchEnabled(true);
+ if (obj != null) {
+ ((CriteriaViewer) (obj)).doFocusOnError();
+ }
+ }
+ };
+
+ private String getRequestName() {
+ return JOptionPane.showInputDialog(this, "Veuillez saisir un nom pour cette recherche :", "Valeur par défaut");
+ }
+
+ private void saveRequest() {
+ String requestName = getRequestName();
+ if (requestName == null || requestName.length() == 0) {
+ return;
+ }
+ RechercheModel rm = new RechercheModel(RechercheModel.QN, requestName);
+ for (CriteriaViewer cv : criterias) {
+ try {
+ rm.addChild(cv.getXmlMarshallable(), CritereModel.QN);
+ } catch (SAXException ignore) {
+ // pour le moment, on la jette bien violement
+ ignore.printStackTrace();
+ }
+ }
+ MainWindow.getInstance().getSavedRequest(elementModel).add(rm);
+ try {
+ DataLayerManager.getImplementation().saveRequest(getElementModel(), rm, getUser());
+ } catch (Exception ex) {
+ logger.error(ex);
+ }
+
+ }
+
+ private void openRequest() {
+ String persistence = null;
+ try {
+ persistence = DataLayerManager.getImplementation().getLayerName();
+ } catch (Throwable t) {
+ }
+ TreeSet<ListDisplayable> data = new TreeSet<ListDisplayable>();
+ if(dp.isSavedRequestsIncluded()) {
+ SavedRequestsModel srm = MainWindow.getInstance().getSavedRequest(elementModel);
+ data.addAll(srm.getRecherches());
+ }
+ Vector<PluginModel> plugins = elementModel.getPlugins();
+ for (PluginModel pm : plugins) {
+ if(pm.isAvailableFor(persistence)) {
+ if (pm.getPluginType().equals(PluginModel.TYPE_SEARCH) && dp.isSearchPluginsIncluded()) {
+ data.add(pm);
+ } else if(pm.getPluginType().equals(PluginModel.TYPE_EXPORT) && dp.isExportPluginsIncluded()) {
+ data.add(pm);
+ }
+ }
+ }
+ Vector<ListDisplayable> vData = new Vector<ListDisplayable>();
+ vData.addAll(data);
+ DlgSelectRequest dsr = new DlgSelectRequest(MainWindow.getInstance(), vData, elementModel);
+ if (dsr.run()) {
+ ListDisplayable xm = (ListDisplayable) dsr.getSelectedItem();
+ if (xm instanceof RechercheModel) {
+ pluginSearchEnabled = false;
+ RechercheModel rm = (RechercheModel) xm;
+ clearAll();
+ for (CritereModel cm : rm.getCriteres()) {
+ CriteriaViewer cv = addLine();
+ cv.changeCritereModel(cm);
+ }
+ pbSaveRequest.setEnabled(true);
+ } else if (xm instanceof PluginModel) {
+ pluginSearchEnabled = true;
+ PluginModel pm = (PluginModel) xm;
+ clearAll();
+ plugin = pm.clone();
+ pbValidateHeader.setEnabled(false);
+ for (CritereModel cm : pm.getCriteres()) {
+ CriteriaViewer cv = addLineNoCriteria();
+ cv.changeCritereModel(cm.clone());
+ criterias.add(cv);
+ }
+ // debug
+ if (pm.getCriteresOp().size() > 0) {
+ pbValidateHeader.setEnabled(true);
+ }
+ criteresOp = new Vector<CritereModel>();
+ for (CritereRefModel cmr : pm.getCriteresOp()) {
+ CritereModel cm = elementModel.getCritere(cmr.getIdRef());
+ criteresOp.add(cm);
+ }
+ // debug
+ pbSaveRequest.setEnabled(false);
+ }
+ }
+ }
+
+ private void showReferentiel() {
+ try {
+ Vector<Document> vXmlData = DataLayerManager.getImplementation().getRepositorysAsDom(documentModel, currentCollectivite, user);
+ if (vXmlData.size() == 0) {
+ JOptionPane.showMessageDialog(this, "Pas de nomenclature disponible");
+ return;
+ }
+
+ // TODO: vérifier que ça marche...
+ XPath xp = XPathFactory.newInstance().newXPath();
+ xp.setNamespaceContext(documentModel.getNamespaces());
+
+ Vector<Node> vRepository = new Vector<Node>();
+ Node repository;
+ for (Document docXml : vXmlData) {
+ repository = (Node) xp.evaluate("//n:" + documentModel.getReferentiel(), docXml.getDocumentElement(), XPathConstants.NODE);
+ vRepository.add(repository);
+ }
+ Document docRoot = FactoryProvider.getDocumentBuilderFactory().newDocumentBuilder().newDocument();
+
+ Element el = docRoot.createElementNS(vXmlData.get(0).getDocumentElement().getNamespaceURI(), vXmlData.get(0).getDocumentElement().getNodeName());
+ docRoot.appendChild(el);
+ //docRoot.appendChild(docRoot.adoptNode(vXmlData.get(0).getDocumentElement()));
+
+ for (int i = 0; i < vXmlData.get(0).getDocumentElement().getChildNodes().getLength(); i++) {
+ Node current = vXmlData.get(0).getDocumentElement().getChildNodes().item(i);
+ if (!current.getNodeName().equals("Nomenclatures") && Node.TEXT_NODE != current.getNodeType()) {
+ docRoot.adoptNode(current);
+ docRoot.getDocumentElement().appendChild(current);
+ }
+ }
+
+ if (vRepository != null && vRepository.size() > 0) {
+ for (int i = 0; i < vRepository.size(); i++) {
+ Node nomencl = vRepository.get(i);
+ if (nomencl != null) {
+ docRoot.adoptNode(nomencl);
+ docRoot.getDocumentElement().appendChild(nomencl);
+ }
+ }
+ }
+
+ File xslFile = new File(new File(documentModel.getBaseDirectory()), documentModel.getReferentielXsltFile());
+ InputStream is = IoUtils.getInputStream(xslFile.getPath());
+ //InputStream htmlStream = DematTransform.transform(new ByteArrayInputStream(sXmlData.getBytes(encoding)),is,encoding);
+ TransformerFactory tFactory = FactoryProvider.getTransformerFactory();
+ tFactory.setURIResolver(new CustomURIResolver(tFactory.getURIResolver(), xslFile.toURI().toURL().toExternalForm()));
+ Transformer t = tFactory.newTransformer(new StreamSource(is));
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ t.transform(new DOMSource(docRoot.getDocumentElement()), new StreamResult(baos));
+ ByteArrayInputStream htmlStream = new ByteArrayInputStream(baos.toByteArray());
+ MainWindow.getInstance().displayHtmlStream(htmlStream, etatModel, MainWindow.getInstance().getDesk());
+
+ } catch (Exception ex) {
+ new DisplayExceptionDlg(SwingUtilities.getWindowAncestor(this), ex);
+ }
+ }
+
+ /**
+ * Permet d'afficher un nouveau titre (autre que celui d'origine), sans modifier
+ * le titre d'origine.
+ * @param newTitle
+ */
+ public abstract void setTitle(String newTitle);
+
+ /**
+ * Permet de réafficher le titre d'origine
+ */
+ public abstract void redisplayTitle();
+
+ /**
+ * Affiche une animation qui fait patienter
+ */
+ public abstract void startWaiter();
+
+ /**
+ * Arrête l'animation qui fait patienter
+ */
+ public abstract void stopWaiter();
+
+ /**
+ * Indique si le panneau est dans un état où on peut exporter
+ * @return
+ */
+ public abstract boolean canExport();
+
+ /**
+ * Permet de sélectionner une collexctivité
+ * @param collectivite
+ */
+ public void setCollectivite(Pair collectivite) {
+ if(modeCollectivite==MODE_COLLECTIVITES.MODE_LIST) {
+ colls.setSelectedItem(collectivite);
+ } else {
+ currentCollectivite = collectivite;
+ dfCollectivite.setText(collectivite.libelle);
+ Vector<Pair> data = new Vector<Pair>();
+ try {
+ data = DataLayerManager.getImplementation().getBudgets(documentModel, currentCollectivite, user);
+ } catch (Exception ex) {
+ Window ancestor = SwingUtilities.getWindowAncestor(PnlSearch.this);
+ if (ancestor instanceof JDialog) {
+ new DisplayExceptionDlg((JDialog) ancestor, ex);
+ } else {
+ new DisplayExceptionDlg((JFrame) ancestor, ex);
+ }
+ }
+ budgets.removeAllItems();
+ for (Pair c : data) {
+ budgets.addItem(c);
+ }
+ if (data.size() > 0) {
+ budgets.setSelectedIndex(0);
+ }
+ clearAll();
+ pluginSearchEnabled = false;
+ addLine();
+ pbSaveRequest.setEnabled(true);
+ pbValidateHeader.setEnabled(true);
+ }
+ }
+ /**
+ * Permet de sélectionner un budget
+ * @param budget
+ */
+ public void setBudget(Pair budget) {
+ budgets.setSelectedItem(budget);
+ }
+
+ public SearchContext getSearchContext() {
+ SearchContext sCtx = new SearchContext(currentCollectivite, currentBudget);
+ sCtx.setUser(getUser());
+ for(CriteriaViewer cv: criterias) {
+ sCtx.addCritere((CritereModel)cv.getXmlMarshallable());
+ }
+ return sCtx;
+ }
+
+ public PropertiesExpansion getApplicationProperties() {
+ return applicationProperties;
+ }
+
+ /**
+ * Renvoie l'action pour la recherche
+ * @return
+ */
+ public AbstractAction getActionSearch() {
+ return actSearch;
+ }
+
+ public static class DisplayParameters {
+ /**
+ * Permet de déterminer si il faut afficher le bouton d'ajout de critères
+ */
+ private boolean addCriteriaVisible = true;
+ /**
+ * Permet de déterminer si il faut afficher le bouton de recherche en arrière-plan
+ */
+ private boolean searchBackgroundVisible = true;
+ /**
+ * Permet de déterminer si il faut afficher le bouton de suppression de tous les critères
+ */
+ private boolean clearAllVisible = true;
+ /**
+ * Permet de déterminer si il faut afficher le bouton d'accès au repository
+ */
+ private boolean showRepositoryVisible = true;
+ /**
+ * Permet de déterminer si il faut afficher le bouton d'enregistrement de requêtes
+ */
+ private boolean saveRequestVisible = true;
+ /**
+ * Permet de déterminer si il faut afficher le bouton d'ouverture de requêtes
+ */
+ private boolean openRequestVisible = true;
+ /**
+ * Permet de déterminer si il faut afficherle bouton de modification de l'environnement
+ */
+ private boolean environmentVisible = true;
+ /**
+ * Permet de déterminer si il faut afficher le bouton permettant de choisir les champs et les tris
+ */
+ private boolean sortFieldsVisible = true;
+ /**
+ * Permet de détermnier si on affiche les widgets
+ */
+ private boolean widgetsVisible = true;
+ /**
+ * Permet de déterminer si les recherches enregistrées sont incluses
+ */
+ private boolean savedRequestsIncluded = true;
+ /**
+ * Permet de déterminer si les plugins de recherche sont inclus
+ */
+ private boolean searchPluginsIncluded = true;
+ /**
+ * Permet de déterminer si les plugins d'export sont inclus
+ */
+ private boolean exportPluginsIncluded = true;
+ /**
+ * Permet de déterminer si l'utilisateur peut modifier la collectivité
+ */
+ private boolean collectiviteEditable = true;
+ /**
+ * Permet de déterminer si l'utilisateur peut modifier le budget
+ */
+ private boolean budgetEditable = true;
+ /**
+ * Permet de déterminer si on affiche les sommations
+ */
+ private boolean summableVisible = true;
+ /**
+ * Permet de savoir si on affiche ou pas le bouton d'export
+ */
+ private boolean exportVisible = true;
+
+ public DisplayParameters() {
+ super();
+ }
+
+ public boolean isAddCriteriaVisible() {
+ return addCriteriaVisible;
+ }
+
+ public void setAddCriteriaVisible(boolean addCriteriaVisible) {
+ this.addCriteriaVisible = addCriteriaVisible;
+ }
+
+ public boolean isClearAllVisible() {
+ return clearAllVisible;
+ }
+
+ public void setClearAllVisible(boolean clearAllVisible) {
+ this.clearAllVisible = clearAllVisible;
+ }
+
+ public boolean isEnvironmentVisible() {
+ return environmentVisible;
+ }
+
+ public void setEnvironmentVisible(boolean environmentVisible) {
+ this.environmentVisible = environmentVisible;
+ }
+
+ public boolean isExportPluginsIncluded() {
+ return exportPluginsIncluded;
+ }
+
+ public void setExportPluginsIncluded(boolean exportPluginsIncluded) {
+ this.exportPluginsIncluded = exportPluginsIncluded;
+ }
+
+ public boolean isOpenRequestVisible() {
+ return openRequestVisible;
+ }
+
+ public void setOpenRequestVisible(boolean openRequestVisible) {
+ this.openRequestVisible = openRequestVisible;
+ }
+
+ public boolean isSaveRequestVisible() {
+ return saveRequestVisible;
+ }
+
+ public void setSaveRequestVisible(boolean saveRequestVisible) {
+ this.saveRequestVisible = saveRequestVisible;
+ }
+
+ public boolean isSavedRequestsIncluded() {
+ return savedRequestsIncluded;
+ }
+
+ public void setSavedRequestsIncluded(boolean savedRequestsIncluded) {
+ this.savedRequestsIncluded = savedRequestsIncluded;
+ }
+
+ public boolean isSearchBackgroundVisible() {
+ return searchBackgroundVisible;
+ }
+
+ public void setSearchBackgroundVisible(boolean searchBackgroundVisible) {
+ this.searchBackgroundVisible = searchBackgroundVisible;
+ }
+
+ public boolean isSearchPluginsIncluded() {
+ return searchPluginsIncluded;
+ }
+
+ public void setSearchPluginsIncluded(boolean searchPluginsIncluded) {
+ this.searchPluginsIncluded = searchPluginsIncluded;
+ }
+
+ public boolean isShowRepositoryVisible() {
+ return showRepositoryVisible;
+ }
+
+ public void setShowRepositoryVisible(boolean showRepositoryVisible) {
+ this.showRepositoryVisible = showRepositoryVisible;
+ }
+
+ public boolean isSortFieldsVisible() {
+ return sortFieldsVisible;
+ }
+
+ public void setSortFieldsVisible(boolean sortFieldsVisible) {
+ this.sortFieldsVisible = sortFieldsVisible;
+ }
+
+ public boolean isWidgetsVisible() {
+ return widgetsVisible;
+ }
+
+ public void setWidgetsVisible(boolean widgetsVisible) {
+ this.widgetsVisible = widgetsVisible;
+ }
+
+ public boolean isBudgetEditable() {
+ return budgetEditable;
+ }
+
+ public void setBudgetEditable(boolean budgetEditable) {
+ this.budgetEditable = budgetEditable;
+ }
+
+ public boolean isCollectiviteEditable() {
+ return collectiviteEditable;
+ }
+
+ public void setCollectiviteEditable(boolean collectiviteEditable) {
+ this.collectiviteEditable = collectiviteEditable;
+ }
+
+ public boolean isSummableVisible() {
+ return summableVisible;
+ }
+
+ public void setSummableVisible(boolean summableVisible) {
+ this.summableVisible = summableVisible;
+ }
+
+ public boolean isExportVisible() {
+ return exportVisible;
+ }
+
+ public void setExportVisible(boolean exportVisible) {
+ this.exportVisible = exportVisible;
+ }
+
+ }
+ private class WidgetAction extends AbstractAction {
+ private AbstractWidget aw;
+ private EtatResultTableModel etrm;
+ private int row;
+ public WidgetAction(AbstractWidget aw,EtatResultTableModel etrm,int row) {
+ super(aw.getWidgetModel().getLibelle());
+ this.aw=aw;
+ this.etrm=etrm;
+ this.row=row;
+ }
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ aw.run(etrm,row);
+ }
+ }
+ private class ExportOptionPane extends JPanel {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+ boolean allSelection = false;
+ String separator = MainWindow.fieldSeparator;
+ private JTextField fldSep;
+ private JRadioButton rbAll, rbSelection;
+
+ public ExportOptionPane() {
+ super();
+ initComponents();
+ }
+ private void initComponents() {
+ FormLayout fl = new FormLayout("1dlu,pref,1dlu","1dlu,pref,1dlu,pref,4dlu,pref,1dlu,pref,1dlu");
+ CellConstraints cc = new CellConstraints();
+ PanelBuilder pb = new PanelBuilder(fl,this);
+ IhmFactory iF=IhmFactory.newInstance();
+
+ int col = 2;
+ int start = 2;
+
+ pb.add(iF.newLabel("Séparateur"), cc.xy(col,0+start));
+ pb.add(fldSep = new JTextField(separator), cc.xy(col,2+start));
+ pb.add(rbSelection = new JRadioButton("Séléction"), cc.xy(col,4+start));
+ pb.add(rbAll = new JRadioButton("Tout"), cc.xy(col,6+start));
+ ButtonGroup bg = new ButtonGroup();
+ bg.add(rbSelection); bg.add(rbAll);
+ rbAll.setSelected(true);
+
+ setVisible(true);
+ }
+
+ public String getSeparator() {
+ String sep = fldSep.getText();
+ if("\\t".equals(sep)) sep = "\t";
+ return sep;
+ }
+ public boolean getExportAll() {
+ return rbAll.isSelected();
+ }
+ }
+ public static class ExportOptionPaneXLS extends JPanel {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+ boolean allSelection = false;
+ private JRadioButton rbAll, rbSelection;
+
+ public ExportOptionPaneXLS() {
+ super();
+ initComponents();
+ }
+ private void initComponents() {
+ FormLayout fl = new FormLayout("1dlu,pref,1dlu","1dlu,pref,1dlu,pref,4dlu,pref,1dlu,pref,1dlu");
+ CellConstraints cc = new CellConstraints();
+ PanelBuilder pb = new PanelBuilder(fl,this);
+ IhmFactory iF=IhmFactory.newInstance();
+
+ int col = 2;
+ int start = 2;
+
+ pb.add(rbSelection = new JRadioButton("Séléction"), cc.xy(col,4+start));
+ pb.add(rbAll = new JRadioButton("Tout"), cc.xy(col,6+start));
+ ButtonGroup bg = new ButtonGroup();
+ bg.add(rbSelection); bg.add(rbAll);
+ rbAll.setSelected(true);
+
+ setVisible(true);
+ }
+
+ public boolean getExportAll() {
+ return rbAll.isSelected();
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui.search;
+
+import java.awt.Cursor;
+import java.text.DecimalFormat;
+import java.text.NumberFormat;
+import java.util.TreeSet;
+
+import javax.swing.JScrollPane;
+import javax.swing.table.TableModel;
+
+import org.apache.log4j.Logger;
+import org.jdesktop.swingx.JXTable;
+
+import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ListeResultatModel;
+import fr.gouv.finances.dgfip.xemelios.data.DataResultSet;
+import fr.gouv.finances.dgfip.xemelios.data.CachedData;
+import fr.gouv.finances.dgfip.xemelios.data.DataHandler;
+import fr.gouv.finances.cp.xemelios.ui.resulttable.EtatResultTableModel;
+import fr.gouv.finances.cp.xemelios.ui.resulttable.ResultTable;
+
+/**
+ * @author chm
+ */
+public class ResultDisplayerThread extends Thread {
+ private static Logger logger = Logger.getLogger(ResultDisplayerThread.class);
+ private DataResultSet rs;
+ private ListeResultatModel lrm;
+ private long start, startParsing;
+ private ElementModel em;
+ private PnlSearch sw;
+
+ public ResultDisplayerThread(DataResultSet rs, ListeResultatModel lrm, long start, ElementModel em, PnlSearch sw) {
+ super("ResultDisplayer");
+ this.rs=rs;
+ this.lrm=lrm;
+ this.start=start;
+ this.em=em;
+ this.sw=sw;
+ }
+ @SuppressWarnings("serial")
+ @Override
+ public void run() {
+ startParsing=System.currentTimeMillis();
+ try {
+ TreeSet<DataHandler> ts = new TreeSet<DataHandler>();
+ int count = 0;
+ CachedData cache = new CachedData();
+ if(rs==null) {
+ sw.setBottomText("Aucun enregistrement trouvé");
+ } else {
+ rs.setEnvironment(lrm,cache);
+ while(rs.hasNext()) {
+ DataHandler dh = rs.next();
+ if(dh==null) continue;
+ ts.add(dh);
+ count++;
+ }
+ rs.clear();
+ if(true) {
+ // on vide l'ancienne table
+ JXTable oldTable = (JXTable)sw.getTable();
+ JXTable table = null;
+ boolean tableIsNew = false;
+ if(oldTable!=null) {
+ EtatResultTableModel oldModel = (EtatResultTableModel)oldTable.getModel();
+ oldModel.dispose();
+ table = oldTable;
+ } else {
+ table = new ResultTable(null,sw,em,sw.getUser(), sw.getApplicationProperties());
+ tableIsNew = true;
+ }
+ TableModel tm = new EtatResultTableModel(lrm,ts,rs);
+ table.setModel(tm);
+ if(tableIsNew) {
+ sw.setTable(table);
+ int pos = sw.getSplitter().getDividerLocation();
+ JScrollPane scrollTable = new JScrollPane(table);
+ scrollTable.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
+ scrollTable.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
+ sw.getSplitter().setRightComponent(scrollTable);
+ sw.getSplitter().setDividerLocation(pos);
+ sw.getSplitter().paintImmediately(sw.getSplitter().getBounds());
+ }
+ }
+ double duration = (System.currentTimeMillis()-start)/1000d;
+ double durationSearch = (startParsing-start)/1000d;
+ double durationParsing = (System.currentTimeMillis()-startParsing)/1000d;
+ NumberFormat nf = new DecimalFormat("0.0##");
+ sw.setBottomText(rs.getEstimatedSize()+" "+em.getParent().getImportableElement().getTitre()+"(s) trouvé(s) en "+nf.format(duration)+" s ("+nf.format(durationSearch)+" s recherche, "+nf.format(durationParsing)+" s affichage)");
+ sw.getPageSeeker().updateData(rs);
+ }
+ sw.setCanExport(ts.size()>0);
+ sw.notifyParentStateChanged();
+ } finally {
+ sw.setCursor(Cursor.getDefaultCursor());
+ sw.stopWaiter();
+ sw.setSearchEnabled(true);
+ }
+ }
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2010 axYus - http://www.axyus.com
+ * 2010 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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 2 of the License, or
+ * (at your option) any later version.
+ *
+ * XEMELIOS 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 Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.search;
+
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+import fr.gouv.finances.dgfip.xemelios.common.config.CritereModel;
+import java.util.ArrayList;
+
+/**
+ * Represente un contexte de recherche
+ * @author cmarchand
+ */
+public class SearchContext {
+
+ private Pair collectivite;
+ private Pair budget;
+ private XemeliosUser user;
+ // les criteres
+ ArrayList<CritereModel> criteres;
+
+ public SearchContext() {
+ super();
+ }
+ public SearchContext(Pair collectivite, Pair budget) {
+ this();
+ this.collectivite=collectivite;
+ this.budget = budget;
+ }
+
+ public Pair getBudget() {
+ return budget;
+ }
+
+ public void setBudget(Pair budget) {
+ this.budget = budget;
+ }
+
+ public Pair getCollectivite() {
+ return collectivite;
+ }
+
+ public void setCollectivite(Pair collectivite) {
+ this.collectivite = collectivite;
+ }
+
+ public XemeliosUser getUser() {
+ return user;
+ }
+
+ public void setUser(XemeliosUser user) {
+ this.user = user;
+ }
+
+ public ArrayList<CritereModel> getCriteres() {
+ return criteres;
+ }
+
+ public void addCritere(CritereModel cm) {
+ if(criteres==null) criteres = new ArrayList<CritereModel>();
+ criteres.add(cm);
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui.search;
+
+import java.awt.Cursor;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Vector;
+
+import javax.swing.SwingUtilities;
+
+import org.apache.log4j.Logger;
+
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
+import fr.gouv.finances.dgfip.xemelios.common.ToolException;
+import fr.gouv.finances.dgfip.xemelios.common.config.ChampModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.CritereModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.HiddenModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ListeResultatModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.PluginModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.WidgetModel;
+import fr.gouv.finances.dgfip.xemelios.data.DataResultSet;
+import fr.gouv.finances.cp.xemelios.plugins.ExportPluginRunner;
+import fr.gouv.finances.cp.xemelios.plugins.SearchPluginRunner;
+import fr.gouv.finances.cp.xemelios.ui.CriteriaViewer;
+//import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+import fr.gouv.finances.dgfip.xemelios.plugins.ExportPlugin;
+import fr.gouv.finances.dgfip.xemelios.plugins.SearchPlugin;
+import java.lang.reflect.Constructor;
+
+/**
+ * Le thread qui lance la recherche, en dehors de l'EDT
+ * @author chm
+ */
+public class SearchThread extends Thread {
+
+ private static Logger logger = Logger.getLogger(SearchThread.class);
+ public Throwable exceptionDuringProcess = null;
+ public Object obj = null;
+ private boolean background;
+ private PnlSearch parentCaller;
+ private ElementModel elementModel = null;
+ private Pair collectivite = null, budget = null;
+ private PluginModel plugin = null;
+ private Vector<CriteriaViewer> criterias = null;
+
+ public SearchThread(PnlSearch parent, ElementModel elementModel, Pair collectivite, Pair budget, Vector<CriteriaViewer> criterias, PluginModel plugin) {
+ super("Searcher");
+ background = false;
+ this.parentCaller = parent;
+ this.elementModel = elementModel;
+ this.collectivite = collectivite;
+ this.budget = budget;
+ this.criterias = criterias;
+ this.plugin = plugin;
+ }
+
+ public SearchThread(PnlSearch parent, ElementModel elementModel, Pair collectivite, Pair budget, Vector<CriteriaViewer> criterias, PluginModel plugin, boolean runInBackground) {
+ this(parent, elementModel, collectivite, budget, criterias, plugin);
+ background = runInBackground;
+ }
+
+ @Override
+ public void run() {
+ long start = System.currentTimeMillis();
+ setPriority(MIN_PRIORITY);
+ if (plugin == null) {
+ simpleSearch(start);
+ } else {
+ if (PluginModel.TYPE_SEARCH.equals(plugin.getPluginType())) {
+ pluginSearch(start);
+ } else if (PluginModel.TYPE_EXPORT.equals(plugin.getPluginType())) {
+ pluginExport(start);
+ }
+ }
+ if (exceptionDuringProcess != null) {
+ if(!(exceptionDuringProcess instanceof ToolException))
+ new DisplayExceptionDlg(SwingUtilities.getWindowAncestor(parentCaller), exceptionDuringProcess);
+ }
+ }
+
+ protected CriteriaViewer getDoublon (Vector<CriteriaViewer>vcv) {
+ Vector<String> ids = new Vector<String>();
+ for (CriteriaViewer cv:vcv) {
+ // est-ce un CV avec un bouton supprimer ?
+ if (!cv.isHideRemoveIcon()) {
+ if (ids.contains(cv.getCurrentCritereModel().getId())) return cv;
+ ids.add(cv.getCurrentCritereModel().getId());
+ }
+ }
+ return null;
+ }
+
+ protected void pluginSearch(long start) {
+ Hashtable<String, String> parameters = new Hashtable<String, String>();
+ boolean shouldContinue = true;
+ for (CriteriaViewer cv : criterias) {
+ try {
+ parameters.putAll(cv.getParameters());
+ } catch (ToolException tEx) {
+ // un champ a mal ete saisi
+ shouldContinue = false;
+ exceptionDuringProcess = tEx;
+ obj = cv;
+ }
+ }
+ /**
+ * On teste si on est en mode recherche par plugin
+ * et si dans la liste des critères optionnels utilisés
+ * on n'a pas de doublon
+ */
+ CriteriaViewer doublon = null;
+ if ((doublon = getDoublon (criterias))!=null) {
+ obj = doublon;//.focusOnDelete();
+ doublon.focusOnDelete();
+ exceptionDuringProcess = new ToolException("Il n'est pas possible d'utiliser plusieurs fois le même critère optionnel dans une recherche prédéfinie. Veuillez supprimer les doublons.", ToolException.ERROR_MISFILLED_CRITERIA);
+ shouldContinue = false;
+ }
+ if (shouldContinue) {
+ try {
+ Class clazz = Class.forName(plugin.getPluginClass());
+ Constructor cc = clazz.getConstructor(XemeliosUser.class);
+ SearchPlugin xp = (SearchPlugin) cc.newInstance(parentCaller.getUser());
+ xp.setPluginModel(plugin);
+ xp.setCollectivite(collectivite);
+ xp.setBudget(budget);
+
+ SearchPluginRunner runner = new SearchPluginRunner(parentCaller.getUser());
+ runner.setPlugin(xp);
+ runner.setParameters(parameters);
+ runner.setSearchWindow(parentCaller);
+ runner.setElementModel(elementModel);
+ runner.setListeResultat(getListeResultat());
+ runner.setStart(start);
+ runner.startSearch();
+ } catch (ClassNotFoundException cnfEx) {
+ exceptionDuringProcess = cnfEx;
+ } catch (InstantiationException iEx) {
+ exceptionDuringProcess = iEx;
+ } catch (IllegalAccessException iaEx) {
+ exceptionDuringProcess = iaEx;
+ } catch (Exception ex) {
+ exceptionDuringProcess = ex;
+ }
+ } else {
+ // erreur de saisie des criteres
+ parentCaller.stopWaiter();
+ parentCaller.setCursor(Cursor.getDefaultCursor());
+ Runnable code = new PnlSearch.DisplayErrorSearchThread(parentCaller, (ToolException) exceptionDuringProcess, obj);
+ if (SwingUtilities.isEventDispatchThread()) {
+ code.run();
+ } else {
+ SwingUtilities.invokeLater(code);
+ }
+ }
+ }
+
+ protected void pluginExport(long start) {
+// throw new RuntimeException("not yet implemented");
+ logger.debug("entering pluginxport");
+ Hashtable<String, String> parameters = new Hashtable<String, String>();
+ boolean shouldContinue = true;
+ for (CriteriaViewer cv : criterias) {
+ try {
+ parameters.putAll(cv.getParameters());
+ } catch (ToolException tEx) {
+ // un champ a mal ete saisi
+ shouldContinue = false;
+ exceptionDuringProcess = tEx;
+ obj = cv;
+ }
+ }
+ if (shouldContinue) {
+ try {
+ Class clazz = Class.forName(plugin.getPluginClass());
+ Constructor cc = clazz.getConstructor(XemeliosUser.class);
+ ExportPlugin xp = (ExportPlugin) cc.newInstance(parentCaller.getUser());
+ xp.setPluginModel(plugin);
+ xp.setCollectivite(collectivite);
+ xp.setBudget(budget);
+ xp.setElementModel(elementModel);
+ xp.setParameters(parameters);
+
+ ExportPluginRunner runner = new ExportPluginRunner(parentCaller.getUser());
+ runner.setPlugin(xp);
+ runner.setStart(start);
+ runner.setSearchWindow(parentCaller);
+ runner.startExport();
+ } catch (ClassNotFoundException cnfEx) {
+ exceptionDuringProcess = cnfEx;
+ } catch (InstantiationException iEx) {
+ exceptionDuringProcess = iEx;
+ } catch (IllegalAccessException iaEx) {
+ exceptionDuringProcess = iaEx;
+ } catch (Exception ex) {
+ exceptionDuringProcess = ex;
+ }
+ } else {
+ // erreur de saisie des criteres
+ parentCaller.stopWaiter();
+ parentCaller.setCursor(Cursor.getDefaultCursor());
+ Runnable code = new PnlSearch.DisplayErrorSearchThread(parentCaller, (ToolException) exceptionDuringProcess, obj);
+ if (SwingUtilities.isEventDispatchThread()) {
+ code.run();
+ } else {
+ SwingUtilities.invokeLater(code);
+ }
+ }
+ }
+
+ protected void simpleSearch(long start) {
+ StringBuffer buff = new StringBuffer();
+ buff.append(elementModel.getPath().getPath());
+ boolean shouldContinue = true;
+ HashMap<String, ChampModel> additionnalFields = new HashMap<String, ChampModel>();
+ Vector<CritereModel> models = new Vector<CritereModel>();
+ for (CriteriaViewer cv : criterias) {
+ CritereModel cm = cv.getModel();
+ models.add(cm);
+ try {
+ if (cv.getAndOrEr().equals(CriteriaViewer.OR_ASSOCIATOR)) {
+ buff.append("|").append(elementModel.getPath().getPath());
+ }
+ buff.append(cv.getXPathExpr());
+
+ if (cv.isOptionalDisplayChecked()) {
+ // to add the optional columns to display
+ String idAffichage = cm.getIdAffichage();
+ if (idAffichage != null && idAffichage.length() > 0) {
+ // Look for the "champ" matching this ID in the result list...
+ ChampModel champOptionnel = elementModel.getListeResultat().getChamps().get(idAffichage).clone();
+ // ... and add it to the optional field list
+ if (champOptionnel != null) {
+ additionnalFields.put(champOptionnel.getId(), champOptionnel);
+ }
+ }
+ }
+ } catch (ToolException tEx) {
+ shouldContinue = false;
+ parentCaller.stopWaiter();
+ setPriority(NORM_PRIORITY);
+ if (tEx.getErrorCode() != ToolException.ERROR_MISFILLED_CRITERIA) {
+ logger.error(tEx.getMessage(), tEx);
+ } else {
+ parentCaller.setCursor(Cursor.getDefaultCursor());
+ exceptionDuringProcess = tEx;
+ obj = cv;
+ }
+ Runnable code = new PnlSearch.DisplayErrorSearchThread(parentCaller, tEx, obj);
+ if (SwingUtilities.isEventDispatchThread()) {
+ code.run();
+ } else {
+ SwingUtilities.invokeLater(code);
+ }
+ exceptionDuringProcess = null;
+ break;
+ } catch (Exception ex) {
+ shouldContinue = false;
+ exceptionDuringProcess = ex;
+ parentCaller.stopWaiter();
+ }
+ }
+ if (!shouldContinue) {
+ parentCaller.stopWaiter();
+ parentCaller.setCursor(Cursor.getDefaultCursor());
+ return;
+ }
+ if (background) {
+ Runnable code = new Runnable() {
+
+ public void run() {
+ logger.debug("iconify");
+ parentCaller.setTitle("Recherche en cours...");
+ parentCaller.iconify(true);
+ }
+ };
+ if (SwingUtilities.isEventDispatchThread()) {
+ code.run();
+ } else {
+ try {
+ SwingUtilities.invokeAndWait(code);
+ } catch (Throwable t) {
+ }
+ }
+ Thread.yield();
+ setPriority(Thread.MIN_PRIORITY);
+ }
+ ListeResultatModel lrm = new ListeResultatModel(ListeResultatModel.QN);
+ lrm.setParent(elementModel);
+
+ for (ChampModel cm : additionnalFields.values()) {
+ try {
+ lrm.addChild(cm, ChampModel.QN);
+ } catch (Throwable t) {
+ } // c'est nous qu'on maitrise, on fait pas de
+ // conneries
+ }
+ ListeResultatModel lrm2 = elementModel.getListeResultat().clone();
+ for (ChampModel cm : lrm2.getListeChamps()) {
+ try {
+ if (cm.isAfficheDefaut() && cm.isAffichable()) {
+ lrm.addChild(cm, ChampModel.QN);
+ }
+ } catch (Throwable t) {
+ } // c'est nous qu'on maitrise toujours
+ }
+ lrm.setTriDefaut(lrm2.getTriDefaut());
+ lrm.setOrdre(lrm2.getOrdre());
+ for (HiddenModel hm : lrm2.getHiddens()) {
+ try {
+ lrm.addChild(hm, HiddenModel.QN);
+ } catch (Throwable t) {
+ } //qu'on matrise toujours, ouyouyouille !
+ }
+ for (WidgetModel wm : lrm2.getWidgets()) {
+ try {
+ lrm.addChild(wm, WidgetModel.QN);
+ } catch (Throwable t) {
+ }
+ }
+ try {
+ XPathExecuter xe = new XPathExecuter(elementModel, buff.toString(), models, collectivite, budget, lrm, start, parentCaller);
+ if (background) {
+ xe.addPropertyChangeListener(new PropertyChangeListener() {
+
+ public void propertyChange(PropertyChangeEvent evt) {
+ if ("COMPLETED".equals(evt.getPropertyName()) && Boolean.TRUE.equals(evt.getNewValue())) {
+ Runnable code = new Runnable() {
+
+ public void run() {
+ logger.debug("uniconify");
+ parentCaller.redisplayTitle();
+ parentCaller.iconify(false);
+ }
+ };
+ if (SwingUtilities.isEventDispatchThread()) {
+ code.run();
+ } else {
+ SwingUtilities.invokeLater(code);
+ }
+ }
+ }
+ });
+ }
+ xe.execute();
+ try {
+ xe.get();
+ } catch (Throwable t) { /* only to wait for completion */
+ }
+ } catch (Throwable th) {
+ th.printStackTrace();
+ if (th instanceof OutOfMemoryError) {
+ exceptionDuringProcess = new ToolException("Mémoire insuffisante pour cette requête. \nEssayez d'augmenter les paramètres -Xmx et -Xss de la JVM ou affinez votre requête.", ToolException.ERROR_DB_ENGINE);
+ } else if (th instanceof StackOverflowError) {
+ exceptionDuringProcess = new ToolException("Mémoire insuffisante pour cette requête. \nEssayez d'augmenter les paramètres -Xmx et -Xss de la JVM ou affinez votre requête.", ToolException.ERROR_DB_ENGINE);
+ } else {
+ exceptionDuringProcess = th;
+ }
+ }
+ }
+
+ protected ListeResultatModel getListeResultat() {
+ HashMap<String, ChampModel> additionnalFields = new HashMap<String, ChampModel>();
+ for (CriteriaViewer cv : criterias) {
+ CritereModel cm = cv.getModel();
+ try {
+
+ if (cv.isOptionalDisplayChecked()) {
+ // to add the optional columns to display
+ String idAffichage = cm.getIdAffichage();
+ if (idAffichage != null && idAffichage.length() > 0) {
+ // Look for the "champ" matching this ID in the result list...
+ ChampModel champOptionnel = elementModel.getListeResultat().getChamps().get(idAffichage).clone();
+ // ... and add it to the optional field list
+ if (champOptionnel != null) {
+ additionnalFields.put(champOptionnel.getId(), champOptionnel);
+ }
+ }
+ }
+ } catch (Exception ex) {
+ }
+ }
+ ListeResultatModel lrm = new ListeResultatModel(ListeResultatModel.QN);
+ lrm.setParent(elementModel);
+
+ for (ChampModel cm : additionnalFields.values()) {
+ try {
+ lrm.addChild(cm, ChampModel.QN);
+ } catch (Throwable t) { }
+ }
+ ListeResultatModel lrm2 = elementModel.getListeResultat().clone();
+ for (ChampModel cm : lrm2.getListeChamps()) {
+ try {
+ if (cm.isAfficheDefaut() && cm.isAffichable()) {
+ lrm.addChild(cm, ChampModel.QN);
+ }
+ } catch (Throwable t) { }
+ }
+ lrm.setTriDefaut(lrm2.getTriDefaut());
+ lrm.setOrdre(lrm2.getOrdre());
+ for (HiddenModel hm : lrm2.getHiddens()) {
+ try {
+ lrm.addChild(hm, HiddenModel.QN);
+ } catch (Throwable t) { }
+ }
+ for (WidgetModel wm : lrm2.getWidgets()) {
+ try {
+ lrm.addChild(wm, WidgetModel.QN);
+ } catch (Throwable t) {
+ }
+ }
+ return lrm;
+ }
+
+ /**
+ * display the result
+ *
+ * @param rs
+ * @param lrm
+ * @param start
+ * @deprecated. Instead, call this method in the done() method of a
+ * SwingWorker
+ */
+ protected void displayResult(DataResultSet rs, ListeResultatModel lrm, long start) {
+ Runnable code = new ResultDisplayerThread(rs, lrm, start, elementModel, parentCaller);
+ if (SwingUtilities.isEventDispatchThread()) {
+ code.run();
+ } else {
+ try {
+ SwingUtilities.invokeAndWait(code);
+ } catch (Throwable t) {
+ }
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui.search;
+
+import java.util.Vector;
+
+import javax.swing.SwingUtilities;
+
+import org.apache.log4j.Logger;
+import org.jdesktop.swingworker.SwingWorker;
+
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
+//import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.dgfip.xemelios.common.config.CritereModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ListeResultatModel;
+import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
+import fr.gouv.finances.dgfip.xemelios.data.DataResultSet;
+import fr.gouv.finances.cp.xemelios.ui.SearchWindow;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+
+/**
+ * @author chm
+ *
+ * TODO To change the template for this generated type comment go to Window -
+ * Preferences - Java - Code Style - Code Templates
+ */
+public class XPathExecuter extends SwingWorker<DataResultSet, String> {
+ private static Logger logger=Logger.getLogger(XPathExecuter.class);
+ private ListeResultatModel lrm;
+
+ private long start;
+ private String xPathQuery;
+
+ private ElementModel elementModel;
+ private Pair collectivite,budget;
+ private Vector<CritereModel> models = null;
+
+ private PnlSearch sw;
+
+ private XemeliosUser user;
+
+ private Throwable errorWhileSearching;
+
+ public XPathExecuter(ElementModel elementModel, String xPathQuery, Vector<CritereModel> models, Pair collectivite, Pair budget, ListeResultatModel lrm, long start, PnlSearch sw) {
+ super();
+ this.xPathQuery = xPathQuery;
+ this.models=models;
+ this.lrm = lrm;
+ this.start = start;
+ this.elementModel = elementModel;
+ this.collectivite=collectivite;
+ this.budget=budget;
+ this.sw = sw;
+ this.user=sw.getUser();
+ }
+ @Override
+ public DataResultSet doInBackground() {
+ try {
+ logger.debug("XQuery="+xPathQuery);
+ DataResultSet rs = DataLayerManager.getImplementation().search(elementModel,collectivite,budget,xPathQuery,lrm,models,user);
+ return rs;
+ }
+ catch (Throwable t) {
+ logger.error("une erreur est survenue.",t);
+ try {
+ errorWhileSearching = t;
+ // on error, try to return an empty ResultSetClient
+ return DataLayerManager.getImplementation().getEmptyDataResultSet();
+ }
+ catch (Throwable t2) {}
+ }
+ return null;
+ }
+ @Override
+ public void done() {
+ try {
+ if (errorWhileSearching != null) {
+ Runnable code = new Runnable() {
+ public void run() {
+ DisplayExceptionDlg.displayException(SwingUtilities.getWindowAncestor(sw), errorWhileSearching);
+ }
+ };
+ if (SwingUtilities.isEventDispatchThread())
+ code.run();
+ else SwingUtilities.invokeLater(code);
+ } else {
+ DataResultSet rs = get();
+ Runnable code = new ResultDisplayerThread(rs, lrm, start, elementModel, sw);
+ if (SwingUtilities.isEventDispatchThread())
+ code.run();
+ else try {
+ SwingUtilities.invokeAndWait(code);
+ }
+ catch (Throwable t) {}
+ }
+ firePropertyChange("COMPLETED", Boolean.FALSE, Boolean.TRUE);
+ }
+ catch (Throwable t) {
+ DisplayExceptionDlg.displayException(SwingUtilities.getWindowAncestor(sw), t);
+ }
+ finally {
+ sw.stopWaiter();
+ }
+ }
+}
--- /dev/null
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.searchParams;
+
+/**
+ *
+ * @author chm
+ */
+public interface CommonDataUpdater {
+ /**
+ * Force data to be updated
+ */
+ public void doUpdate();
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.3" maxVersion="1.5" type="org.netbeans.modules.form.forminfo.JDialogFormInfo">
+ <Properties>
+ <Property name="defaultCloseOperation" type="int" value="2"/>
+ <Property name="title" type="java.lang.String" value="Tris et champs affichés"/>
+ </Properties>
+ <SyntheticProperties>
+ <SyntheticProperty name="formSizePolicy" type="int" value="1"/>
+ </SyntheticProperties>
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="2"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="tabs" alignment="0" pref="544" max="32767" attributes="0"/>
+ <Group type="102" alignment="1" attributes="0">
+ <Component id="pbCancel" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="pbOk" min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Component id="tabs" pref="333" max="32767" attributes="0"/>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="pbOk" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="pbCancel" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Container class="javax.swing.JTabbedPane" name="tabs">
+
+ <Layout class="org.netbeans.modules.form.compat2.layouts.support.JTabbedPaneSupportLayout"/>
+ </Container>
+ <Component class="javax.swing.JButton" name="pbOk">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Ok"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbOkActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="pbCancel">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Annuler"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbCancelActionPerformed"/>
+ </Events>
+ </Component>
+ </SubComponents>
+</Form>
--- /dev/null
+/*
+ * Copyright
+ * 2008 axYus - www.axyus.com
+ * 2008 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.searchParams;
+
+import fr.gouv.finances.cp.xemelios.ui.searchParams.CommonDataUpdater;
+import fr.gouv.finances.dgfip.xemelios.common.config.ListeResultatModel;
+import java.awt.event.ActionEvent;
+import java.awt.event.KeyEvent;
+import java.util.ArrayList;
+import java.util.List;
+import javax.swing.AbstractAction;
+import javax.swing.JComponent;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JRootPane;
+import javax.swing.KeyStroke;
+
+/**
+ *
+ * @author chm
+ */
+public class DlgSearchParams extends javax.swing.JDialog {
+ private List<CommonDataUpdater> panels;
+ private ListeResultatModel originalReference;
+ private ListeResultatModel currentlyModified;
+ private AbstractAction escapeAction;
+
+ /** Creates new form DlgSearchParams */
+ public DlgSearchParams(java.awt.Frame parent, boolean modal,ListeResultatModel lrm) {
+ super(parent, modal);
+ originalReference = lrm;
+ currentlyModified = originalReference.clone();
+ initComponents();
+ postInitComponents();
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ tabs = new javax.swing.JTabbedPane();
+ pbOk = new javax.swing.JButton();
+ pbCancel = new javax.swing.JButton();
+
+ setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+ setTitle("Tris et champs affichés");
+
+ pbOk.setText("Ok");
+ pbOk.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbOkActionPerformed(evt);
+ }
+ });
+
+ pbCancel.setText("Annuler");
+ pbCancel.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbCancelActionPerformed(evt);
+ }
+ });
+
+ org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(tabs, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 544, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
+ .add(pbCancel)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(pbOk)))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(tabs, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 333, Short.MAX_VALUE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(pbOk)
+ .add(pbCancel))
+ .addContainerGap())
+ );
+
+ pack();
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void pbOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbOkActionPerformed
+ for(CommonDataUpdater cdu:panels) cdu.doUpdate();
+
+ // on verifie que les champs triés sont dans les champs affiches
+ String[] tri=currentlyModified.getTriDefaut().split(",");
+ for(String s:tri) {
+ if(!currentlyModified.getChamps().get(s).isAfficheDefaut()) {
+ JOptionPane.showMessageDialog(this, "Vous ne pouvez pas trier sur un champ que vous n'affichez pas.","Erreur",JOptionPane.WARNING_MESSAGE);
+ return;
+ }
+ }
+ // et maintenant, reporter les modifs dans le original
+ originalReference.setOrdre(currentlyModified.getOrdre());
+ originalReference.setTriDefaut(currentlyModified.getTriDefaut());
+ originalReference.changeAllDisplayableChamps(currentlyModified.getListeChamps());
+ setVisible(false);
+}//GEN-LAST:event_pbOkActionPerformed
+
+ private void pbCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbCancelActionPerformed
+ setVisible(false);
+ }//GEN-LAST:event_pbCancelActionPerformed
+
+ protected void postInitComponents() {
+ panels = new ArrayList<CommonDataUpdater>();
+ JPanel jp2 = new PnlFields(currentlyModified);
+ tabs.add("Champs",jp2);
+ panels.add((CommonDataUpdater)jp2);
+ JPanel jp = new PnlSortBy(currentlyModified);
+ tabs.add("Tri", jp);
+ panels.add((CommonDataUpdater)jp);
+ }
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JButton pbCancel;
+ private javax.swing.JButton pbOk;
+ private javax.swing.JTabbedPane tabs;
+ // End of variables declaration//GEN-END:variables
+
+ @Override
+ protected JRootPane createRootPane() {
+ KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0);
+ JRootPane rp = new JRootPane();
+ escapeAction = new AbstractAction("Annuler") {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+
+ public void actionPerformed(ActionEvent evt) {
+ setVisible(false);
+ }
+ };
+ rp.registerKeyboardAction(escapeAction,"TOTOTOTO",ks,JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
+ }
+
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.3" maxVersion="1.5" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="2"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="1" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="jScrollPane1" pref="329" max="32767" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="1" attributes="0">
+ <Component id="pbUp" min="-2" max="-2" attributes="0"/>
+ <Component id="pbDown" alignment="1" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="1" attributes="0">
+ <EmptySpace min="-2" pref="13" max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="jScrollPane1" alignment="0" pref="275" max="32767" attributes="0"/>
+ <Group type="102" alignment="0" attributes="0">
+ <Component id="pbUp" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="pbDown" min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Container class="javax.swing.JScrollPane" name="jScrollPane1">
+ <AuxValues>
+ <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
+ </AuxValues>
+
+ <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
+ <SubComponents>
+ <Component class="javax.swing.JTable" name="tblFields">
+ <Properties>
+ <Property name="model" type="javax.swing.table.TableModel" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
+ <Connection code="tblModel = new PnlFields.DisplayableFieldsTableModel(lrm)" type="code"/>
+ </Property>
+ </Properties>
+ </Component>
+ </SubComponents>
+ </Container>
+ <Component class="javax.swing.JButton" name="pbUp">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="^"/>
+ <Property name="toolTipText" type="java.lang.String" value="Monter"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbUpActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="pbDown">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="V"/>
+ <Property name="toolTipText" type="java.lang.String" value="Descendre"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbDownActionPerformed"/>
+ </Events>
+ </Component>
+ </SubComponents>
+</Form>
--- /dev/null
+/*
+ * PnlFields.java
+ *
+ * Created on 15 septembre 2008, 11:29
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.searchParams;
+
+import fr.gouv.finances.dgfip.xemelios.common.config.ChampModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ListeResultatModel;
+import java.util.Vector;
+import javax.swing.ListSelectionModel;
+import javax.swing.table.AbstractTableModel;
+
+/**
+ *
+ * @author chm
+ */
+public class PnlFields extends javax.swing.JPanel implements CommonDataUpdater {
+ private ListeResultatModel lrm;
+ private DisplayableFieldsTableModel tblModel;
+
+ /** Creates new form PnlFields */
+ public PnlFields(ListeResultatModel lrm) {
+ super();
+ this.lrm=lrm;
+ initComponents();
+ tblFields.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ jScrollPane1 = new javax.swing.JScrollPane();
+ tblFields = new javax.swing.JTable();
+ pbUp = new javax.swing.JButton();
+ pbDown = new javax.swing.JButton();
+
+ tblFields.setModel(tblModel = new PnlFields.DisplayableFieldsTableModel(lrm));
+ jScrollPane1.setViewportView(tblFields);
+
+ pbUp.setText("^");
+ pbUp.setToolTipText("Monter");
+ pbUp.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbUpActionPerformed(evt);
+ }
+ });
+
+ pbDown.setText("V");
+ pbDown.setToolTipText("Descendre");
+ pbDown.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbDownActionPerformed(evt);
+ }
+ });
+
+ org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
+ this.setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
+ .addContainerGap()
+ .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
+ .add(pbUp)
+ .add(pbDown))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
+ .add(13, 13, 13)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 275, Short.MAX_VALUE)
+ .add(layout.createSequentialGroup()
+ .add(pbUp)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(pbDown)))
+ .addContainerGap())
+ );
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void pbUpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbUpActionPerformed
+ int i = tblFields.getSelectedRow();
+ if(i>0) {
+ ChampModel cm = tblModel.getData().remove(i);
+ tblModel.getData().insertElementAt(cm, i-1);
+ tblModel.fireTableDataChanged();
+ tblFields.setRowSelectionInterval(i-1, i-1);
+ }
+}//GEN-LAST:event_pbUpActionPerformed
+
+ private void pbDownActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbDownActionPerformed
+ int i = tblFields.getSelectedRow();
+ if(i<tblModel.getData().size()-1) {
+ ChampModel cm = tblModel.getData().remove(i);
+ tblModel.getData().insertElementAt(cm, i+1);
+ tblModel.fireTableDataChanged();
+ tblFields.setRowSelectionInterval(i+1, i+1);
+ }
+ }//GEN-LAST:event_pbDownActionPerformed
+
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JScrollPane jScrollPane1;
+ private javax.swing.JButton pbDown;
+ private javax.swing.JButton pbUp;
+ private javax.swing.JTable tblFields;
+ // End of variables declaration//GEN-END:variables
+
+ public void doUpdate() {
+ for(int i=lrm.getListeChamps().size()-1;i>=0;i--) {
+ ChampModel cm = lrm.getListeChamps().elementAt(i);
+ if(cm.isAffichable()) {
+ lrm.getChamps().remove(cm);
+ lrm.getListeChamps().remove(cm);
+ }
+ }
+ for(ChampModel cm:tblModel.getData()) {
+ try {
+ lrm.addChild(cm, ChampModel.QN);
+ } catch(Throwable t) {}
+ }
+ }
+
+ public static class DisplayableFieldsTableModel extends AbstractTableModel {
+ Vector<ChampModel> data;
+
+ public DisplayableFieldsTableModel (ListeResultatModel lrm) {
+ data = new Vector<ChampModel>();
+ for(ChampModel cm: lrm.getListeChamps()) {
+ if(cm.isAffichable()) data.add(cm); // cm.clone() ?
+ }
+ }
+
+ public int getRowCount() {
+ return data.size();
+ }
+
+ public int getColumnCount() {
+ return 2;
+ }
+
+ public Object getValueAt(int rowIndex, int columnIndex) {
+ ChampModel cm = data.elementAt(rowIndex);
+ if(columnIndex==0) return cm.isAfficheDefaut();
+ else return cm.getLibelle();
+ }
+
+ @Override
+ public Class<?> getColumnClass(int columnIndex) {
+ if(columnIndex==0) return Boolean.class;
+ else return String.class;
+ }
+
+ @Override
+ public String getColumnName(int column) {
+ if(column==0) return "Afficher";
+ else return "Champ";
+ }
+
+ @Override
+ public boolean isCellEditable(int rowIndex, int columnIndex) {
+ return columnIndex==0;
+ }
+
+ @Override
+ public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
+ ChampModel cm = data.elementAt(rowIndex);
+ if(columnIndex==0) cm.setAfficheDefaut(((Boolean)aValue).booleanValue());
+ }
+
+ public Vector<ChampModel> getData() { return data; }
+ }
+
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.3" maxVersion="1.5" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="2"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="jScrollPane1" min="-2" pref="267" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="1" attributes="0">
+ <Group type="103" groupAlignment="0" max="-2" attributes="0">
+ <Component id="pbAddOne" alignment="1" max="32767" attributes="1"/>
+ <Component id="pbAddAll" alignment="1" max="32767" attributes="1"/>
+ <Component id="pbRemoveAll" alignment="1" min="0" pref="0" max="32767" attributes="1"/>
+ <Component id="pbRemoveOne" alignment="1" max="32767" attributes="1"/>
+ </Group>
+ <Group type="103" groupAlignment="0" max="-2" attributes="0">
+ <Component id="pbDown" alignment="1" max="32767" attributes="1"/>
+ <Component id="pbUp" alignment="1" min="-2" max="-2" attributes="1"/>
+ </Group>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="jScrollPane2" pref="187" max="32767" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="1" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="1" attributes="0">
+ <Component id="jScrollPane1" alignment="0" pref="286" max="32767" attributes="0"/>
+ <Component id="jScrollPane2" alignment="1" pref="286" max="32767" attributes="0"/>
+ <Group type="102" alignment="0" attributes="0">
+ <Component id="pbAddAll" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="pbAddOne" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="pbRemoveOne" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="pbRemoveAll" min="-2" max="-2" attributes="0"/>
+ <EmptySpace pref="118" max="32767" attributes="0"/>
+ <Component id="pbUp" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="pbDown" min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Container class="javax.swing.JScrollPane" name="jScrollPane1">
+ <AuxValues>
+ <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
+ </AuxValues>
+
+ <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
+ <SubComponents>
+ <Component class="javax.swing.JList" name="lstChamps">
+ <Properties>
+ <Property name="model" type="javax.swing.ListModel" editor="org.netbeans.modules.form.editors2.ListModelEditor">
+ <StringArray count="5">
+ <StringItem index="0" value="Item 1"/>
+ <StringItem index="1" value="Item 2"/>
+ <StringItem index="2" value="Item 3"/>
+ <StringItem index="3" value="Item 4"/>
+ <StringItem index="4" value="Item 5"/>
+ </StringArray>
+ </Property>
+ </Properties>
+ </Component>
+ </SubComponents>
+ </Container>
+ <Container class="javax.swing.JScrollPane" name="jScrollPane2">
+ <AuxValues>
+ <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
+ </AuxValues>
+
+ <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
+ <SubComponents>
+ <Component class="org.jdesktop.swingx.JXTable" name="tblChampTries">
+ <Properties>
+ <Property name="model" type="javax.swing.table.TableModel" editor="org.netbeans.modules.form.editors2.TableModelEditor">
+ <Table columnCount="4" rowCount="4">
+ <Column editable="true" title="Title 1" type="java.lang.Object"/>
+ <Column editable="true" title="Title 2" type="java.lang.Object"/>
+ <Column editable="true" title="Title 3" type="java.lang.Object"/>
+ <Column editable="true" title="Title 4" type="java.lang.Object"/>
+ </Table>
+ </Property>
+ </Properties>
+ <AuxValues>
+ <AuxValue name="JavaCodeGenerator_CreateCodeCustom" type="java.lang.String" value="new org.jdesktop.swingx.JXTable() {
 public void valueChanged(ListSelectionEvent e) {
 super.valueChanged(e);
 tableListSelectionChanged(e);
 }
 public TableCellEditor getCellEditor(int row,int column) {
 if(column==0) return super.getCellEditor(row, column);
 else {
 DefaultCellEditor dce = new DefaultCellEditor(cbxSortBy);
 cbxSortBy.setSelectedItem(getValueAt(row,column));
 return dce;
 }
 }
}"/>
+ </AuxValues>
+ </Component>
+ </SubComponents>
+ </Container>
+ <Component class="javax.swing.JButton" name="pbAddAll">
+ <Properties>
+ <Property name="text" type="java.lang.String" value=">>"/>
+ <Property name="toolTipText" type="java.lang.String" value="Tout ajouter"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbAddAllActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="pbAddOne">
+ <Properties>
+ <Property name="text" type="java.lang.String" value=">"/>
+ <Property name="toolTipText" type="java.lang.String" value="Ajouter"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbAddOneActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="pbRemoveOne">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="<"/>
+ <Property name="toolTipText" type="java.lang.String" value="Retirer"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbRemoveOneActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="pbRemoveAll">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="<<"/>
+ <Property name="toolTipText" type="java.lang.String" value="Tout retirer"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbRemoveAllActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="pbUp">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="^"/>
+ <Property name="toolTipText" type="java.lang.String" value="Monter"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbUpActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="pbDown">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="V"/>
+ <Property name="toolTipText" type="java.lang.String" value="Descendre"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbDownActionPerformed"/>
+ </Events>
+ </Component>
+ </SubComponents>
+</Form>
--- /dev/null
+/*
+ * Copyright
+ * 2008 axYus - www.axyus.com
+ * 2008 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.searchParams;
+
+import fr.gouv.finances.dgfip.xemelios.common.config.ChampModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ListeResultatModel;
+import java.util.List;
+import java.util.StringTokenizer;
+import java.util.Vector;
+import javax.swing.JComboBox;
+import javax.swing.DefaultCellEditor;
+import javax.swing.table.AbstractTableModel;
+import javax.swing.table.TableCellEditor;
+import javax.swing.event.ListSelectionEvent;
+import javax.swing.event.ListSelectionListener;
+
+/**
+ *
+ * @author chm
+ */
+public class PnlSortBy extends javax.swing.JPanel implements CommonDataUpdater {
+ private ListeResultatModel lrm;
+// private ArrayList<ChampModel> displayableChamps;
+ private Vector<ChampModel> sortableChamps;
+ private Vector<ChampTriable> champsTriables;
+ private AbstractTableModel tm;
+ private JComboBox cbxSortBy;
+
+ /** Creates new form PnlSortBy */
+ public PnlSortBy(ListeResultatModel lrm) {
+ this.lrm=lrm;
+ initComponents();
+ initData();
+ initListeners();
+ }
+ protected void initListeners() {
+ pbUp.setEnabled(false);
+ pbDown.setEnabled(false);
+// pbRemoveAll.setEnabled(false);
+ pbRemoveOne.setEnabled(false);
+// pbAddAll.setEnabled(false);
+ pbAddOne.setEnabled(false);
+ lstChamps.addListSelectionListener(new ListSelectionListener() {
+ public void valueChanged(ListSelectionEvent e) {
+ if(lstChamps.getSelectedIndices().length==0) {
+// pbAddAll.setEnabled(false);
+ pbAddOne.setEnabled(false);
+ } else {
+ pbAddAll.setEnabled(true);
+ pbAddOne.setEnabled(true);
+ }
+ }
+ });
+ }
+ public void initData() {
+ cbxSortBy = new JComboBox(new String[] { "ASC", "DESC"});
+ sortableChamps = new Vector<ChampModel>();
+ List<ChampModel> champs = lrm.getListeChamps();
+ for(ChampModel cm:champs) {
+ if(cm.isTriable()) sortableChamps.add(cm);
+ }
+ champsTriables = new Vector<ChampTriable>();
+ String triDefaut = lrm.getTriDefaut();
+ String ordreDefaut = lrm.getOrdre();
+ String champsTri[] = triDefaut.split(",");
+ StringTokenizer to = new StringTokenizer(ordreDefaut,",");
+ for(String ch:champsTri) {
+ String or = to.nextToken();
+ if(or==null) or = "ASC";
+ champsTriables.add(new ChampTriable(ch, lrm.getChamps().get(ch).getLibelle(), or));
+ sortableChamps.remove(lrm.getChamps().get(ch));
+ }
+ tm = new TriableTableModel(champsTriables);
+ tblChampTries.setModel(tm);
+ lstChamps.setListData(sortableChamps);
+ }
+ public void tableListSelectionChanged(ListSelectionEvent e) {
+ if(tblChampTries.getSelectedRows().length==0) {
+ pbUp.setEnabled(false);
+ pbDown.setEnabled(false);
+// pbRemoveAll.setEnabled(false);
+ pbRemoveOne.setEnabled(false);
+ } else {
+ pbUp.setEnabled(true);
+ pbDown.setEnabled(true);
+ pbRemoveAll.setEnabled(true);
+ pbRemoveOne.setEnabled(true);
+ }
+ }
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ jScrollPane1 = new javax.swing.JScrollPane();
+ lstChamps = new javax.swing.JList();
+ jScrollPane2 = new javax.swing.JScrollPane();
+ tblChampTries = new org.jdesktop.swingx.JXTable() {
+ public void valueChanged(ListSelectionEvent e) {
+ super.valueChanged(e);
+ tableListSelectionChanged(e);
+ }
+ public TableCellEditor getCellEditor(int row,int column) {
+ if(column==0) return super.getCellEditor(row, column);
+ else {
+ DefaultCellEditor dce = new DefaultCellEditor(cbxSortBy);
+ cbxSortBy.setSelectedItem(getValueAt(row,column));
+ return dce;
+ }
+ }
+ };
+ pbAddAll = new javax.swing.JButton();
+ pbAddOne = new javax.swing.JButton();
+ pbRemoveOne = new javax.swing.JButton();
+ pbRemoveAll = new javax.swing.JButton();
+ pbUp = new javax.swing.JButton();
+ pbDown = new javax.swing.JButton();
+
+ lstChamps.setModel(new javax.swing.AbstractListModel() {
+ String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
+ public int getSize() { return strings.length; }
+ public Object getElementAt(int i) { return strings[i]; }
+ });
+ jScrollPane1.setViewportView(lstChamps);
+
+ tblChampTries.setModel(new javax.swing.table.DefaultTableModel(
+ new Object [][] {
+ {null, null, null, null},
+ {null, null, null, null},
+ {null, null, null, null},
+ {null, null, null, null}
+ },
+ new String [] {
+ "Title 1", "Title 2", "Title 3", "Title 4"
+ }
+ ));
+ jScrollPane2.setViewportView(tblChampTries);
+
+ pbAddAll.setText(">>");
+ pbAddAll.setToolTipText("Tout ajouter");
+ pbAddAll.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbAddAllActionPerformed(evt);
+ }
+ });
+
+ pbAddOne.setText(">");
+ pbAddOne.setToolTipText("Ajouter");
+ pbAddOne.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbAddOneActionPerformed(evt);
+ }
+ });
+
+ pbRemoveOne.setText("<");
+ pbRemoveOne.setToolTipText("Retirer");
+ pbRemoveOne.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbRemoveOneActionPerformed(evt);
+ }
+ });
+
+ pbRemoveAll.setText("<<");
+ pbRemoveAll.setToolTipText("Tout retirer");
+ pbRemoveAll.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbRemoveAllActionPerformed(evt);
+ }
+ });
+
+ pbUp.setText("^");
+ pbUp.setToolTipText("Monter");
+ pbUp.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbUpActionPerformed(evt);
+ }
+ });
+
+ pbDown.setText("V");
+ pbDown.setToolTipText("Descendre");
+ pbDown.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbDownActionPerformed(evt);
+ }
+ });
+
+ org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
+ this.setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 267, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, pbAddOne, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, pbAddAll, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, pbRemoveAll, 0, 0, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, pbRemoveOne, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, pbDown, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, pbUp)))
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 187, Short.MAX_VALUE)
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
+ .addContainerGap()
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
+ .add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 286, Short.MAX_VALUE)
+ .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 286, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
+ .add(pbAddAll)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(pbAddOne)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(pbRemoveOne)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(pbRemoveAll)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 118, Short.MAX_VALUE)
+ .add(pbUp)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(pbDown)))
+ .addContainerGap())
+ );
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void pbUpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbUpActionPerformed
+ boolean moved = false;
+ int[] selectedRows = tblChampTries.getSelectedRows();
+ for(int i=0;i<selectedRows.length;i++) {
+ int row = selectedRows[i];
+ if(row>i) {
+ ChampTriable ch = champsTriables.remove(row);
+ champsTriables.insertElementAt(ch, row-1);
+ moved = true;
+ }
+ }
+ if(moved) {
+ tm.fireTableDataChanged();
+ for(int i=0;i<selectedRows.length;i++) {
+ int row = selectedRows[i];
+ if(row>i) {
+ tblChampTries.getSelectionModel().addSelectionInterval(row-1, row-1);
+ }
+ }
+ }
+}//GEN-LAST:event_pbUpActionPerformed
+
+ private void pbDownActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbDownActionPerformed
+ // TODO: corriger cette méthode
+
+ int[] selectedRows = tblChampTries.getSelectedRows();
+ boolean moved = false;
+ for(int i=selectedRows.length-1;i>=0;i--) {
+ int row = selectedRows[i];
+ if(row<champsTriables.size()-i-1) {
+ ChampTriable ch = champsTriables.remove(row);
+ if(row+1 < champsTriables.size())
+ champsTriables.insertElementAt(ch, row+1);
+ else
+ champsTriables.add(ch);
+ moved=true;
+ }
+ }
+ if(moved) {
+ tm.fireTableDataChanged();
+ for(int i=selectedRows.length-1;i>=0;i--) {
+ int row = selectedRows[i];
+ if(row<champsTriables.size()-i) {
+ tblChampTries.getSelectionModel().addSelectionInterval(row+1, row+1);
+ }
+ }
+ }
+ }//GEN-LAST:event_pbDownActionPerformed
+
+ private void pbAddAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbAddAllActionPerformed
+ for(ChampModel cm:sortableChamps) {
+ ChampTriable ct = new ChampTriable(cm.getId(), cm.getLibelle(), "ASC");
+ champsTriables.add(ct);
+ }
+ sortableChamps.clear();
+ lstChamps.setListData(sortableChamps);
+ tm.fireTableDataChanged();
+ }//GEN-LAST:event_pbAddAllActionPerformed
+
+ private void pbAddOneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbAddOneActionPerformed
+ int[] indexes = lstChamps.getSelectedIndices();
+ for(int i:indexes) {
+ ChampModel cm = sortableChamps.get(i);
+ champsTriables.add(new ChampTriable(cm.getId(), cm.getLibelle(),"ASC"));
+ }
+ for(int i=indexes.length-1;i>=0;i--) sortableChamps.remove(indexes[i]);
+ lstChamps.setListData(sortableChamps);
+ tm.fireTableDataChanged();
+ }//GEN-LAST:event_pbAddOneActionPerformed
+
+ private void pbRemoveOneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbRemoveOneActionPerformed
+ int[] indexes = tblChampTries.getSelectedRows();
+ for(int i:indexes) {
+ ChampTriable ct = champsTriables.get(i);
+ ChampModel cm = lrm.getChamps().get(ct.id);
+ sortableChamps.add(cm);
+ }
+ for(int i=indexes.length-1;i>=0;i--) champsTriables.remove(indexes[i]);
+ lstChamps.setListData(sortableChamps);
+ tm.fireTableDataChanged();
+ }//GEN-LAST:event_pbRemoveOneActionPerformed
+
+ private void pbRemoveAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbRemoveAllActionPerformed
+ for(ChampTriable ct:champsTriables) {
+ ChampModel cm = lrm.getChamps().get(ct.id);
+ sortableChamps.add(cm);
+ }
+ champsTriables.clear();
+ lstChamps.setListData(sortableChamps);
+ tm.fireTableDataChanged();
+ }//GEN-LAST:event_pbRemoveAllActionPerformed
+
+ public void doUpdate() {
+ StringBuffer fields = new StringBuffer();
+ StringBuffer sorts = new StringBuffer();
+ for(ChampTriable ct:champsTriables) {
+ fields.append(ct.id).append(",");
+ sorts.append(ct.sens).append(",");
+ }
+ if(fields.length()>0) {
+ fields.deleteCharAt(fields.length()-1);
+ sorts.deleteCharAt(sorts.length()-1);
+ }
+ lrm.setTriDefaut(fields.toString());
+ lrm.setOrdre(sorts.toString());
+ }
+
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JScrollPane jScrollPane1;
+ private javax.swing.JScrollPane jScrollPane2;
+ private javax.swing.JList lstChamps;
+ private javax.swing.JButton pbAddAll;
+ private javax.swing.JButton pbAddOne;
+ private javax.swing.JButton pbDown;
+ private javax.swing.JButton pbRemoveAll;
+ private javax.swing.JButton pbRemoveOne;
+ private javax.swing.JButton pbUp;
+ private org.jdesktop.swingx.JXTable tblChampTries;
+ // End of variables declaration//GEN-END:variables
+
+ public static class ChampTriable {
+ private String id, sens, desc;
+ public ChampTriable(String id, String desc, String sens) {
+ super();
+ this.id=id;
+ this.desc=desc;
+ this.sens=sens;
+ }
+ @Override
+ public String toString() { return desc; }
+ }
+ public static class TriableTableModel extends AbstractTableModel {
+ private Vector<ChampTriable> champs;
+ public TriableTableModel(Vector<ChampTriable> champs) {
+// super(champs,null);
+ this.champs=champs;
+ }
+
+ @Override
+ public String getColumnName(int column) {
+ switch(column) {
+ case 0: return "Champ";
+ case 1: return "Sens";
+ }
+ return null;
+ }
+
+ public int getColumnCount() {
+ return 2;
+ }
+
+ @Override
+ public boolean isCellEditable(int row, int column) {
+ return column==1;
+ }
+
+ public Object getValueAt(int row, int column) {
+ ChampTriable ct = champs.get(row);
+ switch(column) {
+ case 0: return ct.toString();
+ case 1: return ct.sens;
+ }
+ return null;
+ }
+
+ public int getRowCount() {
+ return champs.size();
+ }
+
+ @Override
+ public Class<?> getColumnClass(int columnIndex) {
+ return String.class;
+ }
+
+ @Override
+ public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
+ ChampTriable ct = champs.get(rowIndex);
+ ct.sens = aValue.toString();
+ }
+
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2011 axYus - http://www.axyus.com
+ * 2011 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS_NB.
+ *
+ * XEMELIOS_NB 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 2 of the License, or
+ * (at your option) any later version.
+ *
+ * XEMELIOS_NB 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 Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with XEMELIOS_NB; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+package fr.gouv.finances.cp.xemelios.ui.tools;
+
+import fr.gouv.finances.cp.xemelios.importers.ImportServiceSwingProvider;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.Loader;
+import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
+import fr.gouv.finances.dgfip.xemelios.importers.EtatImporteur;
+import fr.gouv.finances.dgfip.xemelios.importers.XemeliosArchiveImporter;
+import fr.gouv.finances.dgfip.xemelios.tools.ServiceException;
+import fr.gouv.finances.dgfip.xemelios.tools.ToolServiceProviderFactory;
+import fr.gouv.finances.dgfip.xemelios.tools.XemeliosToolServiceProvider;
+import java.io.File;
+import java.lang.reflect.Constructor;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ *
+ * @author cmarchand
+ */
+public class SwingToolServiceProviderFactory extends ToolServiceProviderFactory {
+
+ private SwingToolServiceProvider service;
+
+ public SwingToolServiceProviderFactory() {
+ super();
+ service = new SwingToolServiceProvider();
+ }
+
+ @Override
+ public XemeliosToolServiceProvider getServiceProvider() {
+ return service;
+ }
+
+ private class SwingToolServiceProvider implements XemeliosToolServiceProvider {
+
+ @Override
+ public List<String> getAvailableDocumentsConfigurations() {
+ ArrayList<String> ids = new ArrayList<String>();
+ try {
+ for (DocumentModel dm : Loader.getDocumentsInfos(null).getDocuments()) {
+ ids.add(dm.getId());
+ }
+ } catch (Exception ex) {
+ // on peut ignorer
+ }
+ return ids;
+ }
+
+ @Override
+ public List<String> getSearchableDocumentsConfigurations() {
+ return getAvailableDocumentsConfigurations();
+ }
+
+ @Override
+ public List<String> getImportableDocumentsConfigurations() {
+ ArrayList<String> ids = new ArrayList<String>();
+ try {
+ for (DocumentModel dm : Loader.getDocumentsInfos(null).getDocuments()) {
+ if (dm.isImportable()) {
+ ids.add(dm.getId());
+ }
+ }
+ } catch (Exception ex) {
+ // on peut ignorer
+ }
+ return ids;
+ }
+
+ @Override
+ public List<String> getBrowsableDocumentsConfigurations() {
+ ArrayList<String> ids = new ArrayList<String>();
+ try {
+ for (DocumentModel dm : Loader.getDocumentsInfos(null).getDocuments()) {
+ if (dm.isBrowsable()) {
+ ids.add(dm.getId());
+ }
+ }
+ } catch (Exception ex) {
+ // on peut ignorer
+ }
+ return ids;
+ }
+
+ @Override
+ public String getDocumentConfigurationTitle(String documentId) {
+ try {
+ return Loader.getDocumentsInfos(null).getDocumentById(documentId).getTitre();
+ } catch (Exception ex) {
+ return null;
+ }
+ }
+
+ @Override
+ public void importFile(File fileToImport, String documentId) throws ServiceException {
+ if (Constants.XEMELIOS_ARCHIVE_SIGN.equals(documentId)) {
+ importXemeliosArchive(fileToImport);
+ } else {
+ try {
+ DocumentModel dm = Loader.getDocumentsInfos(null).getDocumentById(documentId);
+ if (!DataLayerManager.getImplementation().canImportDocument(documentId, MainWindow.getInstance().getConnectedUser())) {
+ String message =
+ "L'import de ce type de document est pour le moment impossible.\n"
+ + "La base de donnée doit être mise à jour avant.\n"
+ + "Prenez contact avec votre administrateur pour faire la mise à jour depuis le serveur.";
+ throw new ServiceException(message);
+ }
+ Class clazz = Class.forName(dm.getImportClass());
+ Constructor cc = clazz.getConstructor(XemeliosUser.class);
+ Object obj = cc.newInstance(MainWindow.getInstance().getConnectedUser());
+ if (!(obj instanceof EtatImporteur)) {
+ throw new ServiceException("Cette classe n'est pas un importeur.\nLe fichier de configuration qui vous a été livré est certainement invalide.\nVeuillez contacter votre fournisseur.");
+ }
+ EtatImporteur ei = (EtatImporteur) obj;
+ MainWindow.ImportContent fToImport = new MainWindow.ImportContent();
+ ArrayList<File> files = new ArrayList<File>();
+ files.add(fileToImport);
+ fToImport.setFilesToImport(files);
+ if (fToImport.getImportCount() > 0) {
+ MainWindow.getInstance().doImport(ei, fToImport, dm, false);
+ }
+ } catch (Exception ex) {
+ throw new ServiceException(ex);
+ } finally {
+ //waiter.stopProgress();
+ }
+ }
+ }
+
+ private void importXemeliosArchive(File archive) throws ServiceException {
+ try {
+ ImportServiceSwingProvider isp = new ImportServiceSwingProvider(MainWindow.getInstance(), null, 0);
+ isp.setDisplayFeedback(false);
+ XemeliosArchiveImporter xai = new XemeliosArchiveImporter(Loader.getDocumentsInfos(null), archive, isp, MainWindow.getInstance().getEnvProperties());
+ xai.setUser(MainWindow.getInstance().getConnectedUser());
+ MainWindow.XemeliosArchiveImporterWorker worker = new MainWindow.XemeliosArchiveImporterWorker(xai);
+ worker.execute();
+ } catch(Exception ex) {
+ throw new ServiceException(ex);
+ }
+ }
+
+ @Override
+ public void importFiles(List<ImportContent> filesToImport) throws Exception {
+ for(ImportContent ic:filesToImport) {
+ importFile(ic.getFile(), ic.getDocumentId());
+ }
+ }
+
+ @Override
+ public XemeliosProperties getApplicationProperties() {
+ return new XemeliosPropertiesImpl(MainWindow.getInstance().getEnvProperties());
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.xhtmlviewer;
+
+/**
+ *
+ * @author chm
+ */
+public class LocalException extends Exception {
+ private static final long serialVersionUID = 1L;
+ public LocalException(String msg) { super(msg); }
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.xhtmlviewer;
+
+/**
+ *
+ * @author chm
+ */
+public class NotFoundException extends Exception {
+
+ /** Creates a new instance of NotFoundException */
+ public NotFoundException(String msg) {
+ super(msg);
+ }
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.xhtmlviewer;
+
+/**
+ *
+ * @author chm
+ * @deprecated
+ */
+public class ScaleChangeEvent {
+
+ private XemeliosXhtmlPanel pane;
+ private double scale;
+ public ScaleChangeEvent(XemeliosXhtmlPanel pane, double scale) {
+ super();
+ this.pane=pane;
+ this.scale=scale;
+ }
+ public XemeliosXhtmlPanel getComponent() { return pane; }
+ public double getScale() { return scale; }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.ui.xhtmlviewer;
+
+/**
+ *
+ * @author chm
+ * @deprecated
+ */
+public interface ScaleChangeListener {
+ public void scaleChanged(ScaleChangeEvent evt);
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui.xhtmlviewer;
+
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import java.awt.Component;
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLDecoder;
+import java.util.ArrayList;
+import java.util.Hashtable;
+import java.util.LinkedHashMap;
+import java.util.Map.Entry;
+import java.util.Properties;
+import java.util.StringTokenizer;
+
+import javax.swing.JFrame;
+import javax.swing.JOptionPane;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathConstants;
+import javax.xml.xpath.XPathFactory;
+
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpMethod;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.log4j.Logger;
+import org.w3c.dom.Document;
+import org.xhtmlrenderer.swing.NaiveUserAgent;
+
+import fr.gouv.finances.cp.utils.StartUrl;
+import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
+import fr.gouv.finances.cp.xemelios.ui.CodeViewer;
+import fr.gouv.finances.cp.xemelios.ui.HtmlViewer;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.cp.xemelios.ui.UpdatableToolbar;
+import fr.gouv.finances.dgfip.utils.Dest;
+import fr.gouv.finances.dgfip.utils.HostUtils;
+import fr.gouv.finances.dgfip.utils.IoUtils;
+import fr.gouv.finances.dgfip.utils.NavigationContext;
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
+import fr.gouv.finances.dgfip.utils.xml.transform.CustomURIResolver;
+import fr.gouv.finances.dgfip.xemelios.auth.UnauthorizedException;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
+import fr.gouv.finances.dgfip.xemelios.common.NetAccess;
+import fr.gouv.finances.dgfip.xemelios.common.PJRef;
+import fr.gouv.finances.dgfip.xemelios.common.ToolException;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.EtatModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.Loader;
+import fr.gouv.finances.dgfip.xemelios.common.config.customLinks.CustomLinkParameters;
+import fr.gouv.finances.dgfip.xemelios.common.config.customLinks.CustomLinkResolver;
+import fr.gouv.finances.dgfip.xemelios.common.config.customLinks.UnresolvedException;
+import fr.gouv.finances.dgfip.xemelios.data.DataAccessException;
+import fr.gouv.finances.dgfip.xemelios.data.DataConfigurationException;
+import fr.gouv.finances.dgfip.xemelios.data.DataImpl;
+import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
+import fr.gouv.finances.dgfip.xemelios.utils.FileUtils;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamSource;
+
+/**
+ *
+ * @author chm
+ */
+public class XemeliosUserAgent extends NaiveUserAgent {
+
+ private static final Logger logger = Logger.getLogger(XemeliosUserAgent.class);
+ public static final int MAX_VISITED_URIS = 100;
+ LinkedHashMap<String, Object> visitedUris;
+ private int index = -1;
+ private ArrayList<String> history = new ArrayList<String>();
+ private String baseUrl;
+ private UpdatableToolbar toolbar;
+ protected NavigationContext nc;
+// private MainWindow mainWindow;
+// private HtmlViewer viewer;
+ private Component viewer;
+ private XPathFactory xpf;
+ private XemeliosUser user;
+ private PropertiesExpansion envProperties;
+
+ public XemeliosUserAgent(MainWindow mw, Component viewer, UpdatableToolbar toolbar, XemeliosUser user) {
+ this(viewer, mw.getEnvProperties(), user);
+// this.mainWindow = mw;
+ this.toolbar = toolbar;
+ xpf = FactoryProvider.getXPathFactory();
+ }
+
+ public XemeliosUserAgent(Component viewer, PropertiesExpansion envProperties, XemeliosUser user) {
+ super();
+ this.user = user;
+ this.viewer = viewer;
+ this.envProperties = envProperties;
+ visitedUris = new LinkedHashMap<String, Object>(16, 0.75f, true) {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ protected boolean removeEldestEntry(Entry<String, Object> eldest) {
+ return size() == MAX_VISITED_URIS;
+ }
+ };
+ }
+
+ @Override
+ public boolean isVisited(String uri) {
+ return visitedUris.containsKey(uri);
+ }
+
+ @Override
+ public String resolveURI(String uri) {
+ if (uri == null) {
+ return getBaseURL();
+ }
+ if (uri.startsWith("xemelios:")) {
+ logger.debug("resolving " + uri);
+ String shortUri;
+ String anchor = null;
+ int indexSharp = uri.indexOf("#");
+ if (indexSharp > 0) {
+ shortUri = uri.substring(0, indexSharp);
+ anchor = uri.substring(indexSharp + 1);
+ } else {
+ shortUri = uri;
+ }
+ Dest dest = (Dest) visitedUris.get(shortUri);
+ if (dest == null || "true".equals(envProperties.getProperty("xemelios.navigation.force-reload"))) {
+ dest = calculateQuery(shortUri);
+ visitedUris.put(shortUri, dest);
+ }
+ if (dest == null && nc != null) {
+ dest = nc.getLastDestination();
+ }
+ if (dest != null && dest.url != null) {
+ if (dest.toExternal) {
+ try {
+ logger.debug("openning " + dest.url.toExternalForm());
+ StartUrl.startUrl(dest.url.toExternalForm());
+ } catch (ToolException toEx) {
+ }
+ return null;
+ } else {
+ String ret = dest.url.toExternalForm();
+ if (indexSharp > 0) {
+ ret += uri.substring(indexSharp);
+ }
+ //if(anchor==null) return ret;
+ //else return ret+"#"+anchor;
+ return ret;
+ }
+ }
+ }
+ return super.resolveURI(uri);
+ }
+
+ @Override
+ @SuppressWarnings("empty-statement")
+ public void setBaseURL(String url) {
+ super.setBaseURL(url);
+ if (baseUrl != null && baseUrl.startsWith("error:")) {
+ baseUrl = null;
+ }
+ baseUrl = url;
+ if (baseUrl == null) {
+ return;
+ }
+ if (index >= 0) {
+ String historic = (String) history.get(index);
+ if (historic.equals(baseUrl)) {
+ toolbar.updateToolbarButtons();
+ return;//moved in history
+ }
+ }
+ index++;
+ for (int i = index; i < history.size(); history.remove(i));
+ history.add(index, baseUrl);
+ toolbar.updateToolbarButtons();
+ toolbar.setBaseUrl(url);
+ }
+
+ public String getForward() {
+ index++;
+ return (String) history.get(index);
+ }
+
+ public String getBack() {
+ index--;
+ return (String) history.get(index);
+ }
+
+ public boolean hasForward() {
+ return (index + 1 < history.size() && index >= 0);
+ }
+
+ public boolean hasBack() {
+ return (index > 0);
+ }
+
+ @Override
+ protected InputStream resolveAndOpenStream(String uri) {
+ InputStream retValue = null;
+ try {
+ URL url = new URL(uri);
+ if ("http".equals(url.getProtocol())) {
+ HttpClient client = NetAccess.getHttpClient(envProperties);
+ HttpMethod meth = new GetMethod(uri);
+ int retCode = client.executeMethod(meth);
+ if (retCode <= 300) {
+ retValue = meth.getResponseBodyAsStream();
+ }
+ }
+ } catch (MalformedURLException muEx) {
+ // TODO
+ } catch (DataConfigurationException dcEx) {
+ // TODO
+ } catch (IOException ioEx) {
+ // TODO
+ }
+ if (retValue == null) {
+ retValue = super.resolveAndOpenStream(uri);
+ }
+ return retValue;
+ }
+
+ public Dest calculateQuery(String query) {
+ NavigationContext ctx = null;
+ if (nc == null) {
+ ctx = new NavigationContext();
+ } else {
+ ctx = nc.clone();
+ }
+ Hashtable<String, Object> params = new Hashtable<String, Object>();
+ params.put(HtmlViewer.PARAM_DESTINATION, HtmlViewer.VALUE_DESTINATION_INTERNAL);
+ String servlet = null;
+ String sTmp = query;
+ int start = query.indexOf('?');
+ if (start >= 0) {
+ servlet = query.substring(query.indexOf("/") + 1, start);
+ sTmp = query.substring(start + 1);
+ }
+ if ("query".equals(servlet)) {
+ Properties additionalParameters = new Properties();
+ StringTokenizer st = new StringTokenizer(sTmp, "&");
+ while (st.hasMoreTokens()) {
+ String data = st.nextToken();
+ logger.debug("parsing " + data);
+ int pos = data.indexOf('=');
+ if (pos > 0) {
+ String paramName = data.substring(0, pos);
+ String paramValue = null;
+ try {
+ //String sTmp = data.substring(pos+1);
+ paramValue = URLDecoder.decode(data.substring(pos + 1), "UTF-8");
+ logger.debug(paramName + "=" + paramValue);
+ } catch (Throwable t) {
+ logger.error("decoding", t);
+ }
+ if ("docId".equals(paramName)) {
+ ctx.setDocId(paramValue);
+ } else if ("etatId".equals(paramName)) {
+ ctx.setEtatId(paramValue);
+ } else if ("elementId".equals(paramName)) {
+ ctx.setElementId(paramValue);
+ } else if ("collectivite".equals(paramName)) {
+ ctx.setCollectivite(paramValue);
+ } else if ("budget".equals(paramName)) {
+ ctx.setBudget(paramValue);
+ } else if ("sp1".equals(paramName)) {
+ ctx.setSp1(paramValue);
+ } else if ("sp2".equals(paramName)) {
+ ctx.setSp2(paramValue);
+ } else if ("path".equals(paramName)) {
+ ctx.setPath(paramValue);
+ } else {
+ try {
+ if (URLDecoder.decode(paramName, "UTF-8").startsWith("xsl:param")) {
+ // logger.debug("xsl:param -> "+paramValue);
+ int virg = paramValue.indexOf(',');
+ String pName = paramValue.substring(1, virg);
+ String pValue = paramValue.substring(virg + 1, paramValue.length() - 1);
+
+ int pos2 = pValue.indexOf('%'); // interprétation des xsl:param avec valeurs de formulaires
+ while (pos2 >= 0) {
+ int closing = pValue.indexOf('%', pos2 + 1);
+ if (closing < 0) {
+ throw new RuntimeException("a '%' is not closed! : " + pValue);
+ }
+ String paramNam = pValue.substring(pos2 + 1, closing);
+ if (additionalParameters.containsKey(paramNam)) {
+ String begin = pValue.substring(0, pos2);
+ String end = pValue.substring(closing + 1);
+ String replacedValue = additionalParameters.getProperty(paramNam);
+ pValue = begin.concat(replacedValue).concat(end);
+ pos2 = pValue.indexOf('%', pos2);
+ } else {
+ pos2 = pValue.indexOf('%', closing);
+ }
+ }
+ params.put(pName, pValue);
+ logger.debug("Adding " + pName + "=" + pValue);
+ } else {
+ additionalParameters.setProperty(paramName, paramValue);
+ }
+ logger.debug(paramName + "=" + paramValue);
+ } catch (Throwable t) {
+ logger.error("decoding", t);
+ }
+ }
+ }
+ }
+ ctx.configXPath(additionalParameters);
+ return generateDestContext(ctx, params, HtmlViewer.INTERNAL_DESTINATION);
+ } else if ("resource".equals(servlet)) {
+// logger.debug("looking for resource "+sTmp);
+ Dest ret = null;
+ try {
+ File resourceDir = new File(envProperties.getProperty("xemelios.resources.location"));
+ File res = new File(resourceDir, sTmp);
+ ret = new Dest(res.toURI().toURL(), false);
+ } catch (Throwable t) {
+ }
+ return ret;
+ } else if ("attachment".equals(servlet)) {
+ StringTokenizer st = new StringTokenizer(sTmp, "&");
+ String pjCollectivite = ctx.getCollectivite();
+ String pjId = null;
+ while (st.hasMoreTokens()) {
+ String data = st.nextToken();
+ logger.debug("parsing " + data);
+ int pos = data.indexOf('=');
+ if (pos > 0) {
+ String paramName = data.substring(0, pos);
+ String paramValue = null;
+ try {
+ //String sTmp = data.substring(pos+1);
+ paramValue = URLDecoder.decode(data.substring(pos + 1), "UTF-8");
+ } catch (Throwable t) {
+ }
+ if ("collectivite".equals(paramName)) {
+ pjCollectivite = paramValue;
+ } else if ("pjId".equals(paramName)) {
+ pjId = paramValue;
+ }
+ }
+ }
+ if (pjId != null && pjCollectivite != null) {
+ try {
+ DataImpl impl = DataLayerManager.getImplementation();
+ PJRef pjRef = impl.getPjByUniqueId(new Pair(pjCollectivite, ""), pjId, user);
+ if (pjRef != null) {
+ String fileName = pjRef.getFileName();
+ fileName = fileName.replaceAll(" ", "_");
+ File tmpFile = File.createTempFile("tmp-", fileName, FileUtils.getTempDir());
+ logger.debug("saving PJ to " + tmpFile.getAbsolutePath());
+ FileOutputStream fos = new FileOutputStream(tmpFile);
+ fos.write(pjRef.getData());
+ fos.flush();
+ fos.close();
+ return new Dest(tmpFile.toURL(), true);
+ } else {
+ JOptionPane.showMessageDialog(viewer, "Pièce non trouvée", "Erreur", JOptionPane.ERROR_MESSAGE);
+ }
+ } catch (UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(viewer, ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (DataConfigurationException dcEx) {
+ logger.error("while getting PJ:", dcEx);
+ } catch (DataAccessException daEx) {
+ logger.error("while getting PJ:", daEx);
+ } catch (IOException ioEx) {
+ logger.error("while getting PJ:", ioEx);
+ }
+ }
+ } else if ("customLink".equals(servlet)) {
+ CustomLinkParameters clp = new CustomLinkParameters();
+ Properties additionalParameters = new Properties();
+
+ StringTokenizer st = new StringTokenizer(sTmp, "&");
+ while (st.hasMoreTokens()) {
+ String data = st.nextToken();
+ logger.debug("parsing " + data);
+ int pos = data.indexOf('=');
+ if (pos > 0) {
+ String paramName = data.substring(0, pos);
+ String paramValue = null;
+ try {
+ //String sTmp = data.substring(pos+1);
+ paramValue = URLDecoder.decode(data.substring(pos + 1), "UTF-8");
+ logger.debug(paramName + "=" + paramValue);
+ } catch (Throwable t) {
+ logger.error("decoding", t);
+ }
+ if ("srcDocId".equals(paramName)) {
+ clp.setSrcDocId(paramValue);
+ } else if ("srcEtatId".equals(paramName)) {
+ clp.setSrcEtatId(paramValue);
+ } else if ("srcElementId".equals(paramName)) {
+ clp.setSrcElementId(paramValue);
+ } else if ("srcCollectivite".equals(paramName)) {
+ clp.setSrcCollectivite(paramValue);
+ } else if ("srcBudget".equals(paramName)) {
+ clp.setSrcBudget(paramValue);
+ } else {
+ try {
+ if (paramName.startsWith("xsl:param")) {
+ // logger.debug("xsl:param -> "+paramValue);
+ int virg = paramValue.indexOf(',');
+ String pName = paramValue.substring(1, virg);
+ String pValue = paramValue.substring(virg + 1, paramValue.length() - 1);
+
+ int pos2 = pValue.indexOf('%'); // interprétation des xsl:param avec valeurs de formulaires
+ while (pos2 >= 0) {
+ int closing = pValue.indexOf('%', pos2 + 1);
+ if (closing < 0) {
+ throw new RuntimeException("a '%' is not closed! : " + pValue);
+ }
+ String paramNam = pValue.substring(pos2 + 1, closing);
+ if (additionalParameters.containsKey(paramNam)) {
+ String begin = pValue.substring(0, pos2);
+ String end = pValue.substring(closing + 1);
+ String replacedValue = additionalParameters.getProperty(paramNam);
+ pValue = begin.concat(replacedValue).concat(end);
+ pos2 = pValue.indexOf('%', pos2);
+ } else {
+ pos2 = pValue.indexOf('%', closing);
+ }
+ }
+ additionalParameters.put(pName, pValue);
+ logger.debug("Adding additionalParameters " + pName + "=" + pValue);
+ } else {
+ //additionalParameters.setProperty(paramName, paramValue);
+ if (additionalParameters.getProperty(paramName) == null && clp.getParameter(paramName) == null) {
+ clp.addParameter(paramName, paramValue);
+ }
+ }
+ logger.debug(paramName + "=" + paramValue);
+ } catch (Throwable t) {
+ logger.error("decoding", t);
+ }
+ }
+ }
+ }
+ try {
+ String clrClassName = clp.getCustomLinkResolverName(Loader.getDocumentsInfos(null));
+ Class clazz = Class.forName(clrClassName);
+ CustomLinkResolver clr = (CustomLinkResolver) clazz.newInstance();
+ clr.setXslParameters(additionalParameters);
+ return generateDestContext(ctx, clr, clp, HtmlViewer.INTERNAL_DESTINATION);
+ } catch (Exception ex) {
+ logger.error("calculateQuery(" + query + ") / customLink", ex);
+ }
+ } else if ("showSrc".equals(servlet)) {
+ String hostName = null;
+ String url = null;
+ StringTokenizer st = new StringTokenizer(sTmp, "&");
+ while (st.hasMoreTokens()) {
+ String data = st.nextToken();
+ int pos = data.indexOf('=');
+ if (pos > 0) {
+ String paramName = data.substring(0, pos);
+ String paramValue = null;
+ try {
+ paramValue = URLDecoder.decode(data.substring(pos + 1), "UTF-8");
+ } catch (Throwable t) {
+ logger.error("decoding", t);
+ }
+ if ("host".equals(paramName)) {
+ hostName = paramValue;
+ } else if ("url".equals(paramName)) {
+ url = paramValue;
+ }
+ }
+ }
+ if (hostName != null && url != null) {
+ if (hostName.equals(HostUtils.getHostName())) {
+ try {
+ File f = new File(url);
+ if (!f.exists()) {
+ throw new Exception(f.getAbsolutePath());
+ }
+ CodeViewer cv = new CodeViewer(f.toURI().toURL());
+ } catch (Exception ex) {
+ JOptionPane.showMessageDialog(viewer, "Le fichier est introuvable:\n" + ex.getMessage(), "Information", JOptionPane.WARNING_MESSAGE);
+ }
+ } else {
+ JOptionPane.showMessageDialog(viewer, "Ce fichier n'a pas été analysé sur cet ordinateur, il n'est pas possible de le visualiser", "Information", JOptionPane.WARNING_MESSAGE);
+ }
+ }
+ }
+ return null;
+ }
+
+ public Dest generateDestContext(NavigationContext ctx, CustomLinkResolver resolver, CustomLinkParameters parameters, boolean toExternalDest) {
+ Dest ret = null;
+ try {
+ File tmp = File.createTempFile("xemelios-data-", ".html", FileUtils.getTempDir());
+ ctx = resolver.resolve(parameters, new StreamResult(tmp), ctx, user);
+ URL url = tmp.toURI().toURL();
+ nc = ctx;
+ ret = new Dest(url, toExternalDest);
+ } catch (UnresolvedException unEx) {
+ JOptionPane.showMessageDialog(viewer, unEx.getMessage(), "Erreur", JOptionPane.INFORMATION_MESSAGE);
+ } catch (Exception ex) {
+ logger.error("generateDestContext(NavigationContext,CustomLinkResolver,CustomLinkParameters,boolean)", ex);
+ }
+ return ret;
+ }
+
+ public Dest generateDestContext(NavigationContext ctx, Hashtable<String, Object> params, final boolean toExternalDest) {
+// logger.debug(ctx);
+ boolean noException = false;
+ Dest ret = null;
+ try {
+ DocumentModel dm = Loader.getDocumentsInfos(null).getDocumentById(ctx.getDocId());
+ if (dm == null) {
+ throw new LocalException("doc " + ctx.getDocId() + " inconnu");
+ }
+ EtatModel em = dm.getEtatById(ctx.getEtatId());
+ if (em == null) {
+ throw new LocalException("etat " + ctx.getEtatId() + " inconnu");
+ }
+ ElementModel element = (ctx.getElementId() != null ? em.getElementById(ctx.getElementId()) : em.getBrowsableElement());
+ if (ctx.getCollectivite() == null) {
+ throw new LocalException("collectivite non definie");
+ }
+ if (ctx.getBudget() == null) {
+ throw new LocalException("budget non defini");
+ }
+ DataImpl impl = DataLayerManager.getImplementation();
+ String docId = null;
+ if (ctx.getPath() == null) {
+ ArrayList<String> documents = impl.getDocumentListFromSpecialKeys(element, ctx.getCollectivite(), ctx.getBudget(), ctx.getSp1(), ctx.getSp2(), ctx.getSp3(), user);
+ if (documents.size() == 0) {
+ JOptionPane.showMessageDialog(viewer, "Le document est introuvable", "", JOptionPane.WARNING_MESSAGE);
+ noException = true;
+ } else if (documents.size() > 1 && !em.isMultiPage()) {
+ JOptionPane.showMessageDialog(viewer, "Plusieurs documents répondant à ces critères ont été trouvés.", "Erreur", JOptionPane.ERROR_MESSAGE);
+ noException = true;
+ } else {
+ docId = documents.get(0);
+ }
+ } else {
+ if (ctx.getElementId() == null) {
+ ctx.setElementId(element.getId());
+ }
+ if (ctx.getPath() != null && ctx.getPath().startsWith("[")) {
+ ctx.setPath(element.getPath().getFormattedPath() + ctx.getPath());
+ }
+ ArrayList<String> documents = impl.getDocumentListFromXPath(element, ctx.getCollectivite(), ctx.getBudget(), ctx.getSp1(), ctx.getSp2(), ctx.getSp3(), ctx.getPath(), user);
+ if (documents.size() == 0) {
+ JOptionPane.showMessageDialog(viewer, "Le document est introuvable", "", JOptionPane.WARNING_MESSAGE);
+ noException = true;
+ } else if (documents.size() > 1 && !em.isMultiPage()) {
+ JOptionPane.showMessageDialog(viewer, "Plusieurs documents répondant à ces critères ont été trouvés.", "Erreur", JOptionPane.ERROR_MESSAGE);
+ noException = true;
+ } else {
+ docId = documents.get(0);
+ }
+ }
+ if (docId != null) {
+ Document doc = impl.getDocumentAsDom(em, new Pair(ctx.getCollectivite(), null), new Pair(ctx.getBudget(), null), docId, user);
+ File f = null;
+ f = new File(new File(new File(System.getProperty("user.home")), "xemelios/documents-def-ovrrd"), element.getXslt());
+ if (!f.exists()) {
+ f = new File(em.getParent().getBaseDirectory(), element.getXslt());
+ }
+// DEBUG
+// FileChannel fChIn = new FileInputStream(f).getChannel();
+// WritableByteChannel wbc = Channels.newChannel(System.out);
+// fChIn.transferTo(0, fChIn.size(), wbc);
+// fChIn.close(); wbc.close();
+// END DEBUG
+ InputStream is = IoUtils.getInputStream(f.getPath());
+// Hashtable<String, Object> parameters = new Hashtable<String, Object>();
+ TransformerFactory tFactory = FactoryProvider.getTransformerFactory();
+ tFactory.setURIResolver(new CustomURIResolver(tFactory.getURIResolver(), f.getParentFile().toURI().toURL().toExternalForm()));
+ Transformer t = tFactory.newTransformer(new StreamSource(is));
+// parameters.putAll(params);
+ if (params.get(HtmlViewer.PARAM_DESTINATION) == null) {
+ t.setParameter(HtmlViewer.PARAM_DESTINATION, em.useExternalBrowser() ? HtmlViewer.VALUE_DESTINATION_EXTERNAL : HtmlViewer.VALUE_DESTINATION_INTERNAL);
+ }
+ for(String key:params.keySet()) {
+ t.setParameter(key, params.get(key));
+ }
+
+ // on passe la nomenclature en parametre
+ // on recupere l'ID de la nomenclature
+ XPath xp = xpf.newXPath();
+ xp.setNamespaceContext(dm.getNamespaces());
+ String idRepository = null;
+ if (dm.getReferenceNomenclaturePath() != null && dm.getReferenceNomenclaturePath().getCodePath() != null) {
+ idRepository = (String) xp.evaluate(dm.getReferenceNomenclaturePath().getCodePath().getPath(), doc.getDocumentElement(), XPathConstants.STRING);
+ }
+ if (idRepository != null && idRepository.length() == 0) {
+ idRepository = null;
+ }
+ Document repository = impl.getRepositoryAsDom(dm, new Pair(ctx.getCollectivite(), null), idRepository, user);
+ if (repository != null) {
+ t.setParameter("repository", repository);
+ }
+ // on passe la config
+ t.setParameter("config", Loader.getDocumentsInfos(null).getSmallDOM());
+ t.setParameter("collectivite", ctx.getCollectivite());
+ t.setParameter("budget", ctx.getBudget());
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ t.transform(new DOMSource(doc), new StreamResult(baos));
+ ByteArrayInputStream htmlStream = new ByteArrayInputStream(baos.toByteArray());
+ File tmp = File.createTempFile("xemelios-data-", ".html", FileUtils.getTempDir());
+ BufferedInputStream bis = new BufferedInputStream(htmlStream);
+ BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmp));
+ byte[] buff = new byte[1024];
+ int lengthRead = bis.read(buff);
+ while (lengthRead > 0) {
+ bos.write(buff, 0, lengthRead);
+ lengthRead = bis.read(buff);
+ }
+ bos.flush();
+ bos.close();
+ URL url = tmp.toURI().toURL();
+ nc = ctx;
+ ret = new Dest(url, toExternalDest);
+ } else if (!noException) {
+ throw new NotFoundException("Pas de " + element.getTitre() + " trouvé(e)");
+ }
+ } catch (LocalException lEx) {
+ JOptionPane.showMessageDialog(viewer, lEx.getMessage(), "Erreur de paramétrage", JOptionPane.ERROR_MESSAGE);
+ } catch (Exception ex) {
+ Component comp2 = viewer;
+ while (comp2 != null && !(comp2 instanceof JFrame)) {
+ comp2 = comp2.getParent();
+ }
+ if (comp2 != null) {
+ new DisplayExceptionDlg((JFrame) comp2, ex);
+ } else {
+ new DisplayExceptionDlg((JFrame) null, ex);
+ }
+ }
+ if (ret != null) {
+ ctx.setLastDestination(ret);
+ }
+ return ret;
+ }
+
+ public Component getViewer() {
+ return viewer;
+ }
+
+ public void setToolbar(UpdatableToolbar toolbar) {
+ this.toolbar = toolbar;
+ }
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.ui.xhtmlviewer;
+
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import java.awt.Font;
+import java.awt.FontFormatException;
+import java.io.IOException;
+import javax.swing.JFrame;
+import javax.swing.JInternalFrame;
+import org.apache.log4j.Logger;
+
+import org.w3c.dom.Document;
+
+import org.xhtmlrenderer.css.style.derived.RectPropertySet;
+import org.xhtmlrenderer.event.DocumentListener;
+import org.xhtmlrenderer.extend.UserAgentCallback;
+import org.xhtmlrenderer.render.Box;
+import org.xhtmlrenderer.swing.ScalableXHTMLPanel;
+
+
+import java.awt.Point;
+
+import java.io.File;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+
+/**
+ *
+ * @author chm
+ */
+public class XemeliosXhtmlPanel extends ScalableXHTMLPanel {
+ private static final Logger logger = Logger.getLogger(XemeliosXhtmlPanel.class);
+ private JInternalFrame iframe;
+ private JFrame frame;
+
+
+ public XemeliosXhtmlPanel(UserAgentCallback uac, JInternalFrame frame) {
+ super(uac);
+ this.iframe=frame;
+ addDocumentListener();
+ addMonospacedFont();
+ }
+ public XemeliosXhtmlPanel(UserAgentCallback uac, JFrame frame) {
+ super(uac);
+ this.frame=frame;
+ addDocumentListener();
+ addMonospacedFont();
+ }
+ /**
+ * Sets the new current document, where the new document
+ * is located relative, e.g using a relative URL.
+ *
+ * @param filename The new document to load
+ */
+ @Override
+ protected void setDocumentRelative(String filename) {
+ String url = getSharedContext().getUac().resolveURI(filename);
+ if(url!=null) {
+ if (isAnchorInCurrentDocument(filename)) {
+ String id = getAnchorId(filename);
+ Box box = getSharedContext().getBoxById(id);
+ if (box != null) {
+ Point pt;
+ if (box.getStyle().isInline()) {
+ pt = new Point(box.getAbsX(), box.getAbsY());
+ } else {
+ RectPropertySet margin = box.getMargin(getLayoutContext());
+ pt = new Point(
+ box.getAbsX() + (int)margin.left(),
+ box.getAbsY() + (int)margin.top());
+ }
+ scrollTo(pt);
+ return;
+ }
+ }
+ Document dom = loadDocument(url);
+ setDocument(dom, url);
+ }
+ }
+ private boolean isAnchorInCurrentDocument(String str) {
+ return str.charAt(0) == '#';
+ }
+
+ private String getAnchorId(String url) {
+ return url.substring(1, url.length());
+ }
+
+ private void addMonospacedFont() {
+ try {
+ if(
+ MainWindow.instance!=null &&
+ !MainWindow.instance.getEnvProperties().replace("${" + Constants.SYS_PROP_RESOURCES_LOCATION + "}").equals("${"+Constants.SYS_PROP_RESOURCES_LOCATION+"}")) {
+ Font font = Font.createFont(Font.TRUETYPE_FONT, new File(new File(MainWindow.instance.getEnvProperties().replace("${" + Constants.SYS_PROP_RESOURCES_LOCATION + "}")), "couri.ttf"));
+ getSharedContext().setFontMapping("monospace", font);
+ }
+ } catch (FontFormatException ex) {
+ logger.error(ex);
+ } catch (IOException ex) {
+ logger.error(ex);
+ } catch(NullPointerException npEx) {
+ logger.error(npEx);
+ }
+ }
+ private void addDocumentListener() {
+ addDocumentListener(new DocumentListener() {
+ @Override
+ public void documentLoaded() {
+ String sUrl = getSharedContext().getUac().getBaseURL();
+ try {
+ URL __url = new URL(sUrl);
+ String url = __url.toExternalForm();
+ int sharpPos = url.indexOf('#');
+
+ if (sharpPos >= 0) {
+ String anchorName = url.substring(sharpPos + 1);
+ Box box =
+ getSharedContext().getBoxById(anchorName);
+
+ if (box != null) {
+ Point pt;
+
+ if (box.getStyle().isInline()) {
+ pt = new Point(box.getAbsX(), box.getAbsY());
+ } else {
+ RectPropertySet margin =
+ box.getMargin(getLayoutContext());
+
+ pt = new Point(
+ box.getAbsX() + (int) margin.left(),
+ box.getAbsY() + (int) margin.top());
+ }
+
+ // TODO
+ Point transPoint = new Point((int) (pt.getX()/ getScale()), (int) (pt.getY()/ getScale()));
+ //Point transPoint = new Point((int) (pt.getX()/ 1.0), (int) (pt.getY()/ 1.0));
+
+ scrollTo(transPoint);
+ repaint();
+
+ return;
+ } else {
+ logger.error("anchor not found: " + anchorName);
+ }
+ }
+ displayTitle(getDocumentTitle());
+ } catch(MalformedURLException muEx) {
+ // ignorable
+ }
+ }
+ @Override
+ public void onLayoutException(Throwable throwable) {
+ logger.error("layout error: ",throwable);
+ }
+ @Override
+ public void onRenderException(Throwable throwable) {
+ logger.error("render error: ",throwable);
+ }
+ @Override
+ public void documentStarted() {}
+ });
+ }
+
+ public JInternalFrame getFrame() {
+ return iframe;
+ }
+ protected void displayTitle(String title) {
+ if(title!=null) {
+ if(frame!=null) frame.setTitle(title);
+ if(iframe!=null) iframe.setTitle(title);
+ }
+ }
+
+ //~--- set methods --------------------------------------------------------
+
+ @Override
+ public void setDocument(File file) throws Exception {
+ setScalePolicy(SCALE_POLICY_FIT_WIDTH);
+ super.setDocument(file);
+ }
+
+ @Override
+ public void setDocument(Document doc, String url) {
+ setScalePolicy(SCALE_POLICY_FIT_WIDTH);
+ super.setDocument(doc, url);
+ }
+
+ @Override
+ public void setDocument(InputStream stream, String url) throws Exception {
+ setScalePolicy(SCALE_POLICY_FIT_WIDTH);
+ super.setDocument(stream, url);
+ }
+}
+
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.updater;
+
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+
+/**
+ * This class is the parent of all configurator started after an update.
+ * @author chm
+ *
+ */
+public abstract class AbstractConfigurator {
+ protected PropertiesExpansion props;
+ protected MainWindow mw;
+ private AbstractConfigurator previousConfigurator = null;
+
+ public AbstractConfigurator() {
+ super();
+ }
+ /**
+ * Called by updater to set parameters.
+ * @param props
+ */
+ public void setProperties(PropertiesExpansion props) {
+ this.props=props;
+ }
+ /**
+ * Called by updater to set the main window
+ * @param mw
+ */
+ public void setMainWindow(MainWindow mw) {
+ this.mw=mw;
+ }
+ public void setPreviousConfigurator(AbstractConfigurator prev) {
+ if(prev==null) return;
+ this.previousConfigurator = prev;
+ prev.setMainWindow(mw);
+ prev.setProperties(props);
+ }
+ public void doConfigure() throws Exception {
+ run();
+ if(previousConfigurator!=null) previousConfigurator.doConfigure();
+ }
+ /**
+ * Called by updater to perform configuration.
+ * Implementors just have to implement this method.
+ * @throws Exception
+ */
+ public abstract void run() throws Exception;
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.3" maxVersion="1.7" type="org.netbeans.modules.form.forminfo.JDialogFormInfo">
+ <Properties>
+ <Property name="defaultCloseOperation" type="int" value="2"/>
+ <Property name="title" type="java.lang.String" value="Mises à jour"/>
+ </Properties>
+ <SyntheticProperties>
+ <SyntheticProperty name="formSizePolicy" type="int" value="1"/>
+ </SyntheticProperties>
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" attributes="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="jLabel1" pref="376" max="32767" attributes="0"/>
+ </Group>
+ <Component id="jSeparator1" alignment="0" pref="388" max="32767" attributes="0"/>
+ <Group type="102" alignment="1" attributes="0">
+ <EmptySpace pref="291" max="32767" attributes="0"/>
+ <Component id="pbDetail" min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ <Group type="102" alignment="1" attributes="0">
+ <EmptySpace pref="173" max="32767" attributes="0"/>
+ <Component id="pbYes" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="pbNo" min="-2" max="-2" attributes="0"/>
+ <EmptySpace min="-2" pref="162" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="jLabel1" min="-2" max="-2" attributes="0"/>
+ <EmptySpace pref="27" max="32767" attributes="0"/>
+ <Component id="pbDetail" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="jSeparator1" min="-2" pref="10" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="pbYes" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="pbNo" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Component class="javax.swing.JLabel" name="jLabel1">
+ <Properties>
+ <Property name="text" type="java.lang.String" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
+ <Connection code="MSG" type="code"/>
+ </Property>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JSeparator" name="jSeparator1">
+ </Component>
+ <Component class="javax.swing.JButton" name="pbYes">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Oui"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbYesActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="pbNo">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Non"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbNoActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="pbDetail">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Voir le détail..."/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbDetailActionPerformed"/>
+ </Events>
+ </Component>
+ </SubComponents>
+</Form>
--- /dev/null
+/*
+ * Copyright
+ * 2011 axYus - http://www.axyus.com
+ * 2011 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS_NB.
+ *
+ * XEMELIOS_NB 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 2 of the License, or
+ * (at your option) any later version.
+ *
+ * XEMELIOS_NB 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 Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with XEMELIOS_NB; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+
+/*
+ * DlgConfirmDownloadUpdate.java
+ *
+ * Created on 8 avr. 2011, 12:51:23
+ */
+
+package fr.gouv.finances.cp.xemelios.updater;
+
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import java.awt.event.ActionEvent;
+import java.awt.event.KeyEvent;
+import javax.swing.AbstractAction;
+import javax.swing.JComponent;
+import javax.swing.JOptionPane;
+import javax.swing.JRootPane;
+import javax.swing.KeyStroke;
+
+/**
+ *
+ * @author cmarchand
+ */
+public class DlgConfirmDownloadUpdate extends javax.swing.JDialog {
+ public static final transient String MSG = "<html>Des mises à jour sont disponibles.<br><br>Voulez-vous les installer ?</html>";
+ private UpdateUtil uu;
+ private int retValue = JOptionPane.NO_OPTION;
+
+ /** Creates new form DlgConfirmDownloadUpdate */
+ public DlgConfirmDownloadUpdate(java.awt.Frame parent, UpdateUtil uu) {
+ super(parent, true);
+ this.uu = uu;
+ initComponents();
+ setLocationRelativeTo(parent);
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ @SuppressWarnings("unchecked")
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ jLabel1 = new javax.swing.JLabel();
+ jSeparator1 = new javax.swing.JSeparator();
+ pbYes = new javax.swing.JButton();
+ pbNo = new javax.swing.JButton();
+ pbDetail = new javax.swing.JButton();
+
+ setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+ setTitle("Mises à jour");
+
+ jLabel1.setText(MSG);
+
+ pbYes.setText("Oui");
+ pbYes.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbYesActionPerformed(evt);
+ }
+ });
+
+ pbNo.setText("Non");
+ pbNo.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbNoActionPerformed(evt);
+ }
+ });
+
+ pbDetail.setText("Voir le détail...");
+ pbDetail.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbDetailActionPerformed(evt);
+ }
+ });
+
+ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE))
+ .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 388, Short.MAX_VALUE)
+ .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
+ .addContainerGap(291, Short.MAX_VALUE)
+ .addComponent(pbDetail)))
+ .addContainerGap())
+ .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
+ .addContainerGap(173, Short.MAX_VALUE)
+ .addComponent(pbYes)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(pbNo)
+ .addGap(162, 162, 162))
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(jLabel1)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE)
+ .addComponent(pbDetail)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(pbYes)
+ .addComponent(pbNo))
+ .addContainerGap())
+ );
+
+ pack();
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void pbYesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbYesActionPerformed
+ retValue = JOptionPane.YES_OPTION;
+ setVisible(false);
+ }//GEN-LAST:event_pbYesActionPerformed
+
+ private void pbNoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbNoActionPerformed
+ retValue = JOptionPane.NO_OPTION;
+ setVisible(false);
+ }//GEN-LAST:event_pbNoActionPerformed
+
+ private void pbDetailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbDetailActionPerformed
+ String source = MainWindow.getInstance().getEnvProperties().getProperty(Constants.SYS_PROP_MAJ_CONFIG);
+ DlgShowUpdateDetail dsud = new DlgShowUpdateDetail(this, uu, source);
+ dsud.setVisible(true);
+ }//GEN-LAST:event_pbDetailActionPerformed
+
+ public int run() {
+ setVisible(true);
+ return retValue;
+ }
+ @Override
+ protected JRootPane createRootPane() {
+ JRootPane rp = new JRootPane();
+ KeyStroke ksEscape = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0);
+ AbstractAction escapeAction = new AbstractAction("Non") {
+ private static final long serialVersionUID = 1L;
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ pbNo.doClick();
+ }
+ };
+ rp.registerKeyboardAction(escapeAction,"CANCEL",ksEscape,JComponent.WHEN_IN_FOCUSED_WINDOW);
+ KeyStroke ksEnter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0);
+ AbstractAction enterAction = new AbstractAction("Oui") {
+ private static final long serialVersionUID = 1L;
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ pbYes.doClick();
+ }
+ };
+ rp.registerKeyboardAction(enterAction,"ENTER",ksEnter,JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
+ }
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JLabel jLabel1;
+ private javax.swing.JSeparator jSeparator1;
+ private javax.swing.JButton pbDetail;
+ private javax.swing.JButton pbNo;
+ private javax.swing.JButton pbYes;
+ // End of variables declaration//GEN-END:variables
+
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.3" maxVersion="1.7" type="org.netbeans.modules.form.forminfo.JDialogFormInfo">
+ <Properties>
+ <Property name="defaultCloseOperation" type="int" value="2"/>
+ </Properties>
+ <SyntheticProperties>
+ <SyntheticProperty name="formSizePolicy" type="int" value="1"/>
+ </SyntheticProperties>
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" attributes="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <Component id="jLabel1" min="-2" max="-2" attributes="0"/>
+ <EmptySpace pref="429" max="32767" attributes="0"/>
+ </Group>
+ <Component id="jLabel2" alignment="0" min="-2" max="-2" attributes="0"/>
+ <Component id="jScrollPane2" alignment="0" pref="576" max="32767" attributes="2"/>
+ <Component id="jScrollPane1" alignment="0" pref="576" max="32767" attributes="2"/>
+ </Group>
+ <EmptySpace min="-2" pref="11" max="-2" attributes="0"/>
+ </Group>
+ <Group type="102" alignment="1" attributes="0">
+ <Component id="pbClose" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Component id="jLabel1" min="-2" max="-2" attributes="0"/>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Component id="jScrollPane1" min="-2" pref="102" max="-2" attributes="0"/>
+ <EmptySpace min="-2" pref="3" max="-2" attributes="0"/>
+ <Component id="jLabel2" min="-2" max="-2" attributes="0"/>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Component id="jScrollPane2" pref="102" max="32767" attributes="0"/>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Component id="pbClose" min="-2" max="-2" attributes="0"/>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Component class="javax.swing.JButton" name="pbClose">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Fermer"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbCloseActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JLabel" name="jLabel1">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Composants à installer"/>
+ </Properties>
+ </Component>
+ <Container class="javax.swing.JScrollPane" name="jScrollPane1">
+ <AuxValues>
+ <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
+ </AuxValues>
+
+ <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
+ <SubComponents>
+ <Component class="org.jdesktop.swingx.JXTable" name="tblCompsToDownload">
+ <Properties>
+ <Property name="model" type="javax.swing.table.TableModel" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
+ <Connection code="downloadModel" type="code"/>
+ </Property>
+ </Properties>
+ <AuxValues>
+ <AuxValue name="JavaCodeGenerator_CreateCodeCustom" type="java.lang.String" value="new MyTable()"/>
+ </AuxValues>
+ </Component>
+ </SubComponents>
+ </Container>
+ <Component class="javax.swing.JLabel" name="jLabel2">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Composants à mettre à jour"/>
+ </Properties>
+ </Component>
+ <Container class="javax.swing.JScrollPane" name="jScrollPane2">
+ <AuxValues>
+ <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
+ </AuxValues>
+
+ <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
+ <SubComponents>
+ <Component class="org.jdesktop.swingx.JXTable" name="tblCompsToUpdate">
+ <Properties>
+ <Property name="model" type="javax.swing.table.TableModel" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
+ <Connection code="updateModel" type="code"/>
+ </Property>
+ </Properties>
+ <AuxValues>
+ <AuxValue name="JavaCodeGenerator_CreateCodeCustom" type="java.lang.String" value="new MyTable()"/>
+ </AuxValues>
+ </Component>
+ </SubComponents>
+ </Container>
+ </SubComponents>
+</Form>
--- /dev/null
+/*
+ * Copyright
+ * 2011 axYus - http://www.axyus.com
+ * 2011 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS_NB.
+ *
+ * XEMELIOS_NB 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 2 of the License, or
+ * (at your option) any later version.
+ *
+ * XEMELIOS_NB 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 Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with XEMELIOS_NB; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+
+package fr.gouv.finances.cp.xemelios.updater;
+
+import fr.gouv.finances.cp.utils.StartUrl;
+import fr.gouv.finances.cp.xemelios.updater.profils.ComponentModel;
+import java.awt.Component;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.KeyEvent;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.TreeSet;
+import javax.swing.AbstractAction;
+import javax.swing.Action;
+import javax.swing.DefaultCellEditor;
+import javax.swing.JComponent;
+import javax.swing.JDialog;
+import javax.swing.JRootPane;
+import javax.swing.JTable;
+import javax.swing.JTextField;
+import javax.swing.KeyStroke;
+import javax.swing.table.AbstractTableModel;
+import javax.swing.table.DefaultTableCellRenderer;
+import javax.swing.table.DefaultTableModel;
+import javax.swing.table.TableCellRenderer;
+import javax.swing.table.TableModel;
+import org.apache.log4j.Logger;
+import org.jdesktop.swingx.JXHyperlink;
+import org.jdesktop.swingx.JXTable;
+
+/**
+ *
+ * @author cmarchand
+ */
+public class DlgShowUpdateDetail extends javax.swing.JDialog {
+ public static final transient String VERSION_NOTE_LIB = "Notes de version";
+ private static final Logger logger = Logger.getLogger(DlgShowUpdateDetail.class);
+ private UpdateUtil uu;
+ private String updateSource;
+ private DownloadModel downloadModel;
+ private UpdateModel updateModel;
+ private TreeSet<String> visitedUrls = new TreeSet<String>();
+
+ /** Creates new form DlgShowUpdateDetail */
+ public DlgShowUpdateDetail(JDialog parent, UpdateUtil uu, String updateSource) {
+ super(parent, true);
+ this.uu = uu;
+ this.updateSource = updateSource;
+ // download table
+ ArrayList<ComponentModel> downloadList = new ArrayList<ComponentModel>();
+ for(ComponentModel cm:uu.getComponentsToAdd()) {
+ if(!uu.getComponentsToBeUpdated().contains(cm)) {
+ downloadList.add(cm);
+ }
+ }
+ downloadModel = new DownloadModel(downloadList);
+ // update table
+ ArrayList<ComponentModel> updateList = new ArrayList<ComponentModel>();
+ updateList.addAll(uu.getComponentsToBeUpdated());
+ updateModel = new UpdateModel(updateList);
+ initComponents();
+ setLocationRelativeTo(parent);
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ @SuppressWarnings("unchecked")
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ pbClose = new javax.swing.JButton();
+ jLabel1 = new javax.swing.JLabel();
+ jScrollPane1 = new javax.swing.JScrollPane();
+ tblCompsToDownload = new MyTable();
+ jLabel2 = new javax.swing.JLabel();
+ jScrollPane2 = new javax.swing.JScrollPane();
+ tblCompsToUpdate = new MyTable();
+
+ setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+
+ pbClose.setText("Fermer");
+ pbClose.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbCloseActionPerformed(evt);
+ }
+ });
+
+ jLabel1.setText("Composants à installer");
+
+ tblCompsToDownload.setModel(downloadModel);
+ jScrollPane1.setViewportView(tblCompsToDownload);
+
+ jLabel2.setText("Composants à mettre à jour");
+
+ tblCompsToUpdate.setModel(updateModel);
+ jScrollPane2.setViewportView(tblCompsToUpdate);
+
+ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addComponent(jLabel1)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 429, Short.MAX_VALUE))
+ .addComponent(jLabel2)
+ .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 576, Short.MAX_VALUE)
+ .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 576, Short.MAX_VALUE))
+ .addGap(11, 11, 11))
+ .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
+ .addComponent(pbClose)
+ .addContainerGap())))
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(jLabel1)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addGap(3, 3, 3)
+ .addComponent(jLabel2)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 102, Short.MAX_VALUE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(pbClose)
+ .addContainerGap())
+ );
+
+ pack();
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void pbCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbCloseActionPerformed
+ setVisible(false);
+ }//GEN-LAST:event_pbCloseActionPerformed
+
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JLabel jLabel1;
+ private javax.swing.JLabel jLabel2;
+ private javax.swing.JScrollPane jScrollPane1;
+ private javax.swing.JScrollPane jScrollPane2;
+ private javax.swing.JButton pbClose;
+ private org.jdesktop.swingx.JXTable tblCompsToDownload;
+ private org.jdesktop.swingx.JXTable tblCompsToUpdate;
+ // End of variables declaration//GEN-END:variables
+
+ private class DownloadModel extends DefaultTableModel {
+ private List<ComponentModel> comps;
+ public DownloadModel(List<ComponentModel> comps) {
+ super();
+ this.comps = comps;
+ }
+
+ @Override
+ public int getRowCount() {
+ if(comps==null) return 0;
+ return comps.size();
+ }
+
+ @Override
+ public int getColumnCount() {
+ return 2;
+ }
+
+ @Override
+ public String getColumnName(int column) {
+ switch(column) {
+ case 0: return "Composant";
+ default: return "Informations";
+ }
+ }
+
+ @Override
+ public Object getValueAt(int row, int column) {
+ ComponentModel cm = comps.get(row);
+ switch(column) {
+ case 0: return cm.getDescription();
+ default: {
+ try {
+ return new URL(cm.getUri()+"/"+updateSource+"/update.xml");
+ } catch(Exception ex) {
+ return null;
+ }
+ }
+ }
+ }
+
+ @Override
+ public Class<?> getColumnClass(int columnIndex) {
+ switch(columnIndex) {
+ case 0: return String.class;
+ default: return URL.class;
+ }
+ }
+
+ @Override
+ public boolean isCellEditable(int row, int column) {
+ return column==1;
+ }
+
+ @Override
+ public void setValueAt(Object aValue, int row, int column) { }
+
+ }
+
+ private class UpdateModel extends AbstractTableModel {
+ private List<ComponentModel> comps;
+ public UpdateModel(List<ComponentModel> comps) {
+ super();
+ this.comps = comps;
+ }
+
+ @Override
+ public int getRowCount() {
+ return comps.size();
+ }
+
+ @Override
+ public int getColumnCount() {
+ return 3;
+ }
+
+ @Override
+ public String getColumnName(int column) {
+ switch(column) {
+ case 0: return "Composant";
+ case 1: return "Version";
+ default: return "Informations";
+ }
+ }
+
+ @Override
+ public Class<?> getColumnClass(int columnIndex) {
+ switch(columnIndex) {
+ case 2: return URL.class;
+ default: return String.class;
+ }
+ }
+
+ @Override
+ public Object getValueAt(int row, int column) {
+ ComponentModel cm = comps.get(row);
+ switch(column) {
+ case 0: return cm.getDescription();
+ case 1: return cm.getVersion();
+ default: try {
+ return new URL(cm.getUri()+"/"+updateSource+"/update.xml");
+ } catch(Exception ex) {
+ return null;
+ }
+ }
+ }
+
+ @Override
+ public boolean isCellEditable(int row, int column) {
+ return column==2;
+ }
+ @Override
+ public void setValueAt(Object aValue, int row, int column) { }
+
+ }
+ @Override
+ protected JRootPane createRootPane() {
+ JRootPane rp = new JRootPane();
+ KeyStroke ksEscape = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0);
+ AbstractAction escapeAction = new AbstractAction("Fermer") {
+ private static final long serialVersionUID = 1L;
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ pbClose.doClick();
+ }
+ };
+ rp.registerKeyboardAction(escapeAction,"CANCEL",ksEscape,JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
+ }
+
+ private class MyTable extends JXTable {
+ UrlCellRenderer urlRenderer = new UrlCellRenderer();
+ UrlCellEditor urlEditor = new UrlCellEditor();
+
+ public MyTable() {
+ super();
+ setDefaultEditor(URL.class, urlEditor);
+ }
+
+ @Override
+ public TableCellRenderer getCellRenderer(int row, int column) {
+ TableModel tm = getModel();
+ Class clazz = tm.getColumnClass(convertColumnIndexToModel(column));
+ if(String.class.equals(clazz))
+ return super.getCellRenderer(row, column);
+ else {
+ return urlRenderer;
+ }
+ }
+
+// @Override
+// public TableCellEditor getCellEditor(int row, int column) {
+// if(URL.class.equals(getModel().getColumnClass(convertColumnIndexToModel(column)))) {
+// return urlEditor;
+// } else return super.getCellEditor(row, column);
+// }
+
+
+ }
+ private class UrlCellRenderer extends DefaultTableCellRenderer {
+ private ReleaseNoteHL hl = new ReleaseNoteHL();
+
+ @Override
+ public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
+ hl.setURL((URL)value);
+ hl.setBackground(isSelected || hasFocus ? table.getSelectionBackground() : table.getBackground());
+ return hl;
+ }
+
+ }
+ private class ReleaseNoteHL extends JXHyperlink {
+ private URL url;
+ private String externalForm;
+ public ReleaseNoteHL() {
+ super();
+ setText(VERSION_NOTE_LIB);
+ addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ try {
+ visitedUrls.add(externalForm);
+ StartUrl.startUrl(externalForm);
+ } catch(Exception ex) {
+ logger.error("starting "+url,ex);
+ }
+ }
+ });
+ }
+ public ReleaseNoteHL(Action act) {
+ super(act);
+ }
+ protected void setURL(URL url) {
+ this.url = url;
+ externalForm = url!=null ? url.toExternalForm() : null;
+ }
+
+ @Override
+ protected boolean isAutoSetClicked() {
+ return true;
+ }
+
+ @Override
+ public boolean isClicked() {
+ boolean ret = externalForm==null ? false : visitedUrls.contains(externalForm);
+// logger.debug(externalForm+(ret?" visited":" not visited"));
+ return ret;
+ }
+
+
+ }
+ private class UrlCellEditor extends DefaultCellEditor {
+ private ReleaseNoteHL hl;
+ public UrlCellEditor() {
+ super(new JTextField());
+ AbstractAction action = new AbstractAction(VERSION_NOTE_LIB) {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ fireEditingStopped();
+ try {
+ StartUrl.startUrl(hl.url.toExternalForm());
+ } catch(Exception ex) {
+ logger.error("while opening "+hl.url,ex);
+ }
+ }
+ };
+ hl = new ReleaseNoteHL(action);
+ }
+
+ @Override
+ public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
+ hl.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
+ hl.setURL((URL)value);
+ return hl;
+ }
+
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2010 axYus - www.axyus.com
+ * 2010 JP.Tessier - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.updater;
+
+import java.util.HashMap;
+import java.util.Vector;
+
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+
+public class GeneratorHelpIndex {
+
+ public GeneratorHelpIndex() {
+ super();
+ }
+
+ /**
+ *
+ * @return
+ */
+ public static String generateIndex(){
+ StringBuilder sb = new StringBuilder("");
+ sb.append("<html><head><title>Guide utilisateur XéMéLios</title>");
+ sb.append("<style type=\"text/css\">");
+ sb.append("p.header { text-align: center; margin: 0 10 5 10; font-family: Helvetica; font-size: 18px; font-weight: bold; }");
+ sb.append("p { text-align: justify; text-justify: auto;}");
+ sb.append("p.p1 { margin-left: 10px; }");
+ sb.append("p.p2 { margin-left: 20px; }");
+ sb.append("p.p3 { margin-left: 30px; }");
+ sb.append("p.center { text-align: center; }");
+ sb.append("h1 { font-family: Helvetica; font-size: 22px; font-weight: bold; }");
+ sb.append("h2 { margin-left: 10px; font-family: Helvetica; font-size: 18px; font-weight: bold; }");
+ sb.append("h3 { margin-left: 20px; font-family: Helvetica; font-size: 16px; font-weight: bold; }");
+ sb.append("table { background-color: black; cell-spacing: 1px; }");
+ sb.append("td { background-color: white; }");
+ sb.append("td.center { text-align:center; }");
+ sb.append("th { background-color: #9F9F9F; text-align: left; }");
+ sb.append("</style>");
+ sb.append("</head>");
+ sb.append("<body>");
+ sb.append("<p class=\"header\"><img src=\"../images/logo_xemelios.png\" alt=\"logo\"/></p>");
+ sb.append("<p class=\"header\">Spécificités des documents</p>");
+ sb.append("\n<p class=\"p1\">A ce jour, XéMèLios sait exploiter les documents suivants :");
+ sb.append("\n<ul>");
+ // reprendre cela pour lister seulement ceux accessibles (display-in-menu-if
+ HashMap<String, Vector<String>> hashDocIds = new HashMap<String, Vector<String>>();
+ for (DocumentModel dm:MainWindow.getInstance().getDocModels().getDocuments()) {
+ if(dm.getExtendedDocId()!=null){
+ Vector<String> v = null;
+ if(hashDocIds.containsKey(dm.getExtendedDocId())){
+ v = hashDocIds.get(dm.getExtendedDocId());
+ v.add(dm.getId());
+ } else {
+ v = new Vector<String>();
+ v.add(dm.getId());
+ hashDocIds.put(dm.getId(), v);
+ }
+ } else {
+ Vector<String> v = new Vector<String>();
+ hashDocIds.put(dm.getId(), v);
+ }
+ }
+ for (DocumentModel dm:MainWindow.getInstance().getDocModels().getDocuments()) {
+// if(dm.getExtendedDocId() == null && hashDocIds.containsKey(dm.getId()) && hashDocIds.get(dm.getId()).size() > 0){
+// sb.append(dm.getTitre()).append(" :");
+// sb.append("\n<ul>");
+// for(String id:hashDocIds.get(dm.getId())) {
+// sb.append("<li type=\"square\"><a href=\""+id+".html\">"+MainWindow.getInstance().getDocModels().getDocumentById(id).getTitre()+"</a></li>");
+// }
+// sb.append("\n</ul>");
+// } else {
+ if(dm.getDisplayInMenuIf()==null || "true".equals(MainWindow.getInstance().getEnvProperties().getProperty(dm.getDisplayInMenuIf())))
+ sb.append("<li type=\"square\"><a href=\""+dm.getId()+".html\">"+dm.getTitre()+"</a></li>");
+// }
+ }
+ sb.append("</ul></p></body></html>");
+ return sb.toString();
+ }
+
+ public void main(String[] args){
+ System.out.println(generateIndex());
+ }
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.3" maxVersion="1.7" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
+ <Properties>
+ <Property name="toolTipText" type="java.lang.String" value="Téléchargement des mises à jour en cours..."/>
+ <Property name="maximumSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
+ <Dimension value="[154, 220]"/>
+ </Property>
+ <Property name="preferredSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
+ <Dimension value="[100, 24]"/>
+ </Property>
+ </Properties>
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <Component id="lblWait" min="-2" max="-2" attributes="0"/>
+ <EmptySpace min="-2" pref="2" max="-2" attributes="0"/>
+ <Component id="pgr" pref="131" max="32767" attributes="0"/>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="103" groupAlignment="2" attributes="0">
+ <Component id="pgr" alignment="2" min="-2" pref="16" max="-2" attributes="2"/>
+ <Component id="lblWait" alignment="2" max="32767" attributes="1"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Component class="javax.swing.JLabel" name="lblWait">
+ <Properties>
+ <Property name="icon" type="javax.swing.Icon" editor="org.netbeans.modules.form.editors2.IconEditor">
+ <Image iconType="3" name="/fr/gouv/finances/cp/xemelios/updater/ui/res/wait-01.png"/>
+ </Property>
+ <Property name="toolTipText" type="java.lang.String" value="Téléchargement des mises à jour en cours..."/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JProgressBar" name="pgr">
+ <Properties>
+ <Property name="stringPainted" type="boolean" value="true"/>
+ </Properties>
+ </Component>
+ </SubComponents>
+</Form>
--- /dev/null
+/*
+ * Copyright
+ * 2011 axYus - http://www.axyus.com
+ * 2011 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS_NB.
+ *
+ * XEMELIOS_NB 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 2 of the License, or
+ * (at your option) any later version.
+ *
+ * XEMELIOS_NB 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 Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with XEMELIOS_NB; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+package fr.gouv.finances.cp.xemelios.updater;
+
+import fr.gouv.finances.cp.utils.ui.IhmFactory;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+import java.util.Timer;
+import java.util.TimerTask;
+import javax.swing.Icon;
+import javax.swing.ImageIcon;
+import javax.swing.SwingUtilities;
+import org.apache.log4j.Logger;
+
+/**
+ * Cette classe permet d'indiquer à l'utilisateur la progression de l'avancement
+ * du téléchargement des mises à jour. Ce composant est affiché dans la StatusBar
+ * de la MainWindow.
+ * Elle reçoit les PropertyChangeEvent de
+ * <ul><li><tt>progress</tt> : pour indiquer le pourcentage d'avancement. <tt>int</tt>
+ * >=0 et <=100</li>
+ * <li><tt>init</tt> : pour indiquer le début d'un téléchargement de mise à jour</li>
+ * <li><tt>close</tt> : pour indiquer la fin du téléchargement d'une mise à jour</li></ul>
+ * @author cmarchand
+ */
+public class PnlUpdaterProgress extends javax.swing.JPanel implements PropertyChangeListener {
+ private static final transient Logger logger = Logger.getLogger(PnlUpdaterProgress.class);
+ Icon[] waiters = new Icon[12];
+ private Timer timer;
+ private ProgressPainter currentPainter;
+
+ /** Creates new form PnlUpdaterProgress */
+ public PnlUpdaterProgress() {
+ initIcons();
+ initComponents();
+ pgr.setIndeterminate(true);
+ pgr.setMaximum(100);
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ @SuppressWarnings("unchecked")
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ lblWait = new javax.swing.JLabel();
+ pgr = new javax.swing.JProgressBar();
+
+ setToolTipText("Téléchargement des mises à jour en cours...");
+ setMaximumSize(new java.awt.Dimension(154, 220));
+ setPreferredSize(new java.awt.Dimension(100, 24));
+
+ lblWait.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fr/gouv/finances/cp/xemelios/updater/ui/res/wait-01.png"))); // NOI18N
+ lblWait.setToolTipText("Téléchargement des mises à jour en cours...");
+
+ pgr.setStringPainted(true);
+
+ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
+ this.setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addComponent(lblWait)
+ .addGap(2, 2, 2)
+ .addComponent(pgr, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE)
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
+ .addComponent(pgr, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addComponent(lblWait, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ );
+ }// </editor-fold>//GEN-END:initComponents
+
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JLabel lblWait;
+ private javax.swing.JProgressBar pgr;
+ // End of variables declaration//GEN-END:variables
+
+ private void initIcons() {
+ String[] names = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"};
+ for(int i=0;i<12;i++) {
+ String name = names[i];
+ String resName = "fr/gouv/finances/cp/xemelios/updater/ui/res/wait-"+name+".png";
+ ImageIcon ii = IhmFactory.getIconFromResource(resName);
+ waiters[i] = ii;
+ }
+ }
+
+ @Override
+ public void setVisible(boolean aFlag) {
+ super.setVisible(aFlag);
+ if(aFlag) {
+ startUpdater();
+ } else {
+ stopUpdater();
+ }
+ }
+
+ private void startUpdater() {
+ if(timer==null) {
+ timer = new Timer();
+ }
+ if(currentPainter!=null) return;
+ currentPainter = new ProgressPainter();
+ timer.schedule(currentPainter, 0, 50);
+ }
+ private void stopUpdater() {
+ if(currentPainter==null) return;
+ currentPainter.cancel();
+ currentPainter = null;
+ }
+
+ @Override
+ public void propertyChange(PropertyChangeEvent evt) {
+ if(evt.getPropertyName().equals("progress")) {
+ int value = (Integer)evt.getNewValue();
+ pgr.setIndeterminate(false);
+ pgr.setValue(value);
+ } else if(evt.getPropertyName().equals("init")) {
+ pgr.setValue(0);
+ pgr.setIndeterminate(true);
+ setVisible(true);
+ } else if(evt.getPropertyName().equals("close")) {
+ setVisible(false);
+ }
+ }
+ // affiche la machin qui tourne
+ private class ProgressPainter extends TimerTask {
+ private long startTime;
+ private int lastIndex;
+
+ public ProgressPainter() {
+ super();
+ startTime = System.currentTimeMillis();
+ }
+
+ @Override
+ public void run() {
+ long delay = (System.currentTimeMillis() - startTime) / 100;
+ final int pos = (int) (delay % 12);
+ if(pos!=lastIndex) {
+ try {
+ SwingUtilities.invokeAndWait(new Runnable() {
+ @Override
+ public void run() {
+ lblWait.setIcon(waiters[pos]);
+ }
+ });
+ } catch(Exception ex) {}
+ lastIndex = pos;
+ }
+ }
+ }
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2010 axYus - www.axyus.com
+ * 2010 F.Nhieu - franck.nhieu@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.updater;
+
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.cp.xemelios.updater.profils.ComponentModel;
+import fr.gouv.finances.cp.xemelios.updater.installed.InstalledModel;
+import fr.gouv.finances.cp.xemelios.updater.profils.ProfilModel;
+import fr.gouv.finances.cp.xemelios.updater.profils.ProfilsModel;
+import fr.gouv.finances.cp.xemelios.updater.update.ComponentRefModel;
+import fr.gouv.finances.cp.xemelios.updater.update.ConfigurationModel;
+import fr.gouv.finances.cp.xemelios.updater.update.DeleteModel;
+import fr.gouv.finances.cp.xemelios.updater.update.FileListModel;
+import fr.gouv.finances.cp.xemelios.updater.update.FileModel;
+import fr.gouv.finances.cp.xemelios.updater.update.UpdateModel;
+import fr.gouv.finances.cp.xemelios.updater.update.VersionModel;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import fr.gouv.finances.dgfip.xemelios.common.NetAccess;
+import fr.gouv.finances.dgfip.xemelios.data.DataConfigurationException;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.text.DateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.zip.GZIPInputStream;
+import javax.swing.JOptionPane;
+import javax.swing.SwingWorker;
+import jonelo.jacksum.algorithm.AbstractChecksum;
+import jonelo.jacksum.algorithm.MD;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpMethod;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.log4j.Logger;
+
+/**
+ * Cette classe est chargée de télécharger les mises à jour
+ * et de préparer le script d'update qui sera exécuté au prochain
+ * démarrage par {@link fr.gouv.finances.cp.xemelios.updater.starter.Updater}
+ * Modifiée le 2011-02-14 pour piloter le composant d'avancement du téléchargement
+ * @author franck.nhieu
+ */
+public class UpdateUtil {
+
+ private static Logger logger = Logger.getLogger(UpdateUtil.class);
+ private final PropertiesExpansion applicationProperties;
+ private String installedFileLocation;
+ private ProfilsModel availableProfils;
+ private InstalledModel im;
+ private ArrayList<ProfilModel> profilsToAdd = new ArrayList<ProfilModel>();
+ private ArrayList<ProfilModel> profilsToDelete = new ArrayList<ProfilModel>();
+ private ArrayList<ComponentModel> componentsToAdd = new ArrayList<ComponentModel>();
+ private ArrayList<ComponentModel> componentsToBeEditable = new ArrayList<ComponentModel>();
+ private ArrayList<ComponentModel> componentsToCheckForUpdate = new ArrayList<ComponentModel>();
+ /* Cet array contient les ComponentModel a INSTALLER, avec LA VERSION a installer */
+ private ArrayList<ComponentModel> componentsToBeUpdated = new ArrayList<ComponentModel>();
+ private ArrayList<ComponentModel> componentsAllreadyScanned = new ArrayList<ComponentModel>();
+ private ArrayList<UpdateModel> updateModels = new ArrayList<UpdateModel>();
+ private String checkMethod = "";
+
+ public UpdateUtil(PropertiesExpansion applicationProperties) throws Exception {
+ this.applicationProperties = applicationProperties;
+ im = loadInstalled();
+ }
+
+ public String getCheckMethod() {
+ return checkMethod;
+ }
+
+ public void setCheckMethod(String checkMethod) {
+ this.checkMethod = checkMethod;
+ }
+
+ private InstalledModel loadInstalled() throws Exception {
+ installedFileLocation = applicationProperties.getProperty(Constants.SYS_PROP_INSTALLED_FILENAME);
+ return InstalledModel.readFromFile(installedFileLocation);
+ }
+
+ private void loadProfils() throws Exception {
+ String urlLocation = applicationProperties.getProperty(Constants.SYS_PROP_MAJ_PROFILS_URL);
+ availableProfils = ProfilsModel.loadModel(urlLocation);
+ }
+
+ public void checkForUpdates() throws Exception {
+ PnlUpdaterProgress pup = MainWindow.getInstance().getUpdaterProgress();
+ pup.firePropertyChange("init", 0, 1);
+ pup.setVisible(true);
+ if (availableProfils == null) {
+ loadProfils();
+ }
+ checkForStructuralUpdates();
+ checkForVersionUpdates();
+ dumpDebug();
+ pup.firePropertyChange("close", 0, 1);
+ pup.setVisible(false);
+ }
+
+ /**
+ * Installe un composant :
+ * Si le composant n'existe pas, alors on créé l'entrée <component...../>
+ * Si le composant existe, on MAJ l'entrée <component...../> correspondante, en modifiant la version et la description (et non pas le flag "editable")
+ * @param applicationProperties
+ * @param cm
+ * @throws Exception
+ */
+ public static void installComponent(PropertiesExpansion applicationProperties, ComponentModel cm) throws Exception {
+ String urlLocation = applicationProperties.getProperty(Constants.SYS_PROP_INSTALLED_FILENAME);
+ InstalledModel im = InstalledModel.readFromFile(urlLocation);
+ int idx = im.getComponentIdx(cm.getUri());
+ if (idx == InstalledModel.NOT_FOUND) {
+ logger.debug("adding component " + cm.getUri() + " (" + cm.getVersion() + ")");
+ im.addComponent(cm);
+ } else {
+ logger.debug("updating component " + cm.getUri() + " (" + cm.getVersion() + ")");
+ im.getComponents().get(idx).setVersion(cm.getVersion());
+ im.getComponents().get(idx).setDescription(cm.getDescription());
+ }
+ im.saveInstalledModel();
+ }
+
+ /**
+ * Vérifie s'il existe des mises à jour de version à effectuer.
+ * Le périmètre de vérification est composé des composants déjà installé ET
+ * Ã installer (componentsToAdd).
+ * Cette méthode constitue 1 ArrayList :
+ * - componentsToUpdated = la liste des composants a UPDATER,
+ * ATTENTION : étant donné que l'on va lire le fichier update.xml de chaque
+ * composant, les temps de traitement peuvent être assez long.
+ */
+ public void checkForVersionUpdates() throws Exception {
+ logger.debug("START");
+ for (ComponentModel cm : componentsToCheckForUpdate) {
+ try {
+ logger.debug("Check new release of : " + cm.getUri() + "(now:" + cm.getVersion() + ") " + cm.getDescription());
+ UpdateModel um = getUpdateModelByComponentUriFromCache(cm.getUri());
+ if (um == null) { // UpdateModel absent du cache
+ logger.debug("UpdateModel absent du CACHE, chargement de l'update.xml...");
+ um = UpdateModel.loadModel(cm, getUpdateTarget());
+ addUniqueUpdateModelInCache(um); // Ajout de l'UpdateModel dans le cache
+ }
+ if (cm.getVersion() == null || // pas de version (donc n'a jamais été installé),
+ cm.getVersion().isEmpty() || // pas de version (donc n'a jamais été installé),
+ compareReleases(um.getLast_version(), cm.getVersion()) > 0 // version supérieure disponible.
+ ) {
+ // Création d'un ComponentModel avec la nouvelle version & description qui provient de l'update.xml
+ logger.debug("+ UPGRADE : " + cm.getUri() + "/" + cm.getDescription() + " (now:" + cm.getVersion() + " < next:" + um.getLast_version() + ")");
+ ComponentModel ucm = new ComponentModel(cm.getUri(), um.getLast_version(), cm.getDescription(), cm.isEditable());
+ addUniqueComponentModel(componentsToBeUpdated, ucm);
+ }
+ } catch (Exception ex) {
+ logger.error(ex);
+ //throw ex;
+ }
+ }
+ logger.debug("END");
+ }
+
+ /**
+ * Renvoie la cible de la mise à jour : PROD, RECETTE, DEV
+ * Si pas définit dans les <tt>applicationProperties</t>, renvoie PROD
+ * @return
+ */
+ private String getUpdateTarget() {
+ String ret = applicationProperties.getProperty(Constants.SYS_PROP_MAJ_CONFIG);
+ if (ret == null) {
+ ret = Constants.MAJ_PROD;
+ }
+ return ret;
+ }
+
+ private ArrayList<ComponentModel> doAddComponentDependencies(ComponentModel cm) throws Exception {
+ ArrayList<ComponentModel> cms = new ArrayList<ComponentModel>();
+ logger.debug("check dependencies of : " + cm.getUri() + "(" + cm.getVersion() + ") " + cm.getDescription());
+ logger.debug(" Chargement de l'update.xml du composant : " + cm.getUri() + "(" + cm.getVersion() + ") " + cm.getDescription());
+ /* Tentative de chargement de l'UpdateModel dans le cache */
+ UpdateModel um = getUpdateModelByComponentUriFromCache(cm.getUri());
+ if (um == null) {
+ try {
+ um = UpdateModel.loadModel(cm, getUpdateTarget());
+ addUniqueUpdateModelInCache(um); // On met en "cache" l'update model de ce composant
+ } catch (Exception ex) {
+ addUniqueComponentModel(cms, cm); // on ajoute quand meme le composant pour le flagger comme traité pour éviter les redondances cyccliques
+ logger.debug(" Chargement d'update.xml impossible : " + ex.getMessage());
+ return cms;
+ }
+ }
+ /* on remplace (ou met pour les composants qui n'ont jamais été installé) la description du composant */
+ cm.setDescription(um.getDescription());
+ addUniqueComponentModel(cms, cm);
+ logger.debug(" Dernière version du composant : " + um.getLast_version());
+ int lastVersionIdx = um.getLastVersionModelIdx();
+ if (lastVersionIdx != UpdateModel.NOT_FOUND) {
+ logger.debug(" VersionModel (" + um.getVersions().get(lastVersionIdx).getVersion() + " du " + um.getVersions().get(lastVersionIdx).getDate() + ") trouvé");
+ logger.debug(" DEB Scan des component-ref... de " + cm.getUri());
+ for (ComponentRefModel crm : um.getVersions().get(lastVersionIdx).getRequires().getComponents()) {
+ ComponentModel cmm = new ComponentModel(crm.getUri());
+ logger.debug(" Scan du composant dépendant de " + cm.getUri() + " : " + cmm.getUri() + "...");
+ if (!component_exists(componentsAllreadyScanned, cm)) {
+ addUniqueComponentModel(componentsAllreadyScanned, cm);
+ ArrayList<ComponentModel> acm = doAddComponentDependencies(cmm);
+ logger.debug("============================ DUMP Array returned, size=" + acm.size());
+ for (ComponentModel ccc : acm) {
+ logger.debug(ccc.getUri());
+ }
+ logger.debug("============================ ");
+ addAllUniqueComponentModels(cms, acm);
+ } else {
+ logger.debug(" !!! dépendances déjà scannées.");
+ }
+ }
+ logger.debug(" FIN du scan des composants dépendants de " + cm.getUri());
+ }
+ logger.debug("FIN du Traitrement du composant : " + cm.getUri() + "(" + cm.getVersion() + ") " + cm.getDescription());
+ return cms;
+ }
+
+ private boolean component_exists(ArrayList<ComponentModel> components, ComponentModel cm) {
+ for (ComponentModel cmm : components) {
+ if (cmm.getUri().equalsIgnoreCase(cm.getUri())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Vérifie s'il existe des mises à jour structurelles à effectuer.
+ * Le périmètre de vérification est composé des profils (ajout, désactivation, modification, requis),
+ * des composants des profils (ajout dans un profil, suppression),
+ * Cette méthode constitue 4 ArrayList : componentsToAdd, componentsToBeEditable,
+ * profilsToAdd et profilsToDelete accéssibles par leur getters respectifs.
+ */
+ public void checkForStructuralUpdates() throws Exception {
+
+ // PHASE 0 :
+ // On scan les profils dispo pour vérifier s'il y a des profils
+ // obligatoires qui ne sont pas inscrit en local
+
+ for (ProfilModel apm : availableProfils.getProfils()) {
+ /*
+ * Profil Requis
+ * On ajoute ses composants
+ */
+ if (apm.isRequired()) {
+ if (im.getProfilIdx(apm.getId()) == InstalledModel.NOT_FOUND) {
+ logger.debug("ph0 : ajout du profil required et non abonné " + apm.getId() + "/" + apm.getDescription());
+ profilsToAdd.add(apm);
+ for (ComponentModel cm : apm.getComponents()) {
+ logger.debug("ph0 : ajout du composant du profil " + apm.getId() + " : " + cm.getUri() + "/" + cm.getDescription());
+ //componentsToAdd.add(cm);
+ addUniqueComponentModel(componentsToAdd, cm);
+ }
+ }
+ }
+ /*
+ * Profil désactivé
+ * On l'enlève des abonnements si présent
+ * On rend éditable ses composants à condition qu'ils ne soient
+ * pas utilisé dans un autre profil
+ */
+ if (apm.isDisabled()) {
+ logger.debug("ph0: profil désactivé : " + apm.getId() + "/" + apm.getDescription());
+ int ipidx = im.getProfilIdx(apm.getId());
+ if (ipidx != InstalledModel.NOT_FOUND) {
+ logger.debug("ph0: profil toujours abonné...");
+ for (ComponentModel acm : apm.getComponents()) {
+ ComponentModel icm = im.getComponent(acm.getUri());
+ if (icm != null) {
+ logger.debug("ph0: composant rendu éditable : " + icm.getUri() + "/" + icm.getDescription());
+ icm.setEditable(true);
+ //componentsToBeEditable.add(icm);
+ addUniqueComponentModel(componentsToBeEditable, icm);
+ }
+ }
+ profilsToDelete.add(apm);
+ //im.removeProfil(apm.getId());
+ }
+ }
+ }
+
+ // PHASE 1
+ // les profils existants dans les profils abonnés :
+ // on scan les composants de chacun des profils abonnés afin de
+ // vérifier que tous les composants sont bien présent en local
+ // => cela permet d'ajouter de nouveaux composants si le profil a
+ // évolué.
+
+ // Confection d'une liste des composants des profils disponibles
+ ArrayList<ComponentModel> acms = new ArrayList<ComponentModel>();
+
+ for (ProfilModel ipm : im.getProfils()) {
+ int idx = availableProfils.getIdxById(ipm.getId());
+ if (idx == InstalledModel.NOT_FOUND) {
+ continue;
+ }
+ ProfilModel apm = availableProfils.getProfils().get(idx);
+ for (ComponentModel acm : apm.getComponents()) {
+ //acms.add(acm); // utilisé pour le phase 2
+ addUniqueComponentModel(acms, acm);
+ if (im.getComponentIdx(acm.getUri()) == InstalledModel.NOT_FOUND) {
+ logger.debug("ph2 : ajout du composant du profil MAJ " + apm.getId() + " : " + acm.getUri() + "/" + acm.getDescription());
+ //componentsToAdd.add(acm);
+ addUniqueComponentModel(componentsToAdd, acm);
+ }
+ }
+ }
+
+ // PHASE 2
+ // les composants non éditables
+ // On scan tous les composants non éditables,
+ // Si un composant n'est pas retrouvé dans la liste des composants
+ // des profils disponibles auquel nous sommes abonnés,
+ // alors c'est que le composant n'est plus utilisé par ce profil
+ // => on rend ce composant editable afin de ne pas l'effacer et laisser
+ // le choix à l'utilisateur de le supprimer
+
+ for (ComponentModel icm : im.getComponents()) {
+ if (!icm.isEditable()) {
+ boolean bFound = false;
+ for (ComponentModel acm : acms) {
+ if (acm.getUri().equalsIgnoreCase(icm.getUri())) {
+ bFound = true;
+ break;
+ }
+ }
+ if (!bFound) {
+ icm.setEditable(true);
+ //componentsToBeEditable.add(icm);
+ addUniqueComponentModel(componentsToBeEditable, icm);
+ }
+ }
+ }
+
+
+ /*
+ * PHASE 3
+ * Clean des listes :
+ * - si add composant, alors check si compsant deja existant (=> toAdd.del(composant),
+ * - si editable composant, alors check si pas add composant (=> editable.del(composant)),
+ */
+
+ for (int i = 0; i < componentsToAdd.size(); i++) {
+ ComponentModel cm = im.getComponent(componentsToAdd.get(i).getUri());
+ if (cm != null) {
+ logger.debug("clean: del component tagged to be added, already existing in installed components list : " + cm.getUri() + "/" + cm.getDescription());
+ componentsToAdd.remove(i);
+ }
+ }
+ for (int i = 0; i < componentsToBeEditable.size(); i++) {
+ for (int j = 0; j < componentsToAdd.size(); j++) {
+ if (componentsToAdd.get(j).getUri().equalsIgnoreCase(componentsToBeEditable.get(i).getUri())) {
+ ComponentModel cm = componentsToBeEditable.get(i);
+ logger.debug("clean: del component tagged to be editabled, already tagged to be add : " + cm.getUri() + "/" + cm.getDescription());
+ componentsToBeEditable.remove(i);
+ }
+ }
+ }
+
+ /*
+ * Liste des composants pour lesquels il faut vérifier la version
+ * donc potentiellement updatables
+ */
+ //componentsToCheckForUpdate.addAll(im.getComponents());
+ addAllUniqueComponentModels(componentsToCheckForUpdate, im.getComponents());
+ //componentsToCheckForUpdate.addAll(componentsToAdd);
+ addAllUniqueComponentModels(componentsToCheckForUpdate, componentsToAdd);
+
+ /*
+ * Traitement des dépendances
+ * attention à la séquence et à l'utilisation de cmd et componentsToCheckForUpdate
+ * pour éviter une exception d'accès concurrent sur componentsToCheckForUpdate...
+ */
+ ArrayList<ComponentModel> cmd = new ArrayList<ComponentModel>();
+ for (ComponentModel cm : componentsToCheckForUpdate) {
+ ArrayList<ComponentModel> ccmd = doAddComponentDependencies(cm);
+ addAllUniqueComponentModels(cmd, ccmd);
+ }
+ logger.debug("FINAL ------------------------------------------- DUMP Array returned, size=" + cmd.size());
+ for (ComponentModel ccc : cmd) {
+ logger.debug(ccc.getUri());
+ }
+ logger.debug("FINAL ------------------------------------------- ");
+ addAllUniqueComponentModels(componentsToCheckForUpdate, cmd);
+
+ /*
+ * On ADD aussi les composants non installé qui découlent des dépendances
+ */
+
+ for (ComponentModel depcm : cmd) {
+ boolean bFound = false;
+ for (ComponentModel icm : im.getComponents()) {
+ if (icm.getUri().equalsIgnoreCase(depcm.getUri())) {
+ bFound = true;
+ break;
+ }
+ }
+ if (!bFound) {
+ addUniqueComponentModel(componentsToAdd, depcm);
+ }
+ }
+
+ /*
+ * A ce stade nous avons la liste des composants pour lesquels nous
+ * devons vérifier les versions
+ */
+ }
+
+ private void dumpDebug() {
+ logger.debug("Liste des profils à supprimer :");
+ for (ProfilModel pm : profilsToDelete) {
+ logger.debug("- " + pm.getId() + "/" + pm.getDescription());
+ }
+ logger.debug("Liste des profils à ajouter :");
+ for (ProfilModel pm : profilsToAdd) {
+ logger.debug("- " + pm.getId() + "/" + pm.getDescription());
+ }
+ logger.debug("Liste des composants à ajouter :");
+ for (ComponentModel cm : componentsToAdd) {
+ logger.debug("- " + cm.getUri() + "/" + cm.getDescription());
+ }
+ logger.debug("Liste des composants à rendre éditable (à éffacer) :");
+ for (ComponentModel cm : componentsToBeEditable) {
+ logger.debug("- " + cm.getUri() + "/" + cm.getDescription()+"/"+cm.getVersion());
+ }
+ logger.debug("Liste des composants à mettre à installer :");
+ for (ComponentModel cm : componentsToBeUpdated) {
+ logger.debug("- " + cm.getUri() + "/" + cm.getDescription());
+ }
+
+ logger.debug("UpdateNeeded returns " + (updateNeeded() ? "TRUE" : "FALSE"));
+ }
+
+ /**
+ * Effectue toutes les MAJ :
+ * Effectue les opérations de MAJ des composants,
+ * Enregistre le fichier installed.xml.
+ */
+ public void doUpdates() throws Exception {
+
+ Downloader dl = new Downloader(componentsToBeUpdated, updateModels);
+ dl.execute();
+ //saveInstalledModel();
+ }
+
+ public void saveInstalledModel() throws Exception {
+
+ /*
+ * Traitement des profils a ajouter et à effacer
+ */
+ for (ProfilModel pm : profilsToDelete) {
+ im.removeProfil(pm.getId());
+ }
+ for (ProfilModel pm : profilsToAdd) {
+ /*
+ * On ajoute seulement le TAG profil du profil
+ * dans le fichier installed.xml et non pas
+ * les composants qui sont attachés
+ */
+ im.addProfil(new ProfilModel(pm.getId(), pm.getDescription()));
+ }
+
+ /*
+ * Traitement des composants
+ */
+
+ /*
+ * Sera MAJ par le starter lors du traitemant de update-script.xem
+ */
+ /*
+ for (ComponentModel cm : componentsToAdd) {
+ try {
+ im.addComponent(cm);
+ } catch (Throwable t) {
+ }
+ }
+ */
+
+ for (ComponentModel cm : componentsToBeEditable) {
+ try {
+ im.getComponent(cm.getUri()).setEditable(true);
+ } catch (Throwable t) {
+ }
+ }
+
+ /*
+ * Sera MAJ par le starter lors du traitemant de update-script.xem
+ */
+ /*
+ for (ComponentModel cm : componentsToBeUpdated) {
+ try {
+ im.getComponent(cm.getUri()).setVersion(cm.getVersion());
+ } catch (Throwable t) {
+ }
+ }
+ */
+ im.saveInstalledModel();
+
+ }
+
+ private boolean addUniqueComponentModel(ArrayList<ComponentModel> ar, ComponentModel c) {
+ if (ar == null || c == null) {
+ return false;
+ }
+ for (int i = 0; i < ar.size(); i++) {
+ if (ar.get(i).getUri().equalsIgnoreCase(c.getUri())) {
+ return false;
+ }
+ }
+ ar.add(c);
+ return true;
+ }
+
+ private void addAllUniqueComponentModels(ArrayList<ComponentModel> ar, ArrayList<ComponentModel> ar_toadd) {
+ if (ar == null || ar_toadd == null) {
+ return;
+ }
+ for (int i = 0; i < ar_toadd.size(); i++) {
+ addUniqueComponentModel(ar, ar_toadd.get(i));
+ }
+ }
+
+ private boolean addUniqueUpdateModelInCache(UpdateModel c) {
+ if (c == null) {
+ return false;
+ }
+ if (c.getComponentUri() == null || c.getComponentUri().isEmpty()) {
+ return false;
+ }
+ for (UpdateModel um : updateModels) {
+ if (um.getComponentUri().equalsIgnoreCase(c.getComponentUri())) {
+ return false;
+ }
+ }
+ updateModels.add(c);
+ return true;
+ }
+
+ private UpdateModel getUpdateModelByComponentUriFromCache(String ComponentUri) {
+ if (ComponentUri == null || ComponentUri.isEmpty()) {
+ return null;
+ }
+ for (UpdateModel um : updateModels) {
+ if (ComponentUri.equalsIgnoreCase(um.getComponentUri())) {
+ return um;
+ }
+ }
+ return null;
+ }
+
+ /**
+ *
+ * @return
+ * Vérifie si des MAJ sont nécessaires
+ */
+ public boolean updateNeeded() {
+ return (!profilsToAdd.isEmpty()
+ || !profilsToDelete.isEmpty()
+ || !componentsToBeUpdated.isEmpty());
+
+// return (!componentsToAdd.isEmpty()
+// || !componentsToBeEditable.isEmpty()
+// || !profilsToAdd.isEmpty()
+// || !profilsToDelete.isEmpty()
+// || !componentsToBeUpdated.isEmpty());
+ }
+
+ /**
+ *
+ * @param r1
+ * @param r2
+ * @return
+ */
+ public static int compareReleases(String r1, String r2) {
+ String[] s1 = splitRelease(r1);
+ String[] s2 = splitRelease(r2);
+ int ret = 0;
+ for (int i = 0; i < Math.min(s1.length, s2.length); i++) {
+ float a = -1f, b = -1f;
+ try {
+ a = Integer.parseInt(s1[i]);
+ } catch (Throwable t) {
+ if (s1[i].endsWith("+")) {
+ // if there is a "+" in the release number, it is a non-official release,
+ // based on the previous build number. So the "real" number is the previous + 0.5
+ try {
+ a = Integer.parseInt(s1[i].substring(0, s1[i].length() - 1));
+ a += 0.5;
+ } catch (Throwable t2) {
+ }
+ }
+ }
+ try {
+ b = Integer.parseInt(s2[i]);
+ } catch (Throwable t) {
+ if (s2[i].endsWith("+")) {
+ // if there is a "+" in the release number, it is a non-official release,
+ // based on the previous build number. So the "real" number is the previous + 0.5
+ try {
+ b = Integer.parseInt(s2[i].substring(0, s2[i].length() - 1));
+ b += 0.5;
+ } catch (Throwable t2) {
+ }
+ }
+ }
+ if (a != -1f && b != -1f) {
+ if (a < b) {
+ ret = -1;
+ } else if (a == b) {
+ ret = 0;
+ } else {
+ ret = 1;
+ }
+ } else {
+ ret = s1[i].compareTo(s2[i]);
+ }
+ if (ret != 0) {
+ return ret;
+ }
+ }
+ if (s1.length > s2.length) {
+ ret = 1;
+ } else if (s1.length < s2.length) {
+ ret = -1;
+ }
+ return ret;
+ }
+
+ public ArrayList<ComponentModel> getComponentsToAdd() {
+ return componentsToAdd;
+ }
+
+ public ArrayList<ComponentModel> getComponentsToBeUpdated() {
+ return componentsToBeUpdated;
+ }
+
+ private static String[] splitRelease(String r) {
+ return r.split("\\.");
+ }
+
+ private File getLocalFileName(String filePath, String fileName) {
+ String ret = filePath;
+ int pos = ret.indexOf("${");
+ while (pos >= 0) {
+ String before = ret.substring(0, pos);
+ int end = ret.indexOf("}");
+ String after = ret.substring(end + 1);
+ String key = ret.substring(pos + 2, end);
+ ret = before + applicationProperties.getProperty(key) + after;
+ pos = ret.indexOf("${");
+ }
+ logger.debug("ret=" + ret);
+ File f = new File(new File(ret), fileName);
+ if (f.exists()) {
+ return f;
+ }
+ return null;
+ }
+
+ private String unescapePath(String path) {
+ return applicationProperties.replace(path);
+ }
+
+ public class Downloader extends SwingWorker<Boolean, Integer> {
+
+ private ArrayList<ComponentModel> ci;
+ private ArrayList<UpdateModel> ui;
+ protected String errorMsg = null;
+ protected Exception exception = null;
+
+ public Exception getException() {
+ return exception;
+ }
+
+ public String getErrorMessage() {
+ return errorMsg;
+ }
+
+ private Downloader(ArrayList<ComponentModel> ci, ArrayList<UpdateModel> ui) {
+ super();
+ this.ci = ci;
+ this.ui = ui;
+ }
+
+ private UpdateModel getUpdateModelFromComponentURI(String ComponentUri) {
+ for (UpdateModel um : ui) {
+ if (ComponentUri.equalsIgnoreCase(um.getComponentUri())) {
+ return um;
+ }
+ }
+ return null;
+ }
+
+ @Override
+ protected Boolean doInBackground() throws Exception {
+ logger.debug("in doInBackground");
+ boolean bRet = true;
+ addPropertyChangeListener(MainWindow.getInstance().getUpdaterProgress());
+ firePropertyChange("init", 0, 1);
+ try {
+ File tmpDir = new File(unescapePath("${xemelios.dir}/tmp-upd"));
+ logger.debug("tmpDir=" + tmpDir.getPath());
+ tmpDir.mkdirs();
+ StringBuilder sb = new StringBuilder();
+ HttpClient client = NetAccess.getHttpClient(MainWindow.getInstance().getEnvProperties());
+ // step 1: on compte le nombre de fichiers à traiter
+ int nbItemsToTreat = 0;
+ for (ComponentModel cm : ci) {
+ UpdateModel um = getUpdateModelFromComponentURI(cm.getUri());
+ if (um != null) {
+ VersionModel vm = um.getLastVersionModel();
+ FileListModel fl = vm.getFiles();
+ nbItemsToTreat += fl.getFiles().size();
+ nbItemsToTreat += fl.getDeletes().size();
+ nbItemsToTreat += vm.getConfigurators().size();
+ }
+ }
+ logger.debug(nbItemsToTreat+" items to run");
+ // step 2: on traite !
+ int itemsRun = 0;
+ int lastProgressValue = 0;
+ for (ComponentModel cm : ci) {
+ logger.debug("Installation du composant : " + cm.getUri() + " / " + cm.getDescription());
+ UpdateModel um = getUpdateModelFromComponentURI(cm.getUri());
+ logger.debug("UpdateModel utilisé : " + um.getLast_version() + " du " + um.getGenerate_date());
+ if (um != null) {
+ VersionModel vm = um.getLastVersionModel();
+ logger.debug("Version utilisée : " + vm.getVersion() + " du " + vm.getDate());
+ FileListModel fl = vm.getFiles();
+ String root = fl.getRoot();
+ logger.debug("root = " + root);
+ for (FileModel fm : fl.getFiles()) {
+ // On teste si le fichier existe déjà en local et s'il est identique, auquel cas on ne fait rien
+ logger.debug("File : dest=" + fm.getDest() + "/name=" + fm.getName() + "/serv_name=" + fm.getSource());
+ File localFile = getLocalFileName(fm.getDest(), fm.getName());
+ if (localFile != null) {
+ AbstractChecksum localChecksum = new MD("MD5");
+ FileInputStream fis = new FileInputStream(localFile);
+ byte[] buffer = new byte[1024];
+ int read = fis.read(buffer);
+ while (read > 0) {
+ localChecksum.update(buffer, 0, read);
+ read = fis.read(buffer);
+ }
+ fis.close();
+ if (localChecksum.getFormattedValue().equals(fm.getMd5())) {
+ logger.info("local " + fm.getName() + " is the same than remote one.");
+ continue;
+ }
+ }
+ String sUrl = root + "/" + fm.getSource();
+ URL url = new URL(sUrl);
+ AbstractChecksum checksum = new MD("MD5");
+ FileOutputStream fos;
+ File tmpFile = File.createTempFile("upd-", null, tmpDir);
+ fos = new FileOutputStream(tmpFile);
+ logger.info("downloading " + sUrl + " to " + tmpFile.getPath());
+ HttpMethod meth = new GetMethod(sUrl);
+ meth.addRequestHeader("Pragma", "no-cache");
+ int returnCode = client.executeMethod(meth);
+ if (returnCode <= 300) {
+ InputStream is = meth.getResponseBodyAsStream();
+ byte[] buffer = new byte[1024];
+ int read = is.read(buffer);
+ while (read > 0) {
+ fos.write(buffer, 0, read);
+ checksum.update(buffer, 0, read);
+ read = is.read(buffer);
+ }
+ is.close();
+ fos.flush();
+ fos.close();
+ if (!fm.getMd5().equals(checksum.getFormattedValue())) {
+ logger.error("File " + fm.getName() + ":\n\texpected : " + fm.getMd5() + "\n\tcalculated: " + checksum.getFormattedValue());
+ throw new UpdaterException("Signature de fichier téléchargé invalide - " + fm.getName());
+ } else {
+ // On décompresse le fichier
+ AbstractChecksum checksumUncompressed = new MD("MD5");
+ GZIPInputStream gzipis = new GZIPInputStream(new FileInputStream(tmpFile));
+ File tmpFileUncompressed = File.createTempFile("upd-", null, tmpDir);
+ FileOutputStream fosUncompressed = new FileOutputStream(tmpFileUncompressed);
+ byte[] bufferUncompressed = new byte[1024];
+ int readUncompressed = gzipis.read(bufferUncompressed);
+ while (readUncompressed > 0) {
+ fosUncompressed.write(bufferUncompressed, 0, readUncompressed);
+ checksumUncompressed.update(bufferUncompressed, 0, readUncompressed);
+ readUncompressed = gzipis.read(bufferUncompressed);
+ }
+ gzipis.close();
+ fosUncompressed.flush();
+ fosUncompressed.close();
+ tmpFile.delete();
+
+ if (!fm.getUnpackedMd5().equals(checksumUncompressed.getFormattedValue())) {
+ logger.error("File " + fm.getName() + ":\n\texpected : " + fm.getUnpackedMd5() + "\n\tcalculated: " + checksumUncompressed.getFormattedValue());
+ throw new UpdaterException("Signature de fichier décompressé invalide - " + fm.getName());
+ }
+
+ logger.debug("copy done.");
+ sb.append("copy|").append(tmpFileUncompressed.getName()).append("|").append(fm.getDest()).append("/").append(fm.getName()).append("\n");
+ }
+ } else {
+ errorMsg = " " + returnCode + " : " + meth.getStatusText() + " : " + sUrl;
+ bRet = false;
+ throw new IOException(errorMsg);
+ }
+ itemsRun++;
+ int newProgressValue = calculateProgress(nbItemsToTreat, itemsRun);
+ firePropertyChange("progress", lastProgressValue, newProgressValue);
+ lastProgressValue = newProgressValue;
+ }
+ for (DeleteModel dm : fl.getDeletes()) {
+ sb.append("delete|").append(dm.getName()).append("\n");
+ int newProgressValue = calculateProgress(nbItemsToTreat, itemsRun);
+ firePropertyChange("progress", lastProgressValue, newProgressValue);
+ lastProgressValue = newProgressValue;
+ }
+ for (ConfigurationModel conf : vm.getConfigurators()) {
+ if (!vm.getConfigurators().isEmpty()) {
+ sb.append("configuration|").append(conf.getClassName()).append("");
+ sb.append("\n");
+ int newProgressValue = calculateProgress(nbItemsToTreat, itemsRun);
+ firePropertyChange("progress", lastProgressValue, newProgressValue);
+ lastProgressValue = newProgressValue;
+ }
+ }
+ // declares component in installed components
+ logger.debug("install-component done.");
+ sb.append("install-component|").append(cm.getUri()).append("|").append(vm.getVersion()).append("|").append(cm.getDescription()).append("\n");
+ }
+ }
+ File batch = new File(tmpDir, "update-script.xem");
+ FileOutputStream fos = new FileOutputStream(batch);
+ StringBuilder header = new StringBuilder("# update of ").append(DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG).format(new Date())).append("\n");
+ fos.write(header.toString().getBytes("ISO-8859-1"));
+ fos.write(sb.toString().getBytes("ISO-8859-1"));
+ fos.flush();
+ fos.close();
+ } catch (UpdaterException uex) {
+ bRet = false;
+ exception = uex;
+ logger.error(uex);
+ } catch (MalformedURLException e) {
+ bRet = false;
+ logger.error(e);
+ } catch (IOException e) {
+ bRet = false;
+ logger.error(e);
+ } catch (DataConfigurationException dcEx) {
+ bRet = false;
+ errorMsg = dcEx.getMessage();
+ logger.error(dcEx);
+ } finally {
+ firePropertyChange("close", 0, 1);
+ }
+ return bRet;
+ }
+
+ @Override
+ protected void done() {
+ try {
+ saveInstalledModel();
+ if (Constants.MAJ_CONFIRM.equals(checkMethod)) {
+ JOptionPane.showMessageDialog(MainWindow.instance, "<html>Téléchargement des mises à jour terminé<br/>Veuillez redémarrer Xemelios afin de finaliser l'installation</html>", "Information", JOptionPane.INFORMATION_MESSAGE);
+ }
+ } catch (Exception ex) {
+ logger.error(ex);
+ new DisplayExceptionDlg(MainWindow.instance, ex);
+ }
+ }
+ /**
+ * calcule le pourcentage d'avancement
+ * @param total Le nombre total d'éléments à traiter
+ * @param current L'élément courant
+ * @return Le pourcentage d'avancement
+ */
+ private int calculateProgress(int total, int current) {
+ int ret = 100 * current / total;
+ logger.debug("item "+current+" done -> value="+ret);
+ return ret;
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.updater;
+
+public class UpdaterException extends Exception {
+
+ public UpdaterException() {
+ super();
+ // TODO Auto-generated constructor stub
+ }
+
+ public UpdaterException(String message) {
+ super(message);
+ // TODO Auto-generated constructor stub
+ }
+
+ public UpdaterException(String message, Throwable cause) {
+ super(message, cause);
+ // TODO Auto-generated constructor stub
+ }
+
+ public UpdaterException(Throwable cause) {
+ super(cause);
+ // TODO Auto-generated constructor stub
+ }
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.updater;
+
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.cp.xemelios.updater.config.ComponentModel;
+import fr.gouv.finances.cp.xemelios.updater.config.SiteModel;
+import fr.gouv.finances.cp.xemelios.updater.config.UpdateParser;
+import fr.gouv.finances.cp.xemelios.updater.config.XemeliosUpdateModel;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
+import fr.gouv.finances.dgfip.xemelios.common.NetAccess;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Hashtable;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathConstants;
+import javax.xml.xpath.XPathExpressionException;
+import javax.xml.xpath.XPathFactory;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.log4j.Logger;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+
+/**
+ *
+ * @author chm
+ */
+public class UpdaterUtil {
+ private static Logger logger = Logger.getLogger(UpdaterUtil.class);
+
+ private String updateUrl, componentsFileLocation;
+ private XPathFactory xpf = null;
+ private DocumentBuilderFactory domFactory;
+ private Hashtable<String,String> installedComponents;
+ private XemeliosUpdateModel downladableComponents;
+
+ /** Creates a new instance of UpdaterUtil */
+ public UpdaterUtil(String updateUrl, String componentsFileLocation) {
+ super();
+ this.updateUrl=updateUrl;
+ this.componentsFileLocation=componentsFileLocation;
+ try {
+ xpf = XPathFactory.newInstance(XPathFactory.DEFAULT_OBJECT_MODEL_URI);
+ domFactory = FactoryProvider.getDocumentBuilderFactory();
+ } catch(Throwable t) {
+ xpf = XPathFactory.newInstance();
+ t.printStackTrace();
+ }
+ }
+ private XemeliosUpdateModel getUpdatesAtUrl(String urlLocation) throws Exception {
+ HttpClient client = NetAccess.getHttpClient(MainWindow.getInstance().getEnvProperties());
+ GetMethod meth = new GetMethod(urlLocation);
+ int httpRet = client.executeMethod(meth);
+ if(httpRet>300) throw new Exception(meth.getStatusText());
+ InputStream is = meth.getResponseBodyAsStream();
+ UpdateParser up = new UpdateParser();
+ up.parse(is);
+ is.close();
+ XemeliosUpdateModel xum = (XemeliosUpdateModel) up.getMarshallable();
+ return xum;
+ }
+ public boolean areThereUpdatesAvailable() {
+ try {
+ loadInstalledComponents();
+ XemeliosUpdateModel xum = getUpdatesAtUrl(updateUrl);
+ return checkUpdates(xum);
+ } catch(Exception ex) {
+ ex.printStackTrace();
+ }
+ return false;
+ }
+ private boolean checkUpdates(XemeliosUpdateModel xum) {
+ logger.debug("checking for updates");
+ boolean ret = false;
+ if(xum.getConfigUpdates()!=null && xum.getConfigUpdates().getComponents().size()>0) {
+ for(ComponentModel cm:xum.getConfigUpdates().getComponents()) {
+ String existingVersion=installedComponents.get(cm.getId());
+ if(existingVersion==null) return true;
+ if(compareReleases(cm.getRelease().getV(),existingVersion)>0) return true;
+ }
+ }
+ if(xum.getFeaturesUpdates()!=null && xum.getFeaturesUpdates().getComponents().size()>0) {
+ for(ComponentModel cm:xum.getFeaturesUpdates().getComponents()) {
+ String existingVersion=installedComponents.get(cm.getId());
+ if(existingVersion==null) return true;
+ if(compareReleases(cm.getRelease().getV(),existingVersion)>0) return true;
+ }
+ }
+ if(xum.getXemeliosUpdates()!=null && xum.getXemeliosUpdates().getComponents().size()>0) {
+ for(ComponentModel cm:xum.getXemeliosUpdates().getComponents()) {
+ String existingVersion=installedComponents.get(cm.getId());
+ if(existingVersion==null) return true;
+ if(compareReleases(cm.getRelease().getV(),existingVersion)>0) return true;
+ }
+ }
+ if(xum.getForeignSites()!=null) {
+ for(SiteModel sm:xum.getForeignSites().getSites()) {
+ try {
+ if(checkUpdates(getUpdatesAtUrl(sm.getText()))) return true;
+ } catch(Exception ex) {}
+ }
+ }
+ return false;
+ }
+ protected void loadInstalledComponents() throws FileNotFoundException, ParserConfigurationException, SAXException, IOException {
+ installedComponents = new Hashtable<String,String>();
+ InputSource is = new InputSource(new FileReader(new File(componentsFileLocation)));
+ // on parse avant pour etre sur de l'implementation utilise (on veut du JAXP)
+ DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
+ Document dom = domBuilder.parse(is);
+ try {
+ XPath xp = xpf.newXPath();
+ Object o;
+ o = xp.evaluate("//component", dom, XPathConstants.NODESET);
+ if (o instanceof NodeList) {
+ NodeList nl = (NodeList) o;
+ for (int i = 0; i < nl.getLength(); i++) {
+ Element el = (Element) nl.item(i);
+ String compId;
+ try {
+ compId = (String) xp.evaluate("./@id", el, XPathConstants.STRING);
+ String compRelease = (String) xp.evaluate("./@version", el, XPathConstants.STRING);
+ installedComponents.put(compId,compRelease);
+ } catch (XPathExpressionException ex) {
+ ex.printStackTrace();
+ }
+ }
+// } else if (o instanceof List) {
+// List l = (List) o;
+// for (Object obj : l) {
+// if (obj instanceof Element) {
+// Element el = (Element) obj;
+// String compId;
+// try {
+// compId = (String) xp.evaluate("./@id", el, XPathConstants.STRING);
+// String compRelease = (String) xp.evaluate("./@version", el, XPathConstants.STRING);
+// installedComponents.put(compId,compRelease);
+// } catch (XPathExpressionException ex) {
+// ex.printStackTrace();
+// }
+// } else {
+// // erreur incomprehensible
+// }
+// }
+// } else {
+ // erreur incomprehensible
+ }
+ } catch (XPathExpressionException ex) {
+ }
+ }
+ public static int compareReleases(String r1, String r2) {
+ String[] s1 = splitRelease(r1);
+ String[] s2 = splitRelease(r2);
+ int ret = 0;
+ for(int i=0;i<Math.min(s1.length,s2.length);i++) {
+ float a = -1f, b = -1f;
+ try {
+ a = Integer.parseInt(s1[i]);
+ } catch(Throwable t) {
+ if(s1[i].endsWith("+")) {
+ // if there is a "+" in the release number, it is a non-official release,
+ // based on the previous build number. So the "real" number is the previous + 0.5
+ try {
+ a = Integer.parseInt(s1[i].substring(0, s1[i].length()-1));
+ a += 0.5;
+ } catch(Throwable t2) {}
+ }
+ }
+ try {
+ b = Integer.parseInt(s2[i]);
+ } catch(Throwable t) {
+ if(s2[i].endsWith("+")) {
+ // if there is a "+" in the release number, it is a non-official release,
+ // based on the previous build number. So the "real" number is the previous + 0.5
+ try {
+ b = Integer.parseInt(s2[i].substring(0, s2[i].length()-1));
+ b += 0.5;
+ } catch(Throwable t2) {}
+ }
+ }
+ if(a!=-1f && b!=-1f) {
+ if(a<b) ret = -1;
+ else if(a==b) ret = 0;
+ else ret = 1;
+ } else {
+ ret = s1[i].compareTo(s2[i]);
+ }
+ if(ret!=0) {
+ return ret;
+ }
+ }
+ if(s1.length>s2.length) ret = 1;
+ else if(s1.length<s2.length) ret = -1;
+ return ret;
+ }
+ private static String[] splitRelease(String r) {
+ return r.split("\\.");
+ }
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.updater.config;
+
+import fr.gouv.finances.dgfip.xemelios.common.config.TexteModel;
+import java.util.ArrayList;
+import java.util.Iterator;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import javax.xml.namespace.QName;
+
+public class ComponentModel implements XmlMarshallable {
+
+ public static final transient String TAG = "component";
+ public static final transient QName QN = new QName(TAG);
+ /**
+ * XEMELIOS type component
+ */
+ public static final int XEMELIOS = 1;
+ /**
+ * CONFIG type component
+ */
+ public static final int CONFIG = 2;
+ /**
+ * FEATURE type component
+ */
+ public static final int FEATURE = 3;
+ private String id, name;
+ private ReleaseModel release;
+ private TexteModel description;
+ private RequireModel requires;
+ private ArrayList<FileListModel> fileLists;
+ private ConfigurationModel configuration;
+ private boolean visible = true;
+ // for UI behavior only
+ public boolean selected = false;
+ public int type = 0;
+
+ public ComponentModel(QName tag) {
+ super();
+ fileLists = new ArrayList<FileListModel>();
+ }
+
+ public void addCharacterData(String cData) throws SAXException {
+ }
+
+ public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
+ if (ReleaseModel.QN.equals(tagName)) {
+ release = (ReleaseModel) child;
+ } else if (UpdateParser.DESCRIPTION.equals(tagName)) {
+ description = (TexteModel) child;
+ } else if (RequireModel.QN.equals(tagName)) {
+ requires = (RequireModel) child;
+ } else if (FileListModel.QN.equals(tagName)) {
+ fileLists.add((FileListModel) child);
+ } else if (ConfigurationModel.QN.equals(tagName)) {
+ configuration = (ConfigurationModel) child;
+ }
+ }
+
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ id = attributes.getValue("cid");
+ name = attributes.getValue("name");
+ String sTmp = attributes.getValue("visible");
+ if (sTmp != null) {
+ visible = attributes.getBooleanValue("visible");
+ }
+ return this;
+ }
+
+ public void marshall(XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("cid", id);
+ output.addAttribute("name", name);
+ if (!visible) {
+ output.addAttribute("visible", "no");
+ }
+ release.marshall(output);
+ description.marshall(output);
+ if (requires != null) {
+ requires.marshall(output);
+ }
+ for (Iterator<FileListModel> it = fileLists.iterator(); it.hasNext();) {
+ it.next().marshall(output);
+ }
+ // TODO
+ output.endTag(TAG);
+ }
+
+ public void validate() throws InvalidXmlDefinition {
+ if (id == null) {
+ throw new InvalidXmlDefinition("cid attribute is mandatory for element " + TAG);
+ }
+ if (name == null) {
+ throw new InvalidXmlDefinition("name attribute is mandatory for element " + TAG);
+ }
+ }
+
+ @Override
+ public ComponentModel clone() {
+ ComponentModel cm = new ComponentModel(QN);
+ cm.id = this.id;
+ cm.name = this.name;
+ cm.release = release.clone();
+ cm.description = this.description.clone();
+ for (Iterator<FileListModel> it = fileLists.iterator(); it.hasNext();) {
+ cm.fileLists.add(it.next().clone());
+ }
+ return cm;
+ }
+
+ public TexteModel getDescription() {
+ return description;
+ }
+
+ public void setDescription(TexteModel description) {
+ this.description = description;
+ }
+
+ public void setDescription(String s) {
+ TexteModel desc = new TexteModel(UpdateParser.DESCRIPTION);
+ try {
+ desc.addCharacterData(s);
+ } catch (Throwable t) {
+ }
+ setDescription(desc);
+ }
+
+ public ArrayList<FileListModel> getFileLists() {
+ return fileLists;
+ }
+
+ public void setFileLists(ArrayList<FileListModel> fileLists) {
+ this.fileLists = fileLists;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public ReleaseModel getRelease() {
+ return release;
+ }
+
+ public void setRelease(ReleaseModel release) {
+ this.release = release;
+ }
+
+ public void setRelease(String s) {
+ ReleaseModel rm = new ReleaseModel(ReleaseModel.QN);
+ rm.setV(s);
+ setRelease(rm);
+ }
+
+ public RequireModel getRequires() {
+ return requires;
+ }
+
+ public void setRequires(RequireModel requires) {
+ this.requires = requires;
+ }
+
+ @Override
+ public String toString() {
+ return getId() + " (" + getRelease().getV() + ")";
+ }
+
+ public boolean isVisible() {
+ return visible;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o instanceof ComponentModel) {
+ ComponentModel cm = (ComponentModel) o;
+ return cm.getId().equals(id) && cm.getRelease().getV().equals(getRelease().getV());
+ } else if (o instanceof ComponentRefModel) {
+ ComponentRefModel cm = (ComponentRefModel) o;
+ return cm.getId().equals(id) && cm.getVersion().equals(getRelease().getV());
+ } else if (o instanceof String) {
+ return getId().equals((String) o);
+ }
+ return false;
+ }
+
+ public ConfigurationModel getConfiguration() {
+ return configuration;
+ }
+
+ public void setConfiguration(ConfigurationModel configuration) {
+ this.configuration = configuration;
+ }
+
+ public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
+ return null;
+ }
+
+ public QName getQName() {
+ return QN;
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.updater.config;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import javax.xml.namespace.QName;
+
+public class ComponentRefModel implements XmlMarshallable {
+ public static final transient String TAG = "component-ref";
+ public static final transient QName QN = new QName(TAG);
+ private String id, version;
+
+ public ComponentRefModel(QName tag) {
+ super();
+ }
+
+ public void addCharacterData(String cData) throws SAXException {
+ }
+
+ public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
+ }
+
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ id=attributes.getValue("cid");
+ version=attributes.getValue("version");
+ return this;
+ }
+
+ public void marshall(XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("cid",id);
+ output.addAttribute("version",version);
+ output.endTag(TAG);
+ }
+
+ public void validate() throws InvalidXmlDefinition {
+ if(id==null) throw new InvalidXmlDefinition("cid attribute is mandatory for element "+TAG);
+ if(version==null) throw new InvalidXmlDefinition("version attribute is mandatory for element "+TAG);
+ }
+ public ComponentRefModel clone() {
+ ComponentRefModel cr = new ComponentRefModel(QN);
+ cr.id=id;
+ cr.version=version;
+ return cr;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+ public String toString() {
+ return id+" ("+version+")";
+ }
+ public boolean equals(ComponentRefModel crm) { return crm.getId().equals(id); }
+ public boolean equals(ComponentModel crm) { return crm.getId().equals(id); }
+ public boolean equals(String id) { return this.id.equals(id); }
+
+ public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
+ return null;
+ }
+
+ public QName getQName() {
+ return QN;
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.updater.config;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import javax.xml.namespace.QName;
+
+public class ConfigurationModel implements XmlMarshallable {
+ public static final transient String TAG="configuration";
+ public static final transient QName QN = new QName(TAG);
+
+ private String className;
+ private ArrayList<ParamModel> params;
+
+ public ConfigurationModel(QName tagName) {
+ super();
+ params = new ArrayList<ParamModel>();
+ }
+
+ public void addCharacterData(String cData) throws SAXException {
+ }
+
+ public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
+ if(ParamModel.QN.equals(tagName)) params.add((ParamModel)child);
+ }
+
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ className = attributes.getValue("class");
+ return this;
+ }
+
+ public void marshall(XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("class",className);
+ for(Iterator<ParamModel> it=params.iterator();it.hasNext();)
+ it.next().marshall(output);
+ output.endTag(TAG);
+ }
+
+ public void validate() throws InvalidXmlDefinition {
+ }
+ public ConfigurationModel clone() {
+ ConfigurationModel cm = new ConfigurationModel(QN);
+ cm.className=this.className;
+ for(Iterator<ParamModel> it=params.iterator();it.hasNext();)
+ cm.params.add(it.next());
+ return cm;
+ }
+
+ public String getClassName() {
+ return className;
+ }
+
+ public void setClassName(String className) {
+ this.className = className;
+ }
+
+ public ArrayList<ParamModel> getParams() {
+ return params;
+ }
+
+ public void setParams(ArrayList<ParamModel> params) {
+ this.params = params;
+ }
+
+ public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
+ return null;
+ }
+
+ public QName getQName() {
+ return QN;
+ }
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.updater.config;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import javax.xml.namespace.QName;
+
+public class DeleteModel implements XmlMarshallable {
+ public static final transient String TAG="delete";
+ public static final transient QName QN = new QName(TAG);
+
+
+ private String name;
+
+ public DeleteModel(QName tagName) {
+ super();
+ }
+
+ public void addCharacterData(String cData) throws SAXException { }
+
+ public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
+ }
+
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ name=attributes.getValue("name");
+ return this;
+ }
+
+ public void marshall(XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("name",name);
+ output.endTag(TAG);
+ }
+
+ public void validate() throws InvalidXmlDefinition { }
+
+ public DeleteModel clone() {
+ DeleteModel dm = new DeleteModel(QN);
+ dm.name=this.name;
+ return dm;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String toString() {
+ return "- "+getName();
+ }
+
+ public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
+ return null;
+ }
+
+ public QName getQName() {
+ return QN;
+ }
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.updater.config;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import javax.xml.namespace.QName;
+
+public class FileListModel implements XmlMarshallable {
+ public static final transient String TAG = "files";
+ public static final transient QName QN = new QName(TAG);
+
+ private String root;
+
+ public ArrayList<XmlMarshallable> files;
+
+ public FileListModel(QName tag) {
+ super();
+ files=new ArrayList<XmlMarshallable>();
+ }
+
+ public void addCharacterData(String cData) throws SAXException {
+ }
+
+ public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
+ files.add(child);
+ }
+
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ root = attributes.getValue("root");
+ return this;
+ }
+
+ public void marshall(XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("root",root);
+ for(Iterator<XmlMarshallable> it=files.iterator();it.hasNext();)
+ it.next().marshall(output);
+ output.endTag(TAG);
+ }
+
+ public void validate() throws InvalidXmlDefinition { }
+ public FileListModel clone() {
+ FileListModel flm = new FileListModel(QN);
+ flm.root=root;
+ for(Iterator<XmlMarshallable> it=files.iterator();it.hasNext();)
+ flm.files.add((XmlMarshallable)it.next().clone());
+ return flm;
+ }
+
+ public ArrayList<XmlMarshallable> getFiles() {
+ return files;
+ }
+
+ public void setFiles(ArrayList<XmlMarshallable> files) {
+ this.files = files;
+ }
+
+ public String getRoot() {
+ return root;
+ }
+
+ public void setRoot(String root) {
+ this.root = root;
+ }
+
+ public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
+ return null;
+ }
+
+ public QName getQName() {
+ return QN;
+ }
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.updater.config;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import javax.xml.namespace.QName;
+
+public class FileModel implements XmlMarshallable {
+
+ public static final transient String TAG = "file";
+ public static final transient QName QN = new QName(TAG);
+ private String name, source, dest, md5, unpackedMd5;
+ public FileModel(QName tag) {
+ super();
+ }
+
+ public void addCharacterData(String cData) throws SAXException {
+ }
+
+ public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
+ }
+
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ name = attributes.getValue("name");
+ source = attributes.getValue("source");
+ dest = attributes.getValue("dest");
+ md5 = attributes.getValue("md5");
+ unpackedMd5 = attributes.getValue("unpacked-md5");
+ return this;
+ }
+
+ public void marshall(XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("name", name);
+ output.addAttribute("source", source);
+ output.addAttribute("dest", dest);
+ output.addAttribute("md5", md5);
+ output.endTag(TAG);
+ }
+
+ public void validate() throws InvalidXmlDefinition {
+ }
+
+ @Override
+ public FileModel clone() {
+ FileModel fm = new FileModel(QN);
+ fm.name = name;
+ fm.source = source;
+ fm.dest = dest;
+ return fm;
+ }
+
+ public String getDest() {
+ return dest;
+ }
+
+ public void setDest(String dest) {
+ this.dest = dest;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getSource() {
+ return source;
+ }
+
+ public void setSource(String source) {
+ this.source = source;
+ }
+
+ @Override
+ public String toString() {
+ return getName();
+ }
+
+ public String getMd5() {
+ return md5;
+ }
+
+ public void setMd5(String md5) {
+ this.md5 = md5;
+ }
+
+ public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
+ return null;
+ }
+
+ public QName getQName() {
+ return QN;
+ }
+
+ public String getUnpackedMd5() {
+ return unpackedMd5;
+ }
+
+ public void setUnpackedMd5(String unpackedMd5) {
+ this.unpackedMd5 = unpackedMd5;
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.updater.config;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import javax.xml.namespace.QName;
+
+public class ForeignSitesModel implements XmlMarshallable {
+
+ public static final transient String TAG = "foreign-sites";
+ public static final transient QName QN = new QName(TAG);
+ private ArrayList<SiteModel> sites;
+
+ public ForeignSitesModel(QName tag) {
+ super();
+ sites = new ArrayList<SiteModel>();
+ }
+
+ public void addCharacterData(String cData) throws SAXException {
+ }
+
+ public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
+ sites.add((SiteModel) child);
+ }
+
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ return this;
+ }
+
+ public void marshall(XmlOutputter output) {
+ output.startTag(TAG);
+ for (Iterator<SiteModel> it = sites.iterator(); it.hasNext();) {
+ it.next().marshall(output);
+ }
+ output.endTag(TAG);
+ }
+
+ public void validate() throws InvalidXmlDefinition {
+ }
+
+ public ForeignSitesModel clone() {
+ ForeignSitesModel fs = new ForeignSitesModel(QN);
+ for (Iterator<SiteModel> it = sites.iterator(); it.hasNext();) {
+ fs.sites.add(it.next());
+ }
+ return fs;
+ }
+
+ public ArrayList<SiteModel> getSites() {
+ return sites;
+ }
+
+ public void setSites(ArrayList<SiteModel> sites) {
+ this.sites = sites;
+ }
+
+ public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
+ return null;
+ }
+
+ public QName getQName() {
+ return QN;
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.updater.config;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import javax.xml.namespace.QName;
+
+public class ParamModel implements XmlMarshallable {
+
+ public static final transient String TAG = "param";
+ public static final transient QName QN = new QName(TAG);
+ private String name;
+ private StringBuilder paramValue;
+
+ public ParamModel(QName tagName) {
+ super();
+ paramValue = new StringBuilder();
+ }
+
+ public void addCharacterData(String cData) throws SAXException {
+ paramValue.append(cData);
+ }
+
+ public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
+ }
+
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ name = attributes.getValue("name");
+ return this;
+ }
+
+ public void marshall(XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("name", name);
+ output.addCharacterData(getParamValue());
+ output.endTag(TAG);
+
+ }
+
+ public void validate() throws InvalidXmlDefinition {
+ }
+
+ public ParamModel clone() {
+ ParamModel pm = new ParamModel(QN);
+ pm.name = this.name;
+ pm.paramValue.append(this.getParamValue());
+ return pm;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getParamValue() {
+ return paramValue.toString();
+ }
+
+ public void setParamValue(StringBuilder paramValue) {
+ this.paramValue = paramValue;
+ }
+
+ public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
+ return null;
+ }
+
+ public QName getQName() {
+ return QN;
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.updater.config;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import javax.xml.namespace.QName;
+
+public class ReleaseModel implements XmlMarshallable {
+
+ public static final transient String TAG = "release";
+ public static final transient QName QN = new QName(TAG);
+ private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+ private String v;
+ private Date date;
+
+ public ReleaseModel(QName tag) {
+ super();
+ }
+
+ public void addCharacterData(String cData) throws SAXException {
+ }
+
+ public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
+ }
+
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ v = attributes.getValue("v");
+ String sTmp = attributes.getValue("date");
+ try {
+ date = sdf.parse(sTmp);
+ } catch (ParseException pEx) {
+ throw new SAXException("format for date attribute is YYYY-MM-DD");
+ }
+ return this;
+ }
+
+ public void marshall(XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("v", v);
+ output.addAttribute("date", sdf.format(date));
+ }
+
+ public Date getDate() {
+ return date;
+ }
+
+ public void setDate(Date date) {
+ this.date = date;
+ }
+
+ public String getV() {
+ return v;
+ }
+
+ public void setV(String v) {
+ this.v = v;
+ }
+
+ public void validate() throws InvalidXmlDefinition {
+ if (v == null || v.length() == 0) {
+ throw new InvalidXmlDefinition("attribute v is mandatory for " + TAG + " element.");
+ }
+ if (date == null) {
+ throw new InvalidXmlDefinition("attribute date is mandatory for " + TAG + " element.");
+ }
+ }
+
+ public ReleaseModel clone() {
+ ReleaseModel rm = new ReleaseModel(QN);
+ rm.v = this.v;
+ rm.date = (Date) this.date.clone();
+ return rm;
+ }
+
+ public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
+ return null;
+ }
+
+ public QName getQName() {
+ return QN;
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.updater.config;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import javax.xml.namespace.QName;
+
+public class RequireModel implements XmlMarshallable {
+ public static final transient String TAG = "requires";
+ public static final transient QName QN = new QName(TAG);
+
+ private ArrayList<ComponentRefModel> components;
+
+ public RequireModel(QName tag) {
+ super();
+ components = new ArrayList<ComponentRefModel>();
+ }
+
+ public void addCharacterData(String cData) throws SAXException {
+ }
+
+ public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
+ components.add((ComponentRefModel)child);
+ }
+
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ return this;
+ }
+
+ public void marshall(XmlOutputter output) {
+ output.startTag(TAG);
+ for(int i=0;i<components.size();i++) components.get(i).marshall(output);
+ output.endTag(TAG);
+ }
+
+ public void validate() throws InvalidXmlDefinition {
+ for(Iterator<ComponentRefModel> it=components.iterator();it.hasNext();)
+ it.next().validate();
+ }
+ public RequireModel clone() {
+ RequireModel rm = new RequireModel(QN);
+ for(Iterator<ComponentRefModel> it=components.iterator();it.hasNext();)
+ rm.components.add(it.next());
+ return rm;
+ }
+
+ public ArrayList<ComponentRefModel> getComponents() {
+ return components;
+ }
+
+ public void setComponents(ArrayList<ComponentRefModel> components) {
+ this.components = components;
+ }
+
+ public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
+ return null;
+ }
+
+ public QName getQName() {
+ return QN;
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.updater.config;
+
+import fr.gouv.finances.dgfip.xemelios.common.config.TexteModel;
+import org.xml.sax.SAXException;
+
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import javax.xml.namespace.QName;
+
+public class SiteModel extends TexteModel {
+ public static final transient String TAG = "site";
+ public static final transient QName QN = new QName(TAG);
+ private String name;
+
+ public SiteModel(QName tagName) {
+ super(tagName);
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ name=attributes.getValue("name");
+ return this;
+ }
+
+ @Override
+ public void marshall(XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("name",name);
+ output.addCharacterData(getText());
+ output.endTag(TAG);
+ }
+
+ @Override
+ public SiteModel clone() {
+ // TODO Auto-generated method stub
+ SiteModel sm = new SiteModel(QN);
+ sm.name=this.name;
+ try {
+ sm.addCharacterData(getText());
+ } catch(Throwable t) {}
+ return sm;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.updater.config;
+
+import fr.gouv.finances.dgfip.xemelios.common.config.TexteModel;
+import java.util.HashMap;
+
+import javax.xml.parsers.FactoryConfigurationError;
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.xml.sax.SAXException;
+
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshalParser;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
+import javax.xml.namespace.QName;
+
+public class UpdateParser extends XmlMarshalParser {
+
+ public UpdateParser() throws SAXException, ParserConfigurationException, FactoryConfigurationError {
+ super(new Mapping(),true,FactoryProvider.getSaxParserFactory());
+ }
+ private static class Mapping extends HashMap<QName,Class> {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 3617293411154145847L;
+
+ public Mapping() {
+ put(ComponentModel.QN,ComponentModel.class);
+ put(ComponentRefModel.QN,ComponentRefModel.class);
+ put(FileListModel.QN,FileListModel.class);
+ put(FileModel.QN,FileModel.class);
+ put(ForeignSitesModel.QN,ForeignSitesModel.class);
+ put(ReleaseModel.QN,ReleaseModel.class);
+ put(RequireModel.QN,RequireModel.class);
+ put(SiteModel.QN,SiteModel.class);
+ put(XemeliosUpdateModel.QN,XemeliosUpdateModel.class);
+ put(ORIGINAL_LOCATION,TexteModel.class);
+ put(DESCRIPTION,TexteModel.class);
+ put(XEMELIOS_UPDATES,UpdatePartModel.class);
+ put(CONFIG_UPDATES,UpdatePartModel.class);
+ put(FEATURES_UPDATES,UpdatePartModel.class);
+ put(DeleteModel.QN,DeleteModel.class);
+ put(ConfigurationModel.QN,ConfigurationModel.class);
+ put(ParamModel.QN,ParamModel.class);
+ }
+ }
+ public static final transient QName ORIGINAL_LOCATION = new QName("original-location");
+ public static final transient QName DESCRIPTION = new QName("description");
+ public static final transient QName XEMELIOS_UPDATES = new QName("xemelios-updates");
+ public static final transient QName CONFIG_UPDATES = new QName("config-updates");
+ public static final transient QName FEATURES_UPDATES = new QName("features-updates");
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.updater.config;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import javax.xml.namespace.QName;
+
+public class UpdatePartModel implements XmlMarshallable {
+
+ private String tag;
+ private QName qn;
+ private ArrayList<ComponentModel> components;
+ public UpdatePartModel(QName tagName) {
+ super();
+ this.qn=tagName;
+ this.tag=qn.getLocalPart();
+ components = new ArrayList<ComponentModel>();
+ }
+
+ public void addCharacterData(String cData) throws SAXException {
+ }
+
+ public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
+ components.add((ComponentModel)child);
+ }
+
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ return this;
+ }
+
+ public void marshall(XmlOutputter output) {
+ output.startTag(tag);
+ for(Iterator<ComponentModel> it=components.iterator();it.hasNext();)
+ it.next().marshall(output);
+ output.endTag(tag);
+ }
+
+ public void validate() throws InvalidXmlDefinition {
+ }
+ public UpdatePartModel clone() {
+ UpdatePartModel upm = new UpdatePartModel(getQName());
+ for(Iterator<ComponentModel> it=components.iterator();it.hasNext();)
+ upm.components.add(it.next());
+ return upm;
+ }
+
+ public ArrayList<ComponentModel> getComponents() {
+ return components;
+ }
+
+ public void setComponents(ArrayList<ComponentModel> components) {
+ this.components = components;
+ }
+
+ public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
+ return null;
+ }
+
+ public QName getQName() {
+ return qn;
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.updater.config;
+
+import fr.gouv.finances.dgfip.xemelios.common.config.TexteModel;
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import javax.xml.namespace.QName;
+
+public class XemeliosUpdateModel implements XmlMarshallable {
+ public static final transient String TAG = "xemelios-update";
+ public static final transient QName QN = new QName(TAG);
+
+ private ReleaseModel release = null;
+ private TexteModel originalLocation = null;
+ private UpdatePartModel xemeliosUpdates, configUpdates, featuresUpdates;
+ private ForeignSitesModel foreignSites;
+
+ public XemeliosUpdateModel(QName tag) {
+ super();
+ }
+
+ public void addCharacterData(String cData) throws SAXException {
+ }
+
+ public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
+ if(ReleaseModel.QN.equals(tagName)) release = (ReleaseModel)child;
+ else if(UpdateParser.ORIGINAL_LOCATION.equals(tagName)) originalLocation = (TexteModel)child;
+ else if(UpdateParser.XEMELIOS_UPDATES.equals(tagName)) xemeliosUpdates = (UpdatePartModel)child;
+ else if(UpdateParser.CONFIG_UPDATES.equals(tagName)) configUpdates = (UpdatePartModel)child;
+ else if(UpdateParser.FEATURES_UPDATES.equals(tagName)) featuresUpdates = (UpdatePartModel)child;
+ else if(ForeignSitesModel.QN.equals(tagName)) foreignSites = (ForeignSitesModel)child;
+ }
+
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ return this;
+ }
+
+ public void marshall(XmlOutputter output) {
+ output.startTag(TAG);
+ if(release!=null) release.marshall(output);
+ if(originalLocation!=null) originalLocation.marshall(output);
+ if(xemeliosUpdates!=null) xemeliosUpdates.marshall(output);
+ if(configUpdates!=null) configUpdates.marshall(output);
+ if(featuresUpdates!=null) featuresUpdates.marshall(output);
+ if(foreignSites!=null) foreignSites.marshall(output);
+ output.endTag(TAG);
+ }
+
+ public void validate() throws InvalidXmlDefinition {
+ if(release==null) throw new InvalidXmlDefinition("element release is mandatory for element "+TAG);
+ }
+ public XemeliosUpdateModel clone() {
+ XemeliosUpdateModel xu = new XemeliosUpdateModel(QN);
+ xu.release=release.clone();
+ if(originalLocation!=null) xu.originalLocation=originalLocation.clone();
+ if(xemeliosUpdates!=null) xu.xemeliosUpdates=xemeliosUpdates.clone();
+ if(configUpdates!=null) xu.configUpdates=configUpdates.clone();
+ if(featuresUpdates!=null) xu.featuresUpdates=featuresUpdates.clone();
+ if(foreignSites!=null) xu.foreignSites=foreignSites.clone();
+ return xu;
+ }
+
+ public UpdatePartModel getConfigUpdates() {
+ return configUpdates;
+ }
+
+ public void setConfigUpdates(UpdatePartModel configUpdates) {
+ this.configUpdates = configUpdates;
+ }
+
+ public UpdatePartModel getFeaturesUpdates() {
+ return featuresUpdates;
+ }
+
+ public void setFeaturesUpdates(UpdatePartModel featuresUpdates) {
+ this.featuresUpdates = featuresUpdates;
+ }
+
+ public ForeignSitesModel getForeignSites() {
+ return foreignSites;
+ }
+
+ public void setForeignSites(ForeignSitesModel foreignSites) {
+ this.foreignSites = foreignSites;
+ }
+
+ public TexteModel getOriginalLocation() {
+ return originalLocation;
+ }
+
+ public void setOriginalLocation(TexteModel originalLocation) {
+ this.originalLocation = originalLocation;
+ }
+
+ public ReleaseModel getRelease() {
+ return release;
+ }
+
+ public void setRelease(ReleaseModel release) {
+ this.release = release;
+ }
+
+ public UpdatePartModel getXemeliosUpdates() {
+ return xemeliosUpdates;
+ }
+
+ public void setXemeliosUpdates(UpdatePartModel xemeliosUpdates) {
+ this.xemeliosUpdates = xemeliosUpdates;
+ }
+
+ public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
+ return null;
+ }
+
+ public QName getQName() {
+ return QN;
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2010 axYus - www.axyus.com
+ * 2010 F.Nhieu - franck.nhieu@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.updater.installed;
+
+import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import fr.gouv.finances.cp.xemelios.updater.profils.ComponentModel;
+import fr.gouv.finances.cp.xemelios.updater.profils.ProfilModel;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.UUID;
+import javax.xml.namespace.QName;
+import javax.xml.parsers.ParserConfigurationException;
+import org.apache.log4j.Logger;
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+public class InstalledModel implements XmlMarshallable {
+ private static Logger logger = Logger.getLogger(InstalledModel.class);
+ public static final transient String TAG = "xemelios-installed";
+ public static final transient QName QN = new QName(TAG);
+ public static final transient int NOT_FOUND = -1;
+ private ArrayList<ComponentModel> components;
+ private ArrayList<ProfilModel> profils;
+ private String fileLocation;
+ public static final transient String ALLREADY_EXISTS = "ALLREADY_EXISTS";
+
+ public InstalledModel(ArrayList<ComponentModel> components, ArrayList<ProfilModel> profils) {
+ super();
+ this.components = components;
+ this.profils = profils;
+ }
+
+ public InstalledModel(QName tagName) {
+ super();
+ profils = new ArrayList<ProfilModel>();
+ components = new ArrayList<ComponentModel>();
+ }
+
+ public static InstalledModel readFromFile(String fileLocation) throws SAXException, ParserConfigurationException, IOException, Exception {
+ if(fileLocation==null) throw new Exception("fichier non renseigné");
+ InstalledParser ip = new InstalledParser();
+ ip.parse(fileLocation);
+ InstalledModel im = (InstalledModel)ip.getMarshallable();
+ im.setFileLocation(fileLocation);
+ return im;
+ }
+
+ /**
+ * Méthode static permettant de charger les abonnements, d'ajouter un
+ * profil et de sauvegarder les abonnements.
+ * @param fileLocation
+ * @param pm
+ * @throws SAXException
+ * @throws ParserConfigurationException
+ * @throws IOException
+ * @throws Exception
+ */
+ public static void addProfilAndSave(String fileLocation, ProfilModel pm)
+ throws SAXException, ParserConfigurationException, IOException, Exception {
+ InstalledModel im = InstalledModel.readFromFile(fileLocation);
+ // check si profil déja abonné, on return si c'est le cas
+ // sans throw une exception utilisateur
+ for(ProfilModel p:im.getProfils()) {
+ if(p.getId().equals(pm.getId()))
+ return;
+ }
+ im.profils.add(pm);
+ im.saveInstalledModel(fileLocation);
+ }
+
+ public void addProfil(ProfilModel pm) {
+ for(ProfilModel p:profils) {
+ if(p.getId().equals(pm.getId()))
+ return;
+ }
+ profils.add(pm);
+ }
+
+
+ public void setFileLocation(String fileLocation) {
+ this.fileLocation = fileLocation;
+ }
+
+ public String getFileLocation() {
+ return fileLocation;
+ }
+
+ public ArrayList<ComponentModel> getComponents() {
+ return components;
+ }
+
+ public ArrayList<ProfilModel> getProfils() {
+ return profils;
+ }
+
+ public void setComponents(ArrayList<ComponentModel> components) {
+ this.components = components;
+ }
+
+ public void setProfils(ArrayList<ProfilModel> profils) {
+ this.profils = profils;
+ }
+
+ @Override
+ public void addCharacterData(String cData) throws SAXException { }
+
+ @Override
+ public void addChild(XmlMarshallable child, QName tag) throws SAXException {
+ if(ComponentModel.QN.equals(tag)) components.add((ComponentModel)child);
+ if(ProfilModel.QN.equals(tag)) profils.add((ProfilModel)child);
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ return this;
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public void marshall(XmlOutputter output) {
+ output.startTag(TAG);
+ for(ComponentModel cm:components) cm.marshall(output);
+ for(ProfilModel pm:profils) pm.marshall(output);
+ output.endTag(TAG);
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ for(ComponentModel cm:components) cm.validate();
+ for(ProfilModel pm:profils) pm.validate();
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
+
+ @Override
+ public InstalledModel clone() {
+ return this;
+ }
+
+ /**
+ * Retourne l'index de l'ArrayList d'un profil donné selon son identifiant
+ * @param id
+ * @return
+ */
+ public int getProfilIdx(String id) {
+ if(id==null) return NOT_FOUND;
+ for(int idx=0; idx<profils.size(); idx++ ) {
+ if(profils.get(idx).getId().equals(id))
+ return idx;
+ }
+ return NOT_FOUND;
+ }
+
+ public ComponentModel getComponent(String URI) {
+ if(URI==null) return null;
+ for(ComponentModel cm:components)
+ if(cm.getUri().equals(URI))
+ return cm;
+ return null;
+ }
+
+
+ /**
+ * Retourne l'index de l'ArrayList d'un composant donné selon son URI
+ * @param id
+ * @return
+ */
+ public int getComponentIdx(String URI) {
+ if(URI==null) return NOT_FOUND;
+ for(int idx=0; idx<components.size(); idx++ ) {
+ if(components.get(idx).getUri().equals(URI))
+ return idx;
+ }
+ return NOT_FOUND;
+ }
+
+ public int getComponentIdx(UUID uuid) {
+ if(uuid==null) return NOT_FOUND;
+ for(int idx=0; idx<components.size(); idx++ ) {
+ if(components.get(idx).getUUID().equals(uuid))
+ return idx;
+ }
+ return NOT_FOUND;
+ }
+
+ public boolean removeComponent(UUID uuid) {
+ if(uuid==null) return false;
+ for(int idx=0; idx<components.size(); idx++ ) {
+ if(components.get(idx).getUUID().equals(uuid)) {
+ components.remove(idx);
+ return true;
+ }
+ }
+ return true;
+ }
+
+ public boolean removeComponent(String URI) {
+ if(URI==null) return false;
+ for(int idx=0; idx<components.size(); idx++ ) {
+ if(components.get(idx).getUri().equals(URI))
+ components.remove(idx);
+ }
+ return true;
+ }
+
+ public boolean removeProfil(String id) {
+ if(id==null) return false;
+ for(int idx=0; idx<profils.size(); idx++ ) {
+ if(profils.get(idx).getId().equals(id))
+ profils.remove(idx);
+ }
+ return true;
+ }
+
+
+ /**
+ * Ajoute le composant passé en paramètre
+ * @param cm
+ * @throws Exception
+ */
+ public void addComponent(ComponentModel cm) throws Exception {
+ for(int idx=0; idx<components.size(); idx++ ) {
+ if(components.get(idx).getUri().equals(cm.getUri()))
+ throw new Exception(ALLREADY_EXISTS);
+ }
+ this.components.add(cm);
+ }
+
+ /**
+ * Verifie l'existance d'un composant
+ * @param cm
+ * @return
+ */
+ public boolean exists(ComponentModel cm) {
+ for(int idx=0; idx<components.size(); idx++ ) {
+ if(components.get(idx).getUri().equals(cm.getUri()))
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Sauvegarde le contenu de l'instanciation courante dans le fichier XML
+ * dans le fichier contenu dans l'attribut 'fileLocation' (ISO8859-1)
+ * @throws Exception
+ */
+ public void saveInstalledModel() throws Exception {
+ if(fileLocation==null)
+ throw new Exception("fichier de sortie non renseigné.");
+ saveInstalledModel(fileLocation);
+ }
+
+ /**
+ * Sauvegarde le contenu de l'instanciation courante dans le fichier XML
+ * passé en paramètre (ISO8859-1)
+ * @param fileLocation
+ * @throws IOException
+ */
+ public void saveInstalledModel(String fileLocation) throws IOException {
+ Charset cs = Charset.forName("ISO-8859-1");
+ File fo = new File(fileLocation);
+ outputToFile(fo, cs);
+ }
+
+ /**
+ * Sauvegarde le contenu de l'instanciation courante dans le fichier XML
+ * dans le fichier indiqué par le paramètre 'fo' au charset
+ * indiqué par le paramètre 'cs'
+ * @param fo
+ * @param cs
+ * @throws IOException
+ */
+ public void outputToFile( String fo, String cs ) throws IOException {
+ outputToFile( new File(fo), Charset.forName(cs) );
+ }
+ /**
+ * Sauvegarde le contenu de l'instanciation courante dans le fichier XML
+ * dans le FileOutputter indiqué par le paramètre 'fo' au charset
+ * indiqué par le parametre 'cs'
+ * @param fo
+ * @param cs
+ * @throws IOException
+ */
+ public void outputToFile( File fo, Charset cs ) throws IOException {
+ FileOutputStream fos = null;
+ try {
+ fos = new FileOutputStream(fo);
+ OutputStreamWriter osw = new OutputStreamWriter(fos, cs);
+ XmlOutputter xo = new XmlOutputter(osw, cs.name());
+ this.marshall(xo);
+ osw.flush();
+ osw.close();
+ } catch (IOException ex) {
+ logger.debug(ex);
+ throw ex;
+ } finally { try { fos.close(); } catch (Throwable t) {} }
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2010 axYus - www.axyus.com
+ * 2010 F.Nhieu - franck.nhieu@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.updater.installed;
+
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshalParser;
+import fr.gouv.finances.cp.xemelios.updater.profils.ComponentModel;
+import fr.gouv.finances.cp.xemelios.updater.profils.ProfilModel;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
+import java.util.HashMap;
+import javax.xml.namespace.QName;
+import javax.xml.parsers.FactoryConfigurationError;
+import javax.xml.parsers.ParserConfigurationException;
+import org.xml.sax.SAXException;
+
+public class InstalledParser extends XmlMarshalParser {
+
+ public InstalledParser(HashMap mapping) throws SAXException, ParserConfigurationException, FactoryConfigurationError {
+ super(mapping, FactoryProvider.getSaxParserFactory());
+ }
+
+ public InstalledParser() throws SAXException, ParserConfigurationException, FactoryConfigurationError {
+ super(new Mapping(),true, FactoryProvider.getSaxParserFactory());
+ }
+
+ private static class Mapping extends HashMap<QName, Class> {
+ public Mapping() {
+ put(InstalledModel.QN, InstalledModel.class);
+ put(ProfilModel.QN, ProfilModel.class);
+ put(ComponentModel.QN, ComponentModel.class);
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2010 axYus - www.axyus.com
+ * 2010 F.Nhieu - franck.nhieu@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.updater.profils;
+
+//~--- non-JDK imports --------------------------------------------------------
+import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import java.util.UUID;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+//~--- JDK imports ------------------------------------------------------------
+
+import javax.xml.namespace.QName;
+import org.apache.log4j.Logger;
+
+/**
+ *
+ * Definition d'un component dans un profil
+ */
+public class ComponentModel implements XmlMarshallable {
+
+ private static Logger logger = Logger.getLogger(ComponentModel.class);
+ public static final transient String TAG = "component";
+ public static final transient QName QN = new QName(TAG);
+ private String uri;
+ private String version;
+ private String description;
+ private String editable;
+ private UUID internal_uuid;
+
+ public ComponentModel() {
+ super();
+ internal_uuid = UUID.randomUUID();
+ }
+
+ public ComponentModel(QName QN) {
+ super();
+ internal_uuid = UUID.randomUUID();
+ }
+
+ public ComponentModel(String uri) {
+ this(QN);
+ this.uri = uri;
+ internal_uuid = UUID.randomUUID();
+ }
+
+ public ComponentModel(String uri, String version, String description, boolean editable) {
+ this(QN);
+ this.uri = uri;
+ this.version = version;
+ this.description = description;
+ this.editable = (editable ? "true" : "false");
+ internal_uuid = UUID.randomUUID();
+ }
+
+ public UUID getUUID() {
+ return internal_uuid;
+ }
+
+ public String getUri() {
+ return uri;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public void setUri(String uri) {
+ this.uri = uri;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ public boolean isEditable() {
+ return "true".equals(editable);
+ }
+
+ public void setEditable(boolean editable) {
+ this.editable = (editable ? "true" : "false");
+ }
+
+ @Override
+ public void addCharacterData(String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(XmlMarshallable child, QName tag) throws SAXException {
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ uri = attributes.getValue("uri");
+ version = attributes.getValue("version");
+ description = attributes.getValue("description");
+ editable = attributes.getValue("editable");
+ return this;
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public void marshall(XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("uri", uri);
+ if (version != null) {
+ output.addAttribute("version", version);
+ }
+ if (description != null) {
+ output.addAttribute("description", description);
+ }
+ if (editable != null) {
+ output.addAttribute("editable", editable);
+ }
+ output.endTag(TAG);
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ if (uri == null) {
+ throw new InvalidXmlDefinition("component uri attribute is mandatory for element " + TAG);
+ }
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
+
+ @Override
+ public ComponentModel clone() {
+ return this;
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if(other instanceof ComponentModel)
+ return uri.equals(((ComponentModel)other).uri);
+ else
+ return super.equals(other);
+ }
+
+ @Override
+ public int hashCode() {
+ int hash = 7;
+ hash = 97 * hash + (this.uri != null ? this.uri.hashCode() : 0);
+ return hash;
+ }
+
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2010 axYus - www.axyus.com
+ * 2010 F.Nhieu - franck.nhieu@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+/**
+ * Modèle de l'élèment "profil"
+ * Contient l'ensemble des composants d'un profil.
+ */
+package fr.gouv.finances.cp.xemelios.updater.profils;
+
+//~--- non-JDK imports --------------------------------------------------------
+import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+//~--- JDK imports ------------------------------------------------------------
+
+import java.util.ArrayList;
+
+import javax.xml.namespace.QName;
+import org.apache.log4j.Logger;
+
+public class ProfilModel implements XmlMarshallable {
+ private static Logger logger = Logger.getLogger(ProfilModel.class);
+
+ public static final transient String TAG = "profil";
+ public static final transient QName QN = new QName(TAG);
+ // par défaut, un profil n'est pas requit, pas désactivé et visible par l'utilisateur.
+ private boolean required = false,
+ disabled = false,
+ visible = true;
+ public ArrayList<ComponentModel> components;
+ private String id, description;
+ private boolean dontWriteOptionalAttributes = false;
+
+ public ProfilModel(QName tagName) {
+ super();
+ this.required = false;
+ this.disabled = false;
+ this.visible = true;
+ components = new ArrayList<ComponentModel>();
+ this.dontWriteOptionalAttributes = false;
+ }
+
+ public ProfilModel(String id, String description, boolean required, boolean disabled, boolean visible,
+ ArrayList<ComponentModel> components) {
+ this(QN);
+ this.id = id;
+ this.description = description;
+ this.required = required;
+ this.disabled = disabled;
+ this.visible = visible;
+ this.components = components;
+ this.dontWriteOptionalAttributes = false;
+ }
+
+ public ProfilModel(String id, String description) {
+ this(QN);
+ this.id = id;
+ this.description = description;
+ this.required = false;
+ this.disabled = false;
+ this.visible = true;
+ this.components = new ArrayList<ComponentModel>();
+ this.dontWriteOptionalAttributes = false;
+ }
+
+ public void setDontWriteOptionalAttributes(boolean dontWriteOptionalAttributes) {
+ this.dontWriteOptionalAttributes = dontWriteOptionalAttributes;
+ }
+
+ @Override
+ public void addCharacterData(String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
+ ComponentModel cm = (ComponentModel) child;
+ components.add(cm);
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ id = attributes.getValue("id");
+ description = attributes.getValue("description");
+ required = ((attributes.getValue("required") != null)
+ ? attributes.getValue("required").equals("true")
+ : false);
+ disabled = ((attributes.getValue("disabled") != null)
+ ? attributes.getValue("disabled").equals("true")
+ : false);
+ visible = ((attributes.getValue("visible") != null)
+ ? attributes.getValue("visible").equals("true")
+ : true);
+
+ return this;
+ }
+
+ @Override
+ public void marshall(XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("id", id);
+ output.addAttribute("description", description);
+ if (!dontWriteOptionalAttributes) {
+ output.addAttribute("required", (required
+ ? "true"
+ : "false"));
+ output.addAttribute("disabled", (disabled
+ ? "true"
+ : "false"));
+ output.addAttribute("visible", (visible
+ ? "true"
+ : "false"));
+ }
+ for (ComponentModel cm : components) {
+ cm.marshall(output);
+ }
+ output.endTag(TAG);
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ if (id == null) {
+ throw new InvalidXmlDefinition("id attribute is mandatory for element " + TAG);
+ }
+ for (ComponentModel cm : components) {
+ cm.validate();
+ }
+ }
+
+ @Override
+ public ProfilModel clone() {
+ ProfilModel m = new ProfilModel(QN);
+ m.description = description;
+ m.disabled = disabled;
+ m.id = id;
+ m.required = required;
+ m.visible = visible;
+ for (ComponentModel cm : components) {
+ m.components.add(cm.clone());
+ }
+ return m;
+ }
+
+ public ArrayList<ComponentModel> getComponents() {
+ return components;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public boolean isDisabled() {
+ return disabled;
+ }
+
+ public boolean isRequired() {
+ return required;
+ }
+
+ public boolean isVisible() {
+ return visible;
+ }
+
+ public void setComponents(ArrayList<ComponentModel> components) {
+ this.components = components;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public void setDisabled(boolean disabled) {
+ this.disabled = disabled;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public void setRequired(boolean required) {
+ this.required = required;
+ }
+
+ public void setVisible(boolean visible) {
+ this.visible = visible;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o instanceof ProfilModel) {
+ ProfilModel m = (ProfilModel) o;
+ return m.getId().equals(getId());
+ }
+ return false;
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
+
+ @Override
+ public String toString() {
+ return "id=" + id + "/description=" + description + "/disabled=" + disabled + "/required=" + required + "/visible=" + visible;
+ }
+
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2010 axYus - www.axyus.com
+ * 2010 F.Nhieu - franck.nhieu@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.updater.profils;
+
+import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.dgfip.xemelios.common.NetAccess;
+import java.io.InputStream;
+import java.util.ArrayList;
+import javax.xml.namespace.QName;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.log4j.Logger;
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+public class ProfilsModel implements XmlMarshallable {
+
+ private static Logger logger = Logger.getLogger(ProfilsModel.class);
+ public static final transient String TAG = "xemelios-profils";
+ public static final transient QName QN = new QName(TAG);
+ public static final transient int NOT_FOUND = -1;
+ private ArrayList<ProfilModel> profils;
+ private boolean dontWriteOptionalAttributes = false;
+
+ public ProfilsModel(QName tagName) {
+ super();
+ profils = new ArrayList<ProfilModel>();
+ }
+
+ private ProfilsModel() {
+ super();
+ profils = new ArrayList<ProfilModel>();
+ }
+
+ public void setDontWriteOptionalAttributes(boolean dontWriteOptionalAttributes) {
+ this.dontWriteOptionalAttributes = dontWriteOptionalAttributes;
+ }
+
+ @Override
+ public void addCharacterData(String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(XmlMarshallable child, QName tag) throws SAXException {
+ ProfilModel pm = (ProfilModel) child;
+ profils.add(pm);
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ return this;
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public void marshall(XmlOutputter output) {
+ output.startTag(TAG);
+ for (ProfilModel pm : profils) {
+ pm.setDontWriteOptionalAttributes(dontWriteOptionalAttributes);
+ pm.marshall(output);
+ }
+ output.endTag(TAG);
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ for (ProfilModel pm : profils) {
+ pm.validate();
+ }
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
+
+ @Override
+ public ProfilsModel clone() {
+ return this;
+ }
+
+ public ArrayList<ProfilModel> getProfils() {
+ return profils;
+ }
+
+ public int getIdxById(String id) {
+ for (int idx = 0; idx < profils.size(); idx++) {
+ if (profils.get(idx).getId().equals(id)) {
+ return idx;
+ }
+ }
+ return NOT_FOUND;
+ }
+
+ public static ProfilsModel loadModel(String urlLocation, HttpClient client) throws Exception {
+ ProfilsModel pms = new ProfilsModel();
+ try {
+ logger.debug("urlLocation=" + urlLocation);
+ GetMethod meth = new GetMethod(urlLocation);
+ meth.addRequestHeader("Pragma", "no-cache");
+ int httpRet = client.executeMethod(meth);
+ if (httpRet > 300) {
+ throw new Exception("URL urlLocation " + urlLocation + " : " + meth.getStatusText());
+ }
+ InputStream is = meth.getResponseBodyAsStream();
+ ProfilsParser pp = new ProfilsParser();
+ pp.parse(is);
+ is.close();
+ pms = (ProfilsModel) pp.getMarshallable();
+ return pms;
+ } catch (Exception ex) {
+ logger.error(ex);
+ throw ex;
+ }
+ }
+ public static ProfilsModel loadModel(String urlLocation) throws Exception {
+ return loadModel(urlLocation, NetAccess.getHttpClient(MainWindow.getInstance().getEnvProperties()) );
+ }
+
+ @Override
+ public String toString() {
+ String strReturn = "";
+ for(ProfilModel pm:profils)
+ strReturn = strReturn.concat("\n"+pm.toString());
+ return strReturn;
+ }
+
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2010 axYus - www.axyus.com
+ * 2010 F.Nhieu - franck.nhieu@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+
+
+package fr.gouv.finances.cp.xemelios.updater.profils;
+
+//~--- non-JDK imports --------------------------------------------------------
+
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshalParser;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
+
+import org.xml.sax.SAXException;
+
+//~--- JDK imports ------------------------------------------------------------
+
+import java.util.HashMap;
+
+import javax.xml.namespace.QName;
+import javax.xml.parsers.FactoryConfigurationError;
+import javax.xml.parsers.ParserConfigurationException;
+
+/**
+ *
+ *
+ */
+public class ProfilsParser extends XmlMarshalParser {
+ public static final transient QName XEMELIOS_PROFILS = new QName("xemelios-profils");
+
+ public ProfilsParser(HashMap mapping) throws SAXException, ParserConfigurationException, FactoryConfigurationError {
+ super(mapping, FactoryProvider.getSaxParserFactory());
+ }
+
+ public ProfilsParser() throws SAXException, ParserConfigurationException, FactoryConfigurationError {
+ super(new Mapping(),true, FactoryProvider.getSaxParserFactory());
+ }
+
+
+
+ private static class Mapping extends HashMap<QName, Class> {
+ public Mapping() {
+ put(XEMELIOS_PROFILS, ProfilsModel.class);
+ put(ProfilModel.QN, ProfilModel.class);
+ put(ComponentModel.QN, ComponentModel.class);
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.updater.script.config;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import javax.xml.namespace.QName;
+
+public class ComponentModel implements XmlMarshallable {
+ public static final transient String TAG = "component";
+ public static final transient QName QN = new QName(TAG);
+
+ private String id, version, description;
+
+ public ComponentModel(QName tagName) {
+ super();
+ }
+ public ComponentModel(String id, String version, String description) {
+ this(QN);
+ this.id=id;
+ this.version=version;
+ this.description=description;
+ }
+
+ public void addCharacterData(String cData) throws SAXException { }
+
+ public void addChild(XmlMarshallable child, QName tagName) throws SAXException { }
+
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ id = attributes.getValue("id");
+ version = attributes.getValue("version");
+ description = attributes.getValue("description");
+ return this;
+ }
+
+ public void marshall(XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("id",id);
+ output.addAttribute("version",version);
+ output.addAttribute("description",description);
+ output.endTag(TAG);
+ }
+
+ public void validate() throws InvalidXmlDefinition { }
+
+ @Override
+ public ComponentModel clone() {
+ return this;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+ @Override
+ public boolean equals(Object o) {
+ if(o instanceof ComponentModel) {
+ ComponentModel cm = (ComponentModel)o;
+ return cm.getId().equals(getId());
+ }
+ return false;
+ }
+
+ public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
+ return null;
+ }
+
+ public QName getQName() {
+ return QN;
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.updater.script.config;
+
+import java.util.HashMap;
+
+import javax.xml.parsers.FactoryConfigurationError;
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.xml.sax.SAXException;
+
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshalParser;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
+import javax.xml.namespace.QName;
+
+public class ComponentsParser extends XmlMarshalParser {
+
+ public ComponentsParser() throws SAXException, ParserConfigurationException, FactoryConfigurationError {
+ super(new Mapping(),true, FactoryProvider.getSaxParserFactory());
+ }
+
+ private static class Mapping extends HashMap<QName,Class> {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 3617293411154145847L;
+
+ public Mapping() {
+ put(XemeliosComponentModel.QN,XemeliosComponentModel.class);
+ put(ComponentModel.QN,ComponentModel.class);
+ }
+ }
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.updater.script.config;
+
+import java.util.ArrayList;
+import java.util.Hashtable;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import javax.xml.namespace.QName;
+
+public class XemeliosComponentModel implements XmlMarshallable {
+ public static final transient String TAG = "xemelios-components";
+ public static final transient QName QN =new QName(TAG);
+ private ArrayList<ComponentModel> components;
+ private Hashtable<String,ComponentModel> compsById;
+
+ public XemeliosComponentModel(QName tagName) {
+ super();
+ components = new ArrayList<ComponentModel>();
+ compsById = new Hashtable<String,ComponentModel>();
+ }
+
+ public void addCharacterData(String cData) throws SAXException { }
+
+ public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
+ ComponentModel cm = (ComponentModel)child;
+ components.add(cm);
+ compsById.put(cm.getId(),cm);
+ }
+
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ return this;
+ }
+
+ public void marshall(XmlOutputter output) {
+ output.startTag(TAG);
+ for(ComponentModel cm:components) cm.marshall(output);
+ output.endTag(TAG);
+ }
+
+ public void validate() throws InvalidXmlDefinition {
+ }
+
+ @Override
+ public XemeliosComponentModel clone() {
+ return this;
+ }
+
+ public ArrayList<ComponentModel> getComponents() {
+ return components;
+ }
+
+ public String getComponentVersion(String id) {
+ ComponentModel cm = compsById.get(id);
+ if(cm==null) return null;
+ return cm.getVersion();
+ }
+ public void remove(String id) {
+ ComponentModel cm = compsById.get(id);
+ if(cm!=null) components.remove(cm);
+ compsById.remove(id);
+ }
+
+ public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
+ return null;
+ }
+
+ public QName getQName() {
+ return QN;
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.updater.ui;
+
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.util.Vector;
+
+import javax.swing.JDialog;
+
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.xemelios.updater.config.ComponentModel;
+import fr.gouv.finances.cp.xemelios.updater.config.FileListModel;
+
+/**
+ *
+ * @author chm
+ */
+public class DlgComponentDetail extends javax.swing.JDialog {
+ /**
+ *
+ */
+ private static final long serialVersionUID = -2917904079172668916L;
+ private ComponentModel cm;
+
+ /** Creates new form NewJDialog */
+ public DlgComponentDetail(JDialog parent, ComponentModel cm) {
+ super(parent, false);
+ this.cm=cm;
+ initComponents();
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
+ private void initComponents() {
+ lblName = new javax.swing.JLabel();
+ vlName = new javax.swing.JLabel();
+ lblId = new javax.swing.JLabel();
+ lblVersion = new javax.swing.JLabel();
+ lblDesc = new javax.swing.JLabel();
+ jScrollPane1 = new javax.swing.JScrollPane();
+ txtDesc = new javax.swing.JTextArea();
+ lblDepends = new javax.swing.JLabel();
+ jScrollPane2 = new javax.swing.JScrollPane();
+ lstDepends = new javax.swing.JList();
+ vlId = new javax.swing.JLabel();
+ vlVersion = new javax.swing.JLabel();
+ lblFiles = new javax.swing.JLabel();
+ jScrollPane3 = new javax.swing.JScrollPane();
+ lstFiles = new javax.swing.JList();
+ pbClose = new javax.swing.JButton();
+
+ setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+ lblName.setText("Nom");
+
+ vlName.setFont(new java.awt.Font("Dialog", 0, 12));
+ vlName.setText(cm.getName());
+
+ lblId.setText("ID");
+
+ lblVersion.setText("Version");
+
+ lblDesc.setText("Description");
+
+ jScrollPane1.setBackground(javax.swing.UIManager.getDefaults().getColor("PropSheet.setBackground"));
+ jScrollPane1.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
+ txtDesc.setBackground(javax.swing.UIManager.getDefaults().getColor("ComboBox.background"));
+ txtDesc.setColumns(20);
+ txtDesc.setEditable(false);
+ txtDesc.setLineWrap(true);
+ txtDesc.setWrapStyleWord(true);
+ txtDesc.setRows(5);
+ txtDesc.setText(cm.getDescription().getText());
+ jScrollPane1.setViewportView(txtDesc);
+ lblConfig = new javax.swing.JLabel();
+ dfConfiguration = new javax.swing.JTextField();
+
+ lblDepends.setText("Dépendances");
+
+ lstDepends.setFont(new java.awt.Font("Dialog", 0, 12));
+ if(cm.getRequires()!=null && cm.getRequires().getComponents()!=null) {
+ lstDepends.setListData(cm.getRequires().getComponents().toArray());
+ }
+ jScrollPane2.setViewportView(lstDepends);
+
+ vlId.setFont(new java.awt.Font("Dialog", 0, 12));
+ vlId.setText(cm.getId());
+
+ vlVersion.setFont(new java.awt.Font("Dialog", 0, 12));
+ vlVersion.setText(cm.getRelease().getV());
+
+ lblFiles.setText("Fichiers");
+
+ lstFiles.setFont(new java.awt.Font("Dialog", 0, 12));
+ Vector<XmlMarshallable> files = new Vector<XmlMarshallable>();
+ for(FileListModel flm:cm.getFileLists()) {
+ for(XmlMarshallable fm:flm.getFiles()) {
+ files.add(fm);
+ }
+ }
+ lstFiles.setListData(files);
+ jScrollPane3.setViewportView(lstFiles);
+
+ pbClose.setText("Fermer");
+ pbClose.addActionListener(new ActionListener() {
+ public void actionPerformed(ActionEvent evt) {
+ setVisible(false);
+ }
+ });
+
+ lblConfig.setText("Configurateur");
+
+ dfConfiguration.setEditable(false);
+ dfConfiguration.setText(cm.getConfiguration()!=null && cm.getConfiguration().getClassName()!=null?cm.getConfiguration().getClassName():"N/A");
+
+ org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(lblName)
+ .add(lblId)
+ .add(lblVersion))
+ .add(17, 17, 17)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(jScrollPane3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE)
+ .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE)
+ .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE)
+ .add(vlVersion)
+ .add(vlId)
+ .add(vlName)
+ .add(dfConfiguration, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE))
+ .addContainerGap())
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(lblConfig)
+ .addContainerGap(244, Short.MAX_VALUE))
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(lblFiles)
+ .addContainerGap(283, Short.MAX_VALUE))
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
+ .add(130, 130, 130)
+ .add(pbClose)
+ .add(136, 136, 136))
+ .add(layout.createSequentialGroup()
+ .add(12, 12, 12)
+ .add(lblDesc)
+ .addContainerGap(259, Short.MAX_VALUE))
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(lblDepends)
+ .addContainerGap(248, Short.MAX_VALUE))
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(layout.createSequentialGroup()
+ .addContainerGap()
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(lblName)
+ .add(vlName))
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(lblId)
+ .add(vlId))
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
+ .add(lblVersion)
+ .add(vlVersion))
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(lblDesc)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(lblDepends)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 89, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(lblFiles)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 93, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .add(8, 8, 8)
+ .add(lblConfig)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(dfConfiguration, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 31, Short.MAX_VALUE)
+ .add(pbClose)
+ .addContainerGap())
+ );
+ pack();
+ setLocationRelativeTo(getOwner());
+ setVisible(true);
+ }// </editor-fold>
+
+
+ // Variables declaration - do not modify
+ private javax.swing.JLabel vlVersion;
+ private javax.swing.JList lstFiles;
+ private javax.swing.JScrollPane jScrollPane1;
+ private javax.swing.JScrollPane jScrollPane2;
+ private javax.swing.JScrollPane jScrollPane3;
+ private javax.swing.JLabel lblConfig;
+ private javax.swing.JLabel lblDepends;
+ private javax.swing.JLabel lblDesc;
+ private javax.swing.JLabel lblFiles;
+ private javax.swing.JLabel lblId;
+ private javax.swing.JLabel lblName;
+ private javax.swing.JLabel lblVersion;
+ private javax.swing.JList lstDepends;
+ private javax.swing.JButton pbClose;
+ private javax.swing.JTextArea txtDesc;
+ private javax.swing.JLabel vlId;
+ private javax.swing.JLabel vlName;
+ private javax.swing.JTextField dfConfiguration;
+ // End of variables declaration
+
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.5" maxVersion="1.7" type="org.netbeans.modules.form.forminfo.JDialogFormInfo">
+ <Properties>
+ <Property name="defaultCloseOperation" type="int" value="2"/>
+ </Properties>
+ <SyntheticProperties>
+ <SyntheticProperty name="formSizePolicy" type="int" value="1"/>
+ </SyntheticProperties>
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" attributes="0">
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" attributes="0">
+ <Group type="103" groupAlignment="0" max="-2" attributes="0">
+ <Component id="jLabel1" alignment="1" min="-2" pref="53" max="-2" attributes="0"/>
+ <Component id="jLabel3" alignment="0" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace type="unrelated" min="-2" max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="jLabelDescription" pref="354" max="32767" attributes="0"/>
+ <Group type="102" alignment="0" attributes="0">
+ <Component id="jTextFieldSite" pref="336" max="32767" attributes="0"/>
+ <EmptySpace min="-2" pref="0" max="-2" attributes="0"/>
+ <Component id="pbSearchExistingComponent" min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Component id="jButtonRechercher" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <Group type="102" alignment="1" attributes="0">
+ <Component id="jButtonEnregistrer" min="-2" max="-2" attributes="0"/>
+ <EmptySpace type="separate" max="-2" attributes="0"/>
+ <Component id="jButtonFermer" min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="jLabel1" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="jTextFieldSite" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="jButtonRechercher" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="pbSearchExistingComponent" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace type="separate" max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="1" attributes="0">
+ <Group type="102" attributes="0">
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="jLabel3" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="jLabelDescription" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace min="-2" pref="44" max="-2" attributes="0"/>
+ </Group>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="jButtonFermer" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="jButtonEnregistrer" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ <EmptySpace max="32767" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Component class="javax.swing.JLabel" name="jLabel1">
+ <Properties>
+ <Property name="font" type="java.awt.Font" editor="org.netbeans.modules.form.editors2.FontEditor">
+ <FontInfo relative="true">
+ <Font component="jLabel1" property="font" relativeSize="true" size="0"/>
+ </FontInfo>
+ </Property>
+ <Property name="text" type="java.lang.String" value="Site"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JLabel" name="jLabel3">
+ <Properties>
+ <Property name="font" type="java.awt.Font" editor="org.netbeans.modules.form.editors2.FontEditor">
+ <FontInfo relative="true">
+ <Font component="jLabel3" property="font" relativeSize="true" size="0"/>
+ </FontInfo>
+ </Property>
+ <Property name="text" type="java.lang.String" value="Description"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JButton" name="jButtonEnregistrer">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Enregistrer"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButtonEnregistrerActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="jButtonFermer">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Fermer"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButtonFermerActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JTextField" name="jTextFieldSite">
+ <Properties>
+ <Property name="font" type="java.awt.Font" editor="org.netbeans.modules.form.editors2.FontEditor">
+ <FontInfo relative="true">
+ <Font component="jTextFieldSite" property="font" relativeSize="true" size="0"/>
+ </FontInfo>
+ </Property>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JButton" name="jButtonRechercher">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Rechercher"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButtonRechercherActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JLabel" name="jLabelDescription">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Description"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JButton" name="pbSearchExistingComponent">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="..."/>
+ <Property name="toolTipText" type="java.lang.String" value="Rechercher un composant connu"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbSearchExistingComponentActionPerformed"/>
+ </Events>
+ </Component>
+ </SubComponents>
+</Form>
--- /dev/null
+/*
+ * Copyright
+ * 2010 axYus - www.axyus.com
+ * 2010 F.Nhieu - franck.nhieu@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.updater.ui;
+
+import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
+import fr.gouv.finances.cp.xemelios.updater.installed.InstalledModel;
+import fr.gouv.finances.cp.xemelios.updater.profils.ComponentModel;
+import fr.gouv.finances.cp.xemelios.updater.update.UpdateModel;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
+import javax.swing.JFrame;
+import javax.swing.JOptionPane;
+import org.apache.log4j.Logger;
+import java.awt.event.ActionEvent;
+import java.awt.event.KeyEvent;
+import java.io.InputStream;
+import java.net.URL;
+import javax.swing.AbstractAction;
+import javax.swing.JComponent;
+import javax.swing.JRootPane;
+import javax.swing.KeyStroke;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import org.w3c.dom.Document;
+
+public class DlgComposantEdition extends javax.swing.JDialog {
+
+ private AbstractAction escapeAction;
+ private ComponentModel cm;
+ private UpdateModel um;
+ private static Logger logger = Logger.getLogger(DlgComposantEdition.class);
+ private String InstalledModelFileLocation;
+ private String environement;
+ private InstalledModel im;
+
+ public DlgComposantEdition(JFrame parent, ComponentModel cm) {
+ super(parent, true);
+ this.cm = cm;
+ initComponents();
+ jTextFieldSite.setText(cm.getUri());
+ jLabelDescription.setText(cm.getDescription());
+ jButtonEnregistrer.setEnabled(false);
+ }
+
+ @Override
+ protected JRootPane createRootPane() {
+ KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0);
+ JRootPane rp = new JRootPane();
+ escapeAction = new AbstractAction("Fermer") {
+ private static final long serialVersionUID = 1L;
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ jButtonFermerActionPerformed(evt);
+ }
+ };
+ rp.registerKeyboardAction(escapeAction,"TOTOTOTO",ks,JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
+ }
+
+ public void setInstalledModelFileLocation(String InstalledModelFileLocation) {
+ this.InstalledModelFileLocation = InstalledModelFileLocation;
+ try {
+ im = InstalledModel.readFromFile(InstalledModelFileLocation);
+ im.setFileLocation(InstalledModelFileLocation);
+ } catch (Exception ex) {
+ logger.error("while loading installedComponents", ex);
+ }
+ }
+
+ public void setEnvironement(String environement) {
+ this.environement = environement;
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ @SuppressWarnings("unchecked")
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ jLabel1 = new javax.swing.JLabel();
+ jLabel3 = new javax.swing.JLabel();
+ jButtonEnregistrer = new javax.swing.JButton();
+ jButtonFermer = new javax.swing.JButton();
+ jTextFieldSite = new javax.swing.JTextField();
+ jButtonRechercher = new javax.swing.JButton();
+ jLabelDescription = new javax.swing.JLabel();
+ pbSearchExistingComponent = new javax.swing.JButton();
+
+ setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+
+ jLabel1.setFont(jLabel1.getFont());
+ jLabel1.setText("Site");
+
+ jLabel3.setFont(jLabel3.getFont());
+ jLabel3.setText("Description");
+
+ jButtonEnregistrer.setText("Enregistrer");
+ jButtonEnregistrer.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ jButtonEnregistrerActionPerformed(evt);
+ }
+ });
+
+ jButtonFermer.setText("Fermer");
+ jButtonFermer.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ jButtonFermerActionPerformed(evt);
+ }
+ });
+
+ jTextFieldSite.setFont(jTextFieldSite.getFont());
+
+ jButtonRechercher.setText("Rechercher");
+ jButtonRechercher.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ jButtonRechercherActionPerformed(evt);
+ }
+ });
+
+ jLabelDescription.setText("Description");
+
+ pbSearchExistingComponent.setText("...");
+ pbSearchExistingComponent.setToolTipText("Rechercher un composant connu");
+ pbSearchExistingComponent.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbSearchExistingComponentActionPerformed(evt);
+ }
+ });
+
+ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
+ .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addComponent(jLabel3))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(jLabelDescription, javax.swing.GroupLayout.DEFAULT_SIZE, 354, Short.MAX_VALUE)
+ .addGroup(layout.createSequentialGroup()
+ .addComponent(jTextFieldSite, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE)
+ .addGap(0, 0, 0)
+ .addComponent(pbSearchExistingComponent)))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(jButtonRechercher))
+ .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
+ .addComponent(jButtonEnregistrer)
+ .addGap(18, 18, 18)
+ .addComponent(jButtonFermer)))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(jLabel1)
+ .addComponent(jTextFieldSite, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addComponent(jButtonRechercher)
+ .addComponent(pbSearchExistingComponent))
+ .addGap(18, 18, 18)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
+ .addGroup(layout.createSequentialGroup()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(jLabel3)
+ .addComponent(jLabelDescription))
+ .addGap(44, 44, 44))
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(jButtonFermer)
+ .addComponent(jButtonEnregistrer)))
+ .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ );
+
+ pack();
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void jButtonFermerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonFermerActionPerformed
+ // TODO add your handling code here:
+ this.setVisible(false);
+ }//GEN-LAST:event_jButtonFermerActionPerformed
+
+ private void jButtonRechercherActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRechercherActionPerformed
+ try {
+ // TODO add your handling code here:
+ String URI = jTextFieldSite.getText();
+ ComponentModel cml = new ComponentModel(URI);
+ um = UpdateModel.loadModel(cml,environement);
+ // à ce statde, le fichier update.xml a bien été chargé
+ // on vérifie s'il n'existe deja pas dans la liste des composants
+ // déjà installé seulement dans le cas d'un AJOUT
+ if(cm.getUri()==null) {
+ try {
+ if(im.exists(new ComponentModel(URI))) {
+ String msg = "Composant '"+um.getDescription()+"' déjà existant dans la liste des abonnements";
+ JOptionPane.showMessageDialog(this, msg, "Attention", JOptionPane.WARNING_MESSAGE);
+ return;
+ }
+ } catch(Exception ex) {
+ logger.error(ex);
+ DisplayExceptionDlg exdlg = new DisplayExceptionDlg(ex);
+ return;
+ }
+ }
+ // TOUT est OK, on prépare les controles pour l'enregistrement
+ jLabelDescription.setText(um.getDescription());
+ jButtonEnregistrer.setEnabled(true);
+ String msg = "Composant '"+um.getDescription()+"' ("+um.getLast_version()+") trouvé";
+ JOptionPane.showMessageDialog(this, msg, "Succès", JOptionPane.INFORMATION_MESSAGE);
+ } catch (Exception ex) {
+ JOptionPane.showMessageDialog(this, "Aucun composant n'a été trouvé à cette adresse", "Erreur", JOptionPane.ERROR_MESSAGE);
+ logger.debug(ex);
+ }
+ }//GEN-LAST:event_jButtonRechercherActionPerformed
+
+ private void jButtonEnregistrerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEnregistrerActionPerformed
+ InstalledModel newInstalledComponents;
+ try {
+ // TODO add your handling code here:
+ newInstalledComponents = InstalledModel.readFromFile(InstalledModelFileLocation);
+ newInstalledComponents.setFileLocation(InstalledModelFileLocation);
+ } catch (Exception ex) {
+ logger.error(ex);
+ DisplayExceptionDlg exdlg = new DisplayExceptionDlg(ex);
+ return;
+ }
+
+ ComponentModel newcm = new ComponentModel();
+ newcm.setUri(jTextFieldSite.getText());
+ newcm.setDescription(um.getDescription());
+ newcm.setEditable(true);
+
+ if(cm.getUri()!=null) {
+ // MODE EDITION, on efface l'ancienne entrée
+ int old_cm_idx = newInstalledComponents.getComponentIdx(cm.getUri());
+ logger.debug("idx remove="+old_cm_idx);
+ logger.debug("old component UUID (read)="+newInstalledComponents.getComponents().get(old_cm_idx).getUUID().toString());
+ logger.debug("old component URI (read)="+newInstalledComponents.getComponents().get(old_cm_idx).getUri());
+ //im.getComponents().remove(old_cm_idx);
+ newInstalledComponents.removeComponent(cm.getUri());
+ }
+
+ try {
+ newInstalledComponents.addComponent(newcm);
+ newInstalledComponents.saveInstalledModel();
+ this.setVisible(false);
+ } catch (Exception ex) {
+ if(!InstalledModel.ALLREADY_EXISTS.equals(ex.getMessage())) {
+ logger.error(ex);
+ DisplayExceptionDlg exdlg = new DisplayExceptionDlg(ex);
+ }
+ }
+ }//GEN-LAST:event_jButtonEnregistrerActionPerformed
+
+ private void pbSearchExistingComponentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbSearchExistingComponentActionPerformed
+ DocumentBuilderFactory domFactory = FactoryProvider.getDocumentBuilderFactory();
+ try {
+ DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
+ InputStream is = new URL("http://xemelios.org/updatesV5/existing-components.xml").openStream();
+ Document dom = domBuilder.parse(is);
+ DlgExistingComponents dlg = new DlgExistingComponents(this, dom, im);
+ if(dlg.run()) {
+ String url = dlg.getRetUrl();
+ jTextFieldSite.setText(url);
+ jButtonRechercher.doClick();
+ }
+ is.close();
+ } catch(Exception ex) {
+ JOptionPane.showMessageDialog(this, "Impossible de récupérer la liste des composants connus.","Attention",JOptionPane.WARNING_MESSAGE);
+ logger.error("while retreiving existing components list", ex);
+ }
+ }//GEN-LAST:event_pbSearchExistingComponentActionPerformed
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JButton jButtonEnregistrer;
+ private javax.swing.JButton jButtonFermer;
+ private javax.swing.JButton jButtonRechercher;
+ private javax.swing.JLabel jLabel1;
+ private javax.swing.JLabel jLabel3;
+ private javax.swing.JLabel jLabelDescription;
+ private javax.swing.JTextField jTextFieldSite;
+ private javax.swing.JButton pbSearchExistingComponent;
+ // End of variables declaration//GEN-END:variables
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2010 axYus - www.axyus.com
+ * 2010 F.Nhieu - franck.nhieu@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.updater.ui;
+
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import java.awt.event.ActionEvent;
+import java.awt.event.KeyEvent;
+import javax.swing.AbstractAction;
+import javax.swing.JComponent;
+import javax.swing.JRootPane;
+import javax.swing.KeyStroke;
+
+/**
+ *
+ * @author franck.nhieu
+ */
+public class DlgComposants extends javax.swing.JDialog {
+ private AbstractAction escapeAction;
+
+ public DlgComposants(java.awt.Frame parent, boolean modal) {
+ super(parent, modal);
+ initComponents();
+ setLocationRelativeTo(parent);
+ }
+
+ @Override
+ protected JRootPane createRootPane() {
+ KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0);
+ JRootPane rp = new JRootPane();
+ escapeAction = new AbstractAction("Fermer") {
+ private static final long serialVersionUID = 1L;
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ jButtonFermerActionPerformed(evt);
+ }
+ };
+ rp.registerKeyboardAction(escapeAction,"TOTOTOTO",ks,JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
+ }
+
+ private void initComponents() {
+
+ jPanel1 = new PnlComposants(MainWindow.getInstance().getEnvProperties());
+ jSeparator1 = new javax.swing.JSeparator();
+ jButtonFermer = new javax.swing.JButton();
+
+ setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+
+ javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
+ jPanel1Layout.setHorizontalGroup(
+ jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGap(0, 0, Short.MAX_VALUE)
+ );
+ jPanel1Layout.setVerticalGroup(
+ jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGap(0, 0, Short.MAX_VALUE)
+ );
+
+ jButtonFermer.setText("Fermer");
+ jButtonFermer.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ jButtonFermerActionPerformed(evt);
+ }
+ });
+
+ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
+ .addGap(0, 0, 0)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
+ .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE))
+ .addGap(0, 0, 0))
+ .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
+ .addContainerGap(323, Short.MAX_VALUE)
+ .addComponent(jButtonFermer)
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
+ .addGap(0, 0, 0)
+ .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addGap(0, 0, 0)
+ .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(jButtonFermer)
+ .addContainerGap())
+ );
+
+ pack();
+ }// </editor-fold>
+
+ private void jButtonFermerActionPerformed(java.awt.event.ActionEvent evt) {
+ setVisible(false);
+ }
+
+ private javax.swing.JButton jButtonFermer;
+ private javax.swing.JPanel jPanel1;
+ private javax.swing.JSeparator jSeparator1;
+
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.3" maxVersion="1.7" type="org.netbeans.modules.form.forminfo.JDialogFormInfo">
+ <Properties>
+ <Property name="defaultCloseOperation" type="int" value="2"/>
+ </Properties>
+ <SyntheticProperties>
+ <SyntheticProperty name="formSizePolicy" type="int" value="1"/>
+ </SyntheticProperties>
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="1" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="1" attributes="0">
+ <Component id="jScrollPane1" alignment="0" pref="452" max="32767" attributes="0"/>
+ <Group type="102" alignment="1" attributes="0">
+ <Component id="pbSelect" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="pbCancel" min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="1" attributes="0">
+ <EmptySpace min="-2" pref="13" max="-2" attributes="0"/>
+ <Component id="jScrollPane1" pref="173" max="32767" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="3" attributes="0">
+ <Component id="pbCancel" alignment="3" min="-2" max="-2" attributes="0"/>
+ <Component id="pbSelect" alignment="3" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Component class="javax.swing.JButton" name="pbCancel">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Fermer"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbCancelActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="pbSelect">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Sélectionner"/>
+ <Property name="enabled" type="boolean" value="false"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="pbSelectActionPerformed"/>
+ </Events>
+ </Component>
+ <Container class="javax.swing.JScrollPane" name="jScrollPane1">
+ <AuxValues>
+ <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
+ </AuxValues>
+
+ <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
+ <SubComponents>
+ <Component class="org.jdesktop.swingx.JXTable" name="jXTable1">
+ <Properties>
+ <Property name="model" type="javax.swing.table.TableModel" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
+ <Connection code="model" type="code"/>
+ </Property>
+ </Properties>
+ <AuxValues>
+ <AuxValue name="JavaCodeGenerator_CreateCodeCustom" type="java.lang.String" value="createTable()"/>
+ </AuxValues>
+ </Component>
+ </SubComponents>
+ </Container>
+ </SubComponents>
+</Form>
--- /dev/null
+/*
+ * Copyright
+ * 2011 axYus - http://www.axyus.com
+ * 2011 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS_NB.
+ *
+ * XEMELIOS_NB 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 2 of the License, or
+ * (at your option) any later version.
+ *
+ * XEMELIOS_NB 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 Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with XEMELIOS_NB; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+
+package fr.gouv.finances.cp.xemelios.updater.ui;
+
+import fr.gouv.finances.cp.xemelios.updater.installed.InstalledModel;
+import fr.gouv.finances.cp.xemelios.updater.profils.ComponentModel;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
+import java.awt.event.ActionEvent;
+import java.awt.event.KeyEvent;
+import java.util.ArrayList;
+import javax.swing.AbstractAction;
+import javax.swing.JComponent;
+import javax.swing.JDialog;
+import javax.swing.JRootPane;
+import javax.swing.KeyStroke;
+import javax.swing.event.ListSelectionEvent;
+import javax.swing.event.ListSelectionListener;
+import javax.swing.table.DefaultTableModel;
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathConstants;
+import org.apache.log4j.Logger;
+import org.jdesktop.swingx.JXTable;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+
+/**
+ * Permet de visualiser les composants existants et recensés et d'en sélectionner un
+ * @author cmarchand
+ */
+public class DlgExistingComponents extends javax.swing.JDialog {
+ private static final transient Logger logger = Logger.getLogger(DlgExistingComponents.class);
+ ExistingComponentsTableModel model = null;
+ private boolean retAction = false;
+ private String retUrl;
+ private InstalledModel installed;
+ private ListSelectionListener listSelectionListener;
+
+ /** Creates new form DlgExistingComponents */
+ public DlgExistingComponents(JDialog parent, Document existingComponents, InstalledModel installed) {
+ super(parent, true);
+ this.installed = installed;
+ model = new ExistingComponentsTableModel(constructExistingComponents(existingComponents));
+ listSelectionListener = new ListSelectionListener() {
+
+ @Override
+ public void valueChanged(ListSelectionEvent e) {
+ int row = jXTable1.getSelectedRow();
+ if(row>=0)
+ pbSelect.setEnabled(!model.comps.get(row).installed);
+ else
+ pbSelect.setEnabled(false);
+ }
+ };
+ initComponents();
+ model.fireTableDataChanged();
+ setLocationRelativeTo(getParent());
+ }
+ private ArrayList<ExistingComponent> constructExistingComponents(Document doc) {
+ ArrayList<ExistingComponent> ret = new ArrayList<ExistingComponent>();
+ try {
+ XPath xpath = FactoryProvider.getXPathFactory().newXPath();
+ NodeList nl = (NodeList)xpath.evaluate("/existing-components/component", doc, XPathConstants.NODESET);
+ for(int i=0;i<nl.getLength();i++) {
+ Element el = (Element)nl.item(i);
+ ExistingComponent ec = new ExistingComponent(el);
+ ec.installed = installed.exists(new ComponentModel(ec.url));
+ ret.add(ec);
+ }
+ } catch(Exception ex) {
+ logger.error("while constructing model", ex);
+ }
+ return ret;
+ }
+ public boolean run() {
+ setVisible(true);
+ return retAction;
+ }
+ @Override
+ protected JRootPane createRootPane() {
+ KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0);
+ JRootPane rp = new JRootPane();
+ AbstractAction escapeAction = new AbstractAction("Fermer") {
+ private static final long serialVersionUID = 1L;
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ pbCancelActionPerformed(evt);
+ }
+ };
+ rp.registerKeyboardAction(escapeAction,"TOTOTOTO",ks,JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
+ }
+
+ public String getRetUrl() {
+ return retUrl;
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ @SuppressWarnings("unchecked")
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ pbCancel = new javax.swing.JButton();
+ pbSelect = new javax.swing.JButton();
+ jScrollPane1 = new javax.swing.JScrollPane();
+ jXTable1 = createTable();
+
+ setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+
+ pbCancel.setText("Fermer");
+ pbCancel.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbCancelActionPerformed(evt);
+ }
+ });
+
+ pbSelect.setText("Sélectionner");
+ pbSelect.setEnabled(false);
+ pbSelect.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ pbSelectActionPerformed(evt);
+ }
+ });
+
+ jXTable1.setModel(model);
+ jScrollPane1.setViewportView(jXTable1);
+
+ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
+ .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 452, Short.MAX_VALUE)
+ .addGroup(layout.createSequentialGroup()
+ .addComponent(pbSelect)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(pbCancel)))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
+ .addGap(13, 13, 13)
+ .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(pbCancel)
+ .addComponent(pbSelect))
+ .addContainerGap())
+ );
+
+ pack();
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void pbCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbCancelActionPerformed
+ setVisible(false);
+ }//GEN-LAST:event_pbCancelActionPerformed
+
+ private void pbSelectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbSelectActionPerformed
+ int row = jXTable1.getSelectedRow();
+ if(row>=0) {
+ ExistingComponent ec = model.comps.get(row);
+ if(!ec.installed) {
+ retAction = true;
+ retUrl = ec.url;
+ setVisible(false);
+ }
+ }
+ }//GEN-LAST:event_pbSelectActionPerformed
+
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JScrollPane jScrollPane1;
+ private org.jdesktop.swingx.JXTable jXTable1;
+ private javax.swing.JButton pbCancel;
+ private javax.swing.JButton pbSelect;
+ // End of variables declaration//GEN-END:variables
+
+ protected JXTable createTable() {
+ JXTable table = new JXTable() {
+ @Override
+ public void valueChanged(ListSelectionEvent e) {
+ super.valueChanged(e);
+ listSelectionListener.valueChanged(e);
+ }
+ };
+ return table;
+ }
+
+ private class ExistingComponentsTableModel extends DefaultTableModel {
+ private ArrayList<ExistingComponent> comps;
+ public ExistingComponentsTableModel(ArrayList<ExistingComponent> comps) {
+ super();
+ this.comps = comps;
+ }
+
+ @Override
+ public int getRowCount() {
+ if(comps==null) return 0;
+ return comps.size();
+ }
+
+ @Override
+ public Class<?> getColumnClass(int columnIndex) {
+ if(columnIndex==0) return Boolean.class;
+ else return String.class;
+ }
+
+ @Override
+ public String getColumnName(int column) {
+ switch(column) {
+ case 0: return "Installé";
+ case 1: return "Description";
+ default: return "URL";
+ }
+ }
+
+ @Override
+ public Object getValueAt(int row, int column) {
+ ExistingComponent ec = comps.get(row);
+ switch(column) {
+ case 0: return ec.installed;
+ case 1: return ec.description;
+ default: return ec.url;
+ }
+ }
+
+ @Override
+ public boolean isCellEditable(int row, int column) {
+ return false;
+ }
+
+ @Override
+ public int getColumnCount() {
+ return 3;
+ }
+
+
+ }
+ private class ExistingComponent {
+ private String url;
+ private String description;
+ private boolean installed;
+ public ExistingComponent(Element el) {
+ url = el.getElementsByTagName("url").item(0).getTextContent();
+ description = el.getElementsByTagName("description").item(0).getTextContent();
+ }
+ }
+}
--- /dev/null
+<?xml version="1.1" encoding="UTF-8" ?>
+
+<Form version="1.5" maxVersion="1.7" type="org.netbeans.modules.form.forminfo.JDialogFormInfo">
+ <Properties>
+ <Property name="defaultCloseOperation" type="int" value="2"/>
+ </Properties>
+ <SyntheticProperties>
+ <SyntheticProperty name="formSizePolicy" type="int" value="1"/>
+ </SyntheticProperties>
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="jScrollPane1" alignment="0" pref="417" max="32767" attributes="0"/>
+ <Component id="jLabelTitre" alignment="0" min="-2" max="-2" attributes="0"/>
+ <Component id="jButtonFermer" alignment="1" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="jLabelTitre" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="jScrollPane1" pref="334" max="32767" attributes="0"/>
+ <EmptySpace min="-2" pref="11" max="-2" attributes="0"/>
+ <Component id="jButtonFermer" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Component class="javax.swing.JLabel" name="jLabelTitre">
+ <Properties>
+ <Property name="font" type="java.awt.Font" editor="org.netbeans.modules.form.editors2.FontEditor">
+ <FontInfo relative="true">
+ <Font bold="true" component="jLabelTitre" property="font" relativeSize="true" size="0"/>
+ </FontInfo>
+ </Property>
+ <Property name="text" type="java.lang.String" value="Liste des composants du profil"/>
+ </Properties>
+ </Component>
+ <Container class="javax.swing.JScrollPane" name="jScrollPane1">
+ <AuxValues>
+ <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
+ </AuxValues>
+
+ <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
+ <SubComponents>
+ <Component class="org.jdesktop.swingx.JXTable" name="jXTableComposants">
+ <Properties>
+ <Property name="model" type="javax.swing.table.TableModel" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
+ <Connection code="cTableModel" type="code"/>
+ </Property>
+ </Properties>
+ </Component>
+ </SubComponents>
+ </Container>
+ <Component class="javax.swing.JButton" name="jButtonFermer">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Fermer"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButtonFermerActionPerformed"/>
+ </Events>
+ </Component>
+ </SubComponents>
+</Form>
--- /dev/null
+/*
+ * Copyright
+ * 2010 axYus - www.axyus.com
+ * 2010 F.Nhieu - franck.nhieu@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.updater.ui;
+
+import fr.gouv.finances.cp.xemelios.updater.profils.ComponentModel;
+import fr.gouv.finances.cp.xemelios.updater.profils.ProfilModel;
+import java.awt.Frame;
+import java.awt.event.ActionEvent;
+import java.awt.event.KeyEvent;
+import java.util.ArrayList;
+import javax.swing.AbstractAction;
+import javax.swing.JComponent;
+import javax.swing.JRootPane;
+import javax.swing.KeyStroke;
+import javax.swing.table.AbstractTableModel;
+import org.apache.log4j.Logger;
+
+public class DlgProfilDetail extends javax.swing.JDialog {
+
+ private static Logger logger = Logger.getLogger(DlgProfilDetail.class);
+ private ComposantsTableModel cTableModel = new ComposantsTableModel();
+ private AbstractAction escapeAction;
+
+ public DlgProfilDetail(Frame owner, ProfilModel pm) {
+ super(owner, pm.getDescription(), true);
+ cTableModel.setComposants(pm.getComponents());
+ initComponents();
+ jXTableComposants.setShowGrid(false);
+
+ jLabelTitre.setText("Liste des composants du profil \"" + pm.getDescription() + "\"");
+ setLocationRelativeTo(owner);
+ }
+
+ @Override
+ protected JRootPane createRootPane() {
+ KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0);
+ JRootPane rp = new JRootPane();
+ escapeAction = new AbstractAction("Fermer") {
+ private static final long serialVersionUID = 1L;
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ jButtonFermerActionPerformed(evt);
+ }
+ };
+ rp.registerKeyboardAction(escapeAction,"TOTOTOTO",ks,JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
+ }
+
+ private class ComposantsTableModel extends AbstractTableModel {
+
+ public ArrayList<ComponentModel> composants;
+
+ public ComposantsTableModel() {
+ this.composants = new ArrayList<ComponentModel>();
+ }
+
+ @Override
+ public int getRowCount() {
+ return composants.size();
+ }
+
+ @Override
+ public int getColumnCount() {
+ return 1;
+ }
+
+ @Override
+ public Object getValueAt(int rowIndex, int columnIndex) {
+ return composants.get(rowIndex).getDescription();
+ }
+
+ @Override
+ public Class<?> getColumnClass(int columnIndex) {
+ return String.class;
+ }
+
+ @Override
+ public String getColumnName(int column) {
+ return "Description";
+ }
+
+ @Override
+ public boolean isCellEditable(int rowIndex, int columnIndex) {
+ return false;
+ }
+
+ public void setComposants(ArrayList<ComponentModel> composants) {
+ this.composants = composants;
+ }
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ @SuppressWarnings("unchecked")
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ jLabelTitre = new javax.swing.JLabel();
+ jScrollPane1 = new javax.swing.JScrollPane();
+ jXTableComposants = new org.jdesktop.swingx.JXTable();
+ jButtonFermer = new javax.swing.JButton();
+
+ setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+
+ jLabelTitre.setFont(jLabelTitre.getFont().deriveFont(jLabelTitre.getFont().getStyle() | java.awt.Font.BOLD));
+ jLabelTitre.setText("Liste des composants du profil");
+
+ jXTableComposants.setModel(cTableModel);
+ jScrollPane1.setViewportView(jXTableComposants);
+
+ jButtonFermer.setText("Fermer");
+ jButtonFermer.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ jButtonFermerActionPerformed(evt);
+ }
+ });
+
+ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 417, Short.MAX_VALUE)
+ .addComponent(jLabelTitre)
+ .addComponent(jButtonFermer, javax.swing.GroupLayout.Alignment.TRAILING))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(jLabelTitre)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 334, Short.MAX_VALUE)
+ .addGap(11, 11, 11)
+ .addComponent(jButtonFermer)
+ .addContainerGap())
+ );
+
+ pack();
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void jButtonFermerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonFermerActionPerformed
+ // TODO add your handling code here:
+ setVisible(false);
+ }//GEN-LAST:event_jButtonFermerActionPerformed
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JButton jButtonFermer;
+ private javax.swing.JLabel jLabelTitre;
+ private javax.swing.JScrollPane jScrollPane1;
+ private org.jdesktop.swingx.JXTable jXTableComposants;
+ // End of variables declaration//GEN-END:variables
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.updater.ui;
+
+import fr.gouv.finances.cp.xemelios.updater.UpdaterUtil;
+import java.awt.BorderLayout;
+import java.awt.Container;
+import java.awt.Dimension;
+import java.awt.FlowLayout;
+import java.awt.Frame;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.MouseEvent;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.security.NoSuchAlgorithmException;
+import java.text.DateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.Vector;
+
+import javax.swing.AbstractAction;
+import javax.swing.Icon;
+import javax.swing.ImageIcon;
+import javax.swing.JButton;
+import javax.swing.JDialog;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JTabbedPane;
+import javax.swing.JTable;
+import javax.swing.JViewport;
+import javax.swing.ListSelectionModel;
+import javax.swing.UIManager;
+import javax.swing.event.ListSelectionEvent;
+import javax.swing.event.ListSelectionListener;
+import javax.swing.event.TableModelEvent;
+import javax.swing.table.AbstractTableModel;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathConstants;
+import javax.xml.xpath.XPathExpressionException;
+import javax.xml.xpath.XPathFactory;
+import javax.xml.xpath.XPathFactoryConfigurationException;
+
+import jonelo.jacksum.algorithm.AbstractChecksum;
+import jonelo.jacksum.algorithm.MD;
+
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpMethod;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.log4j.Logger;
+import org.jdesktop.swingx.JXTable;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import fr.gouv.finances.cp.utils.StartUrl;
+import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
+import fr.gouv.finances.cp.utils.ui.IhmFactory;
+import fr.gouv.finances.cp.utils.ui.SameSizeVerticalFlowLayout;
+import fr.gouv.finances.cp.utils.ui.VerticalFlowLayout;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import fr.gouv.finances.dgfip.xemelios.common.NetAccess;
+import fr.gouv.finances.dgfip.xemelios.data.DataConfigurationException;
+import fr.gouv.finances.cp.xemelios.updater.UpdaterException;
+import fr.gouv.finances.cp.xemelios.updater.config.ComponentModel;
+import fr.gouv.finances.cp.xemelios.updater.config.ComponentRefModel;
+import fr.gouv.finances.cp.xemelios.updater.config.ConfigurationModel;
+import fr.gouv.finances.cp.xemelios.updater.config.DeleteModel;
+import fr.gouv.finances.cp.xemelios.updater.config.FileListModel;
+import fr.gouv.finances.cp.xemelios.updater.config.FileModel;
+import fr.gouv.finances.cp.xemelios.updater.config.ParamModel;
+import fr.gouv.finances.cp.xemelios.updater.config.SiteModel;
+import fr.gouv.finances.cp.xemelios.updater.config.UpdateParser;
+import fr.gouv.finances.cp.xemelios.updater.config.XemeliosUpdateModel;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
+import fr.gouv.finances.dgfip.xemelios.swing.InfiniteGlassPane;
+import fr.gouv.finances.dgfip.xemelios.ui.ImageResources;
+import java.awt.Color;
+import java.awt.Cursor;
+import java.awt.Graphics;
+import java.awt.event.FocusAdapter;
+import java.awt.event.FocusEvent;
+import java.awt.event.KeyEvent;
+import java.awt.event.MouseAdapter;
+import javax.swing.Action;
+import javax.swing.Box;
+import javax.swing.JLabel;
+import javax.swing.KeyStroke;
+import javax.swing.border.EmptyBorder;
+import javax.swing.event.TableModelListener;
+import javax.swing.table.TableModel;
+import org.jdesktop.swingworker.SwingWorker;
+
+@Deprecated
+public class DlgUpdate extends JDialog {
+ /**
+ *
+ */
+ private static final long serialVersionUID = 3532748822800835233L;
+
+ private static Logger logger = Logger.getLogger(DlgUpdate.class);
+
+ private static final transient String XEMELIOS_TT = "Composant XeMeLios";
+
+ private static final transient String CONFIG_TT = "Configuration";
+
+ private static final transient String FEATURE_TT = "Fonctionnalité";
+
+ private PropertiesExpansion sysProps;
+
+ /**
+ * The already installed components
+ */
+ private ComponentHolder installedComponents;
+
+ private UpdatePanel updateTab;
+
+ /**
+ * The available-for-install components
+ */
+ private Vector<ComponentModel> updateComps = new Vector<ComponentModel>();
+ private Hashtable<String,ComponentModel> updateCompsById = new Hashtable<String,ComponentModel>();
+ private XPathFactory xpf = null;
+ private DocumentBuilderFactory domFactory;
+
+
+ public DlgUpdate(Frame owner) {
+ super(owner, "Mise à jour de XeMeLios", false);
+ try {
+ xpf = XPathFactory.newInstance(XPathFactory.DEFAULT_OBJECT_MODEL_URI);
+ domFactory = FactoryProvider.getDocumentBuilderFactory();
+ } catch(Throwable t) {
+ xpf = FactoryProvider.getXPathFactory();
+ t.printStackTrace();
+ }
+ sysProps = MainWindow.getInstance().getEnvProperties();
+ initComponents();
+ }
+
+ private void initComponents() {
+ Exception initException = null;
+ try {
+ loadComponentList();
+ } catch (Exception ex) {
+ initException = ex;
+ }
+
+ JPanel mainPane = new JPanel(new BorderLayout());
+ JPanel centerPane = new JPanel(new VerticalFlowLayout());
+
+ JTabbedPane tab = new JTabbedPane(JTabbedPane.TOP, JTabbedPane.SCROLL_TAB_LAYOUT);
+ tab.addTab("Composants installés", getComponentsTab());
+ tab.addTab("Mises à jour disponibles", getUpdateTab());
+ centerPane.add(tab);
+ HyperLink releaseNotes = new HyperLink("Notes de version...","http://www.xemelios.org/release-notes.html");
+ centerPane.add(releaseNotes);
+
+ mainPane.add(centerPane, BorderLayout.CENTER);
+
+ // BOTTOM PART
+ JPanel buttonPane = new JPanel(new FlowLayout(FlowLayout.CENTER));
+ JButton pbClose = new JButton("Fermer");
+ pbClose.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(java.awt.event.ActionEvent e) {
+ setVisible(false);
+ };
+ });
+ buttonPane.add(pbClose);
+ mainPane.add(buttonPane, BorderLayout.SOUTH);
+
+ setContentPane(mainPane);
+
+ pack();
+ setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
+ setLocationRelativeTo(getParent());
+ setGlassPane(new InfiniteGlassPane());
+ setVisible(true);
+ if (initException != null)
+ new DisplayExceptionDlg(this, initException);
+ }
+
+ private JPanel getComponentsTab() {
+ JPanel ret = new JPanel();
+ JTable tbl = new JTable(new ComponentsTableModel(installedComponents));
+ ret.add(new JScrollPane(tbl));
+ return ret;
+ }
+
+ private JPanel getUpdateTab() {
+ updateTab = new UpdatePanel(this);
+ return updateTab;
+ }
+
+ private void loadUpdateList() throws Exception {
+ String prop = System.getProperty(Constants.SYS_PROP_UPDATE_SOURCE);
+ updateComps = new Vector<ComponentModel>();
+ updateFromUrl(prop);
+ ((UpdCompTableModel) (updateTab.tblComponents.getModel())).setData(updateComps);
+ updateTab.pbUpdate.setEnabled(updateComps.size()>0);
+ }
+
+ private void updateFromUrl(String urlLocation) throws Exception {
+ //URL url = new URL(urlLocation);
+ HttpClient client = NetAccess.getHttpClient(MainWindow.getInstance().getEnvProperties());
+ GetMethod meth = new GetMethod(urlLocation);
+ meth.addRequestHeader("Pragma", "no-cache");
+ int httpRet = client.executeMethod(meth);
+ if(httpRet>300) throw new Exception(meth.getStatusText());
+ InputStream is = meth.getResponseBodyAsStream();
+ UpdateParser up = new UpdateParser();
+ up.parse(is);
+ is.close();
+ XemeliosUpdateModel xum = (XemeliosUpdateModel) up.getMarshallable();
+ // logger.debug(xum.getRelease().getV());
+
+ if(xum.getXemeliosUpdates()!=null) {
+ addNewComponents(ComponentModel.XEMELIOS, xum.getXemeliosUpdates().getComponents());
+ }
+ if(xum.getConfigUpdates()!=null) {
+ addNewComponents(ComponentModel.CONFIG, xum.getConfigUpdates().getComponents());
+ }
+ if(xum.getFeaturesUpdates()!=null) {
+ addNewComponents(ComponentModel.FEATURE, xum.getFeaturesUpdates().getComponents());
+ }
+
+ if (xum.getForeignSites() != null) {
+ for (Iterator<SiteModel> it = xum.getForeignSites().getSites().iterator(); it.hasNext();) {
+ SiteModel site = it.next();
+ try {
+ updateFromUrl(site.getText());
+ } catch (IOException ioEx) {
+ JOptionPane.showMessageDialog(this, "Site de mise à jour introuvable :\n" + ioEx.getMessage(), "Erreur", JOptionPane.ERROR_MESSAGE);
+ }
+ }
+ }
+ }
+
+ private void addNewComponents(int componentType, Iterable<ComponentModel> cps) {
+ for (Iterator<ComponentModel> it = cps.iterator(); it.hasNext();) {
+ ComponentModel cm = it.next();
+ if (UpdaterUtil.compareReleases(getInstalledcomponentVersion(cm.getId()),cm.getRelease().getV()) < 0) {
+ cm.type = componentType;
+ // verify if this component is already in update
+ ComponentModel oldRelease = updateCompsById.get(cm.getId());
+ if(oldRelease!=null) {
+ updateComps.remove(oldRelease);
+ updateCompsById.remove(cm.getId());
+ }
+ updateComps.add(cm);
+ updateCompsById.put(cm.getId(),cm);
+ }
+ }
+ }
+
+ // moved to UpdaterUtil
+// private int compareReleases(String r1, String r2) {
+// String[] s1 = splitRelease(r1);
+// String[] s2 = splitRelease(r2);
+// int ret = 0;
+// for(int i=0;i<Math.min(s1.length,s2.length);i++) {
+// float a = -1f, b = -1f;
+// try {
+// a = Integer.parseInt(s1[i]);
+// } catch(Throwable t) {
+// if(s1[i].endsWith("+")) {
+// // if there is a "+" in the release number, it is a non-official release,
+// // based on the previous build number. So the "real" number is the previous + 0.5
+// try {
+// a = Integer.parseInt(s1[i].substring(0, s1[i].length()-1));
+// a += 0.5;
+// } catch(Throwable t2) {}
+// }
+// }
+// try {
+// b = Integer.parseInt(s2[i]);
+// } catch(Throwable t) {
+// if(s2[i].endsWith("+")) {
+// // if there is a "+" in the release number, it is a non-official release,
+// // based on the previous build number. So the "real" number is the previous + 0.5
+// try {
+// b = Integer.parseInt(s2[i].substring(0, s2[i].length()-1));
+// b += 0.5;
+// } catch(Throwable t2) {}
+// }
+// }
+// if(a!=-1f && b!=-1f) {
+// if(a<b) ret = -1;
+// else if(a==b) ret = 0;
+// else ret = 1;
+// } else {
+// ret = s1[i].compareTo(s2[i]);
+// }
+// if(ret!=0) {
+// return ret;
+// }
+// }
+// if(s1.length>s2.length) ret = 1;
+// else if(s1.length<s2.length) ret = -1;
+// return ret;
+// }
+ private String[] splitRelease(String r) {
+ return r.split("\\.");
+ }
+ private static String printArray(String[] s) {
+ StringBuffer sb = new StringBuffer();
+ sb.append("[");
+ for(int i=0;i<s.length;i++) {
+ sb.append("\"").append(s[i]).append("\"");
+ if(i+1<s.length) sb.append(",");
+ }
+ sb.append("]");
+ return sb.toString();
+ }
+
+ @SuppressWarnings("serial")
+ private class UpdatePanel extends JPanel {
+ JXTable tblComponents;
+
+ private DlgUpdate parent;
+
+ private JButton pbDetails;
+ private JButton pbLoad, pbUpdate, pbCheckAll;
+
+ public UpdatePanel(DlgUpdate parent) {
+ super();
+ this.parent = parent;
+ initComponents();
+ }
+
+ private void initComponents() {
+ // first state : display only a load button
+ setLayout(new BorderLayout());
+ tblComponents = new JXTable() {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ protected void configureEnclosingScrollPane() {
+ Container p = getParent();
+ if (p instanceof JViewport) {
+ Container gp = p.getParent();
+ if (gp instanceof JScrollPane) {
+ JScrollPane scrollPane = (JScrollPane) gp;
+ JViewport viewport = scrollPane.getViewport();
+ if (viewport == null || viewport.getView() != this) {
+ return;
+ }
+ scrollPane.getViewport().setScrollMode(JViewport.BACKINGSTORE_SCROLL_MODE);
+ scrollPane.setBorder(UIManager.getBorder("Table.scrollPaneBorder"));
+ }
+ }
+ }
+
+ @Override
+ public String getToolTipText(MouseEvent evt) {
+ int row = rowAtPoint(evt.getPoint());
+ int column = columnAtPoint(evt.getPoint());
+ if (column == 0) {
+ ComponentModel cm = updateComps.elementAt(row);
+ switch (cm.type) {
+ case ComponentModel.XEMELIOS:
+ return XEMELIOS_TT;
+ case ComponentModel.CONFIG:
+ return CONFIG_TT;
+ case ComponentModel.FEATURE:
+ return FEATURE_TT;
+ default:
+ return null;
+ }
+ }
+ return null;
+ }
+ };
+ tblComponents.setShowGrid(false);
+ tblComponents.setShowHorizontalLines(true);
+ tblComponents.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
+ final UpdCompTableModel model = new UpdCompTableModel(new Vector<ComponentModel>());
+ tblComponents.setModel(model);
+ tblComponents.getColumnModel().getColumn(0).setMaxWidth(20);
+// tblComponents.getColumnModel().getColumn(1).setMaxWidth(20);
+ tblComponents.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
+ @Override
+ public void valueChanged(ListSelectionEvent e) {
+ int row = tblComponents.getSelectedRow();
+ pbDetails.setEnabled(row >= 0);
+ }
+ });
+ model.addTableModelListener(new TableModelListener() {
+ @Override
+ public void tableChanged(TableModelEvent e) {
+ Object source = e.getSource();
+ if(source instanceof JTable) {
+ JTable table = (JTable)source;
+ pbCheckAll.setEnabled(table.getRowCount()>0);
+ } else if(source instanceof TableModel) {
+ TableModel tm = (TableModel)source;
+ pbCheckAll.setEnabled(tm.getRowCount()>0);
+ }
+ }
+ });
+ add(new JScrollPane(tblComponents), BorderLayout.CENTER);
+
+ JPanel buttonPane = new JPanel(new SameSizeVerticalFlowLayout(SameSizeVerticalFlowLayout.TOP));
+ pbLoad = new JButton(new ActionLoad(parent));
+ buttonPane.add(pbLoad);
+ pbDetails = new JButton("Détails");
+ pbDetails.setEnabled(false);
+ pbDetails.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ new DlgComponentDetail(DlgUpdate.this, updateComps.elementAt(tblComponents.getSelectedRow()));
+ }
+ });
+ buttonPane.add(pbDetails);
+ pbUpdate = new JButton("Installer");
+ pbUpdate.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ try {
+ pbCheckAll.doClick();
+ doUpdate();
+ } catch (Throwable t) {
+ new DisplayExceptionDlg(DlgUpdate.this, t);
+ }
+ }
+ });
+ pbUpdate.setEnabled(false);
+ buttonPane.add(pbUpdate);
+ buttonPane.add(Box.createVerticalGlue());
+ pbCheckAll = new JButton("Tout sélectionner");
+ pbCheckAll.setEnabled(false);
+ pbCheckAll.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ model.selectAll();
+ }
+ });
+// buttonPane.add(pbCheckAll);
+
+ add(buttonPane, BorderLayout.EAST);
+ setMinimumSize(new Dimension(240, 140));
+ }
+ }
+
+ protected void doUpdate() throws NoSuchAlgorithmException {
+ boolean bRet = false;
+ getGlassPane().setVisible(true);
+ // 1 - constitute component list with dependences
+ ComponentHolder ch = new ComponentHolder(updateComps);
+ try {
+ for (ComponentModel cm : updateComps) {
+ if (!cm.selected) continue;
+ ch.addComponent(cm);
+ }
+ } catch(DataConfigurationException dcEx) {
+ getGlassPane().setVisible(false);
+ JOptionPane.showMessageDialog(this,dcEx.getMessage(),"Erreur",JOptionPane.ERROR_MESSAGE);
+ return;
+ }
+ if(ch.comps.size()==0) {
+ getGlassPane().setVisible(false);
+ JOptionPane.showMessageDialog(this,"Vous devez cocher au moins un composant à installer.","Erreur",JOptionPane.ERROR_MESSAGE);
+ return;
+ }
+ for (ComponentModel cm : ch.comps) {
+ cm.selected = true;
+// logger.debug("selected:" + cm);
+ }
+ updateTab.tblComponents.tableChanged(new TableModelEvent(updateTab.tblComponents.getModel()));
+
+ Downloader downloader = new Downloader(ch);
+ try {
+// SwingUtilities.invokeLater(downloader);
+ downloader.execute();
+ bRet = downloader.get().booleanValue();
+ } catch(Exception ex) {
+ }
+ String msg = "Le téléchargement des nouveaux composants est terminé.\nPour les installer, vous devez redémarrer XeMeLios.";
+ if (bRet) {
+ updateTab.pbDetails.setEnabled(false);
+ updateTab.pbLoad.setEnabled(false);
+ updateTab.pbUpdate.setEnabled(false);
+ JOptionPane.showMessageDialog(this, msg);
+ } else {
+ if(downloader.getException()!=null) DisplayExceptionDlg.displayException(this, downloader.getException());
+ else if(downloader.getErrorMessage()!=null) JOptionPane.showMessageDialog(this,downloader.getErrorMessage(), "ERREUR",JOptionPane.ERROR_MESSAGE);
+ }
+ }
+
+ private File getLocalFileName(String filePath, String fileName) {
+ String ret = filePath;
+ int pos = ret.indexOf("${");
+ while(pos>=0) {
+ String before = ret.substring(0,pos);
+ int end = ret.indexOf("}");
+ String after = ret.substring(end+1);
+ String key = ret.substring(pos+2,end);
+ ret = before + System.getProperty(key) + after;
+ pos = ret.indexOf("${");
+ }
+ File f = new File(new File(ret),fileName);
+ if(f.exists()) return f;
+ return null;
+ }
+
+
+ @SuppressWarnings("serial")
+ private class ActionLoad extends AbstractAction {
+ private DlgUpdate dialog;
+
+ public ActionLoad(DlgUpdate dialog) {
+ super("Rechercher");
+ this.dialog = dialog;
+ }
+
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ try {
+ dialog.loadUpdateList();
+ } catch (Exception ex) {
+ new DisplayExceptionDlg(dialog, ex);
+ }
+ }
+ }
+
+ private void loadComponentList() throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
+ installedComponents = new ComponentHolder(new Vector<ComponentModel>());
+ String fileName = System.getProperty(Constants.SYS_PROP_COMPONENTS_FILENAME);
+ InputSource is = new InputSource(new FileReader(new File(fileName)));
+ // on parse avant pour etre sur de l'implementation utilise (on veut du JAXP)
+ DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
+ Document dom = domBuilder.parse(is);
+ try {
+ XPath xp = xpf.newXPath();
+// logger.error(xpf.getClass().getName());
+ Object o = xp.evaluate("//component", dom, XPathConstants.NODESET);
+ if (o instanceof NodeList) {
+ NodeList nl = (NodeList) o;
+ for (int i = 0; i < nl.getLength(); i++) {
+ Element el = (Element) nl.item(i);
+ try {
+ installedComponents.addComponent(new XemeliosComponent(el));
+ } catch(DataConfigurationException dcEx) {}
+ }
+// } else if (o instanceof List) {
+// List l = (List) o;
+// for (Object obj : l) {
+// if (obj instanceof Element) {
+// try {
+// installedComponents.addComponent(new XemeliosComponent((Element) obj));
+// } catch(DataConfigurationException dcEx) {}
+// } else {
+//// logger.debug(obj.getClass().getName());
+// Class clazz = obj.getClass();
+// Class[] interfaces = clazz.getInterfaces();
+//// for (Class c : interfaces)
+//// logger.debug("\ti:" + c.getName());
+// Class superClass = clazz.getSuperclass();
+// while (superClass != null) {
+//// logger.debug("\tsuper:" + superClass.getName());
+// superClass = superClass.getSuperclass();
+// }
+// }
+// }
+ }
+ } catch (XPathFactoryConfigurationException e) {
+ logger.error("in loadComponentList()",e);
+ }
+ }
+
+ private String getInstalledcomponentVersion(String cid) {
+ String ret = installedComponents.getComponentVersion(cid);
+ return ret == null ? "0" : ret;
+ }
+
+ private String unescapePath(String path) {
+ return sysProps.replace(path);
+ }
+
+ private class XemeliosComponent extends ComponentModel {
+ public XemeliosComponent(Element el) throws XPathExpressionException, XPathFactoryConfigurationException {
+ super(null);
+ XPath xp = xpf.newXPath();
+ setId((String) xp.evaluate("./@id", el, XPathConstants.STRING));
+ setRelease((String) xp.evaluate("./@version", el, XPathConstants.STRING));
+ setDescription((String) xp.evaluate("./@description", el, XPathConstants.STRING));
+ }
+
+ public XemeliosComponent(String cid, String version) {
+ super(null);
+ setId(cid);
+ setRelease(version);
+ }
+ }
+
+ @SuppressWarnings("serial")
+ private class ComponentsTableModel extends AbstractTableModel {
+ private Vector<ComponentModel> data = null;
+
+ public ComponentsTableModel(ComponentHolder comps) {
+ super();
+ data = new Vector<ComponentModel>();
+ this.data.addAll(comps.comps);
+ }
+
+ @Override
+ public int getRowCount() {
+ return data.size();
+ }
+
+ @Override
+ public int getColumnCount() {
+ return 2;
+ }
+
+ @Override
+ public Object getValueAt(int rowIndex, int columnIndex) {
+ ComponentModel c = data.get(rowIndex);
+ switch (columnIndex) {
+ case 0:
+ return c.getDescription().getText();
+ case 1:
+ return c.getRelease().getV();
+ }
+ return null;
+ }
+
+ @Override
+ public String getColumnName(int column) {
+ switch (column) {
+ case 0:
+ return "Composant";
+ case 1:
+ return "Version";
+ }
+ return "";
+ }
+ }
+
+ @SuppressWarnings("serial")
+ private class UpdCompTableModel extends AbstractTableModel {
+ private Vector<ComponentModel> components;
+
+ private ImageIcon xemeliosIcon, configIcon, featureIcon;
+
+ public UpdCompTableModel(Vector<ComponentModel> components) {
+ super();
+ this.components = components;
+// IhmFactory iF = IhmFactory.newInstance();
+ xemeliosIcon = IhmFactory.getIconFromResource(ImageResources.XEMELIOS_COMPONENT_ICON);
+ configIcon = IhmFactory.getIconFromResource(ImageResources.CONFIG_COMPONENT_ICON);
+ featureIcon = IhmFactory.getIconFromResource(ImageResources.FEATURE_COMPONENT_ICON);
+ }
+
+ @Override
+ public Class<?> getColumnClass(int columnIndex) {
+ switch (columnIndex) {
+ case 0:
+ return Icon.class;
+// case 1:
+// return Boolean.class;
+ case 1:
+ return String.class;
+ default:
+ return super.getColumnClass(columnIndex);
+ }
+ }
+
+ @Override
+ public boolean isCellEditable(int rowIndex, int columnIndex) {
+// ComponentModel cm = components.elementAt(rowIndex);
+// if (cm.isVisible())
+// return columnIndex == 1;
+ return false;
+ }
+
+ @Override
+ public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
+ ComponentModel cm = components.elementAt(rowIndex);
+ cm.selected = ((Boolean) aValue).booleanValue();
+ }
+
+ @Override
+ public int getColumnCount() {
+ return 2;
+ }
+
+ @Override
+ public int getRowCount() {
+ return components.size();
+ }
+
+ @Override
+ public Object getValueAt(int rowIndex, int columnIndex) {
+ ComponentModel cm = components.elementAt(rowIndex);
+ if (columnIndex == 0) {
+ switch (cm.type) {
+ case ComponentModel.XEMELIOS:
+ return xemeliosIcon;
+ case ComponentModel.CONFIG:
+ return configIcon;
+ case ComponentModel.FEATURE:
+ return featureIcon;
+ default:
+ return null;
+ }
+// } else if (columnIndex == 1) {
+// return new Boolean(cm.selected);
+ } else
+ return cm.toString();
+ }
+
+ public void setData(Vector<ComponentModel> data) {
+ components = data;
+ fireTableDataChanged();
+ }
+
+ public void selectAll() {
+ for(ComponentModel cm:components) cm.selected=true;
+ fireTableDataChanged();
+ }
+ }
+
+ @SuppressWarnings("unused")
+ private class ComponentHolder {
+ private HashMap<String, String> compList;
+ private Vector<ComponentModel> updateComps;
+ private ArrayList<ComponentModel> comps;
+
+ public ComponentHolder(Vector<ComponentModel> updateComps) {
+ super();
+ compList = new HashMap<String, String>();
+ comps = new ArrayList<ComponentModel>();
+ this.updateComps=updateComps;
+ }
+
+ public boolean isComponentPresent(String cid) {
+ return compList.get(cid) != null;
+ }
+
+ public String getComponentVersion(String cid) {
+ return compList.get(cid);
+ }
+
+ public boolean isComponentAlreadySelected(String cid, String version) {
+ return isComponentPresent(cid) && UpdaterUtil.compareReleases(getComponentVersion(cid), version) >= 0;
+ }
+
+ public void addComponent(ComponentModel cm) throws DataConfigurationException {
+ if (isComponentAlreadySelected(cm.getId(), cm.getRelease().getV()))
+ return;
+ if (isComponentPresent(cm.getId())) {
+ int ret = UpdaterUtil.compareReleases(getComponentVersion(cm.getId()),cm.getRelease().getV());
+ if(ret<0) {
+ XemeliosComponent xc = new XemeliosComponent(cm.getId(), getComponentVersion(cm.getId()));
+ comps.remove(xc);
+ compList.remove(cm.getId());
+ }
+ }
+ comps.add(cm);
+ compList.put(cm.getId(), cm.getRelease().getV());
+ if(cm.getRequires()!=null) {
+ for(ComponentRefModel cRef:cm.getRequires().getComponents()) {
+ String installedVersion = installedComponents.getComponentVersion(cRef.getId());
+ if(installedVersion!=null && UpdaterUtil.compareReleases(installedVersion,cRef.getVersion())>=0) continue;
+ ComponentModel dep = updateCompsById.get(cRef.getId());
+ if(dep !=null && UpdaterUtil.compareReleases(dep.getRelease().getV(),cRef.getVersion())>=0)
+ addComponent(dep);
+ else
+ throw new DataConfigurationException("Composant requis introuvable: "+cRef.getId()+" ("+cRef.getVersion()+")");
+ }
+ }
+ }
+ public void removeComponent(String cid) {
+ String version = getComponentVersion(cid);
+ XemeliosComponent xc = new XemeliosComponent(cid, version);
+ comps.remove(xc);
+ compList.remove(cid);
+ }
+ }
+
+ public class HyperLink extends JLabel {
+ private String uri;
+ private Action act;
+ public HyperLink(String text,String uri) {
+ super(text);
+ this.uri=uri;
+ act = new AbstractAction() {
+
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ try {
+ StartUrl.startUrl(HyperLink.this.uri);
+ } catch(Exception ex) {}
+ }
+
+ };
+ setForeground(new Color(0x00,0x33,0xFF));
+ setFocusable(true);
+ setBorder(new EmptyBorder(2,2,2,2));
+ getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE,0), "CLICK");
+ getActionMap().put("CLICK", act);
+ addFocusListener(new FocusAdapter() {
+
+ @Override
+ public void focusGained(FocusEvent e) {
+ ((HyperLink)e.getComponent()).paintFocus();
+ }
+
+ @Override
+ public void focusLost(FocusEvent e) {
+ ((HyperLink)e.getComponent()).paintFocus();
+ }
+
+ });
+ addMouseListener(new MouseAdapter() {
+
+ @Override
+ public void mouseClicked(MouseEvent e) {
+ HyperLink.this.act.actionPerformed(null);
+ }
+
+ @Override
+ public void mouseEntered(MouseEvent e) {
+ super.mouseEntered(e);
+ HyperLink.this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
+ }
+
+ @Override
+ public void mouseExited(MouseEvent e) {
+ super.mouseExited(e);
+ HyperLink.this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
+ }
+
+ });
+ }
+ @Override
+ protected void paintComponent(Graphics g) {
+ super.paintComponent(g);
+ g.setColor(getForeground());
+ int height = getFontMetrics(getFont()).getAscent()+2;
+ g.drawLine(0,height,getWidth(),height);
+ paintFocus(g);
+ }
+ protected void paintFocus(Graphics g) {
+ if(g==null) return;
+ if(isFocusOwner()) {
+ g.setColor(UIManager.getColor("Button.focus"));
+ } else {
+ g.setColor(UIManager.getColor("Label.background"));
+ }
+ g.drawRect(0, 0, getWidth()-1, getHeight()-1);
+ }
+ protected void paintFocus() { paintFocus(getGraphics()); }
+ }
+ public class Downloader extends SwingWorker<Boolean,Integer> {
+ private ComponentHolder ch;
+ protected String errorMsg = null;
+ protected Exception exception = null;
+
+ public Exception getException() { return exception; }
+ public String getErrorMessage() { return errorMsg; }
+
+ private Downloader(ComponentHolder ch) {
+ super();
+ this.ch=ch;
+ }
+ @Override
+ protected Boolean doInBackground() throws Exception {
+ logger.debug("in doInBackground");
+ boolean bRet = true;
+ try {
+ File tmpDir = new File(unescapePath("${xemelios.dir}/tmp-upd"));
+ logger.debug("tmpDir=" + tmpDir.getPath());
+ tmpDir.mkdirs();
+
+ StringBuilder sb = new StringBuilder();
+
+ HttpClient client = NetAccess.getHttpClient(MainWindow.getInstance().getEnvProperties());
+ for (ComponentModel cm : ch.comps) {
+ for (FileListModel fl : cm.getFileLists()) {
+ String root = fl.getRoot();
+ for (XmlMarshallable x : fl.getFiles()) {
+ if (x instanceof FileModel) {
+ FileModel fm = (FileModel) x;
+ File localFile = getLocalFileName(fm.getDest(),fm.getName());
+ if(localFile!=null) {
+ AbstractChecksum localChecksum = new MD("MD5");
+ FileInputStream fis = new FileInputStream(localFile);
+ byte[] buffer = new byte[1024];
+ int read = fis.read(buffer);
+ while (read > 0) {
+ localChecksum.update(buffer, 0, read);
+ read = fis.read(buffer);
+ }
+ fis.close();
+ if(localChecksum.getFormattedValue().equals(fm.getMd5())) {
+ logger.info("local "+fm.getName()+" is the same than remote one.");
+ continue;
+ }
+ }
+ String sUrl = root + "/" + fm.getSource();
+ URL url = new URL(sUrl);
+ //URLConnection con = url.openConnection();
+ AbstractChecksum checksum = new MD("MD5");
+ FileOutputStream fos;
+ File tmpFile = File.createTempFile("upd-", null, tmpDir);
+ sb.append("copy|").append(tmpFile.getName()).append("|").append(fm.getDest() + "/" + fm.getName()).append("\n");
+ fos = new FileOutputStream(tmpFile);
+ logger.info("downloading " + sUrl + " to " + tmpFile.getPath());
+ HttpMethod meth = new GetMethod(sUrl);
+ meth.addRequestHeader("Pragma", "no-cache");
+ int returnCode = client.executeMethod(meth);
+ if(returnCode<=300) {
+ InputStream is = meth.getResponseBodyAsStream();
+ byte[] buffer = new byte[1024];
+ int read = is.read(buffer);
+ while (read > 0) {
+ fos.write(buffer, 0, read);
+ checksum.update(buffer, 0, read);
+ read = is.read(buffer);
+ }
+ is.close();
+ fos.flush();
+ fos.close();
+ if (!fm.getMd5().equals(checksum.getFormattedValue())) {
+ logger.error("File " + fm.getName() + ":\n\texpected : " + fm.getMd5() + "\n\tcalculated: " + checksum.getFormattedValue());
+ throw new UpdaterException("Signature de fichier téléchargé invalide - " + fm.getName());
+ }
+ } else {
+// JOptionPane.showMessageDialog(this," "+returnCode+" : "+meth.getStatusText()+"\n"+sUrl,"ERREUR",JOptionPane.ERROR_MESSAGE);
+ errorMsg = " "+returnCode+" : "+meth.getStatusText()+" : "+sUrl;
+ bRet = false;
+ throw new IOException();
+ }
+ } else if (x instanceof DeleteModel) {
+ DeleteModel dm = (DeleteModel) x;
+ sb.append("delete|").append(dm.getName()).append("\n");
+ }
+ }
+ }
+ if (cm.getConfiguration() != null) {
+ ConfigurationModel conf = cm.getConfiguration();
+ sb.append("configuration|").append(conf.getClassName()).append("");
+ if (conf.getParams().size() == 0)
+ sb.append("\n");
+ else {
+ for (ParamModel pm : conf.getParams()) {
+ sb.append("|").append(pm.getName()).append("|").append(pm.getParamValue());
+ }
+ sb.append("\n");
+ }
+ }
+ // declares component in installed components
+ sb.append("install-component|").append(cm.getId()).append("|").append(cm.getRelease().getV()).append("|").append(cm.getDescription().getText()).append("\n");
+ }
+// bRet = true;
+ File batch = new File(tmpDir, "update-script.xem");
+ FileOutputStream fos = new FileOutputStream(batch);
+ StringBuilder header = new StringBuilder("# update of ").append(DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG).format(new Date())).append("\n");
+ fos.write(header.toString().getBytes("ISO-8859-1"));
+ fos.write(sb.toString().getBytes("ISO-8859-1"));
+ // props.storeToXML(fos,"update of
+ // "+DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG).format(new
+ // Date()));
+ fos.flush();
+ fos.close();
+ } catch (UpdaterException uex) {
+ //new DisplayExceptionDlg(this, uex);
+ bRet = false;
+ exception = uex;
+ } catch (MalformedURLException e) {
+ // TODO Auto-generated catch block
+ bRet = false;
+ e.printStackTrace();
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ bRet = false;
+ e.printStackTrace();
+ } catch(DataConfigurationException dcEx) {
+ //JOptionPane.showMessageDialog(this,dcEx.getMessage(),"ERREUR",JOptionPane.ERROR_MESSAGE);
+ bRet = false;
+ errorMsg = dcEx.getMessage();
+ }
+ return new Boolean(bRet);
+ }
+
+ @Override
+ protected void done() {
+ getGlassPane().setVisible(false);
+ }
+
+ }
+}
--- /dev/null
+<?xml version="1.1" encoding="UTF-8" ?>
+
+<Form version="1.5" maxVersion="1.7" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
+ <Properties>
+ <Property name="preferredSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
+ <Dimension value="[472, 465]"/>
+ </Property>
+ <Property name="requestFocusEnabled" type="boolean" value="false"/>
+ </Properties>
+ <AuxValues>
+ <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
+ <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
+ <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
+ <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
+ <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
+ </AuxValues>
+
+ <Layout>
+ <DimensionLayout dim="0">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" attributes="0">
+ <EmptySpace max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="jLabel1" min="-2" max="-2" attributes="0"/>
+ <Group type="102" alignment="0" attributes="0">
+ <Component id="jScrollPane1" pref="361" max="32767" attributes="0"/>
+ <EmptySpace type="unrelated" min="-2" max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="jButtonSupprimer" max="32767" attributes="2"/>
+ <Component id="jButtonEditer" pref="81" max="32767" attributes="2"/>
+ <Component id="jButtonAjouter" alignment="0" pref="81" max="32767" attributes="2"/>
+ </Group>
+ </Group>
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace min="-2" pref="32" max="-2" attributes="0"/>
+ <Component id="jLabelSite" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <Component id="jLabel2" alignment="0" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <EmptySpace max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ <DimensionLayout dim="1">
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Component id="jLabel1" min="-2" max="-2" attributes="0"/>
+ <EmptySpace min="-2" max="-2" attributes="0"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Group type="102" alignment="0" attributes="0">
+ <Component id="jButtonAjouter" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="jButtonEditer" min="-2" max="-2" attributes="0"/>
+ <EmptySpace max="-2" attributes="0"/>
+ <Component id="jButtonSupprimer" min="-2" max="-2" attributes="0"/>
+ </Group>
+ <Group type="102" alignment="0" attributes="0">
+ <Component id="jScrollPane1" max="32767" attributes="0"/>
+ <EmptySpace type="unrelated" min="-2" max="-2" attributes="1"/>
+ <Group type="103" groupAlignment="0" attributes="0">
+ <Component id="jLabel2" min="-2" max="-2" attributes="0"/>
+ <Component id="jLabelSite" alignment="0" min="-2" max="-2" attributes="0"/>
+ </Group>
+ </Group>
+ </Group>
+ <EmptySpace min="26" pref="26" max="26" attributes="0"/>
+ </Group>
+ </Group>
+ </DimensionLayout>
+ </Layout>
+ <SubComponents>
+ <Component class="javax.swing.JLabel" name="jLabel1">
+ <Properties>
+ <Property name="font" type="java.awt.Font" editor="org.netbeans.modules.form.editors2.FontEditor">
+ <FontInfo relative="true">
+ <Font bold="true" component="jLabel1" property="font" relativeSize="true" size="0"/>
+ </FontInfo>
+ </Property>
+ <Property name="text" type="java.lang.String" value="Liste d'abonnements aux composants"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JLabel" name="jLabel2">
+ <Properties>
+ <Property name="font" type="java.awt.Font" editor="org.netbeans.modules.form.editors2.FontEditor">
+ <FontInfo relative="true">
+ <Font bold="true" component="jLabel2" property="font" relativeSize="true" size="0"/>
+ </FontInfo>
+ </Property>
+ <Property name="text" type="java.lang.String" value="Site"/>
+ </Properties>
+ </Component>
+ <Component class="javax.swing.JLabel" name="jLabelSite">
+ </Component>
+ <Component class="javax.swing.JButton" name="jButtonAjouter">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Ajouter"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButtonAjouterActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="jButtonEditer">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Editer"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButtonEditerActionPerformed"/>
+ </Events>
+ </Component>
+ <Component class="javax.swing.JButton" name="jButtonSupprimer">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Supprimer"/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButtonSupprimerActionPerformed"/>
+ </Events>
+ </Component>
+ <Container class="javax.swing.JScrollPane" name="jScrollPane1">
+ <AuxValues>
+ <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
+ </AuxValues>
+
+ <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
+ <SubComponents>
+ <Component class="org.jdesktop.swingx.JXTable" name="jxTableComposants">
+ <Properties>
+ <Property name="model" type="javax.swing.table.TableModel" editor="org.netbeans.modules.form.RADConnectionPropertyEditor">
+ <Connection code="cTableModel" type="code"/>
+ </Property>
+ </Properties>
+ </Component>
+ </SubComponents>
+ </Container>
+ </SubComponents>
+</Form>
--- /dev/null
+/*
+ * Copyright
+ * 2010 axYus - www.axyus.com
+ * 2010 F.Nhieu - franck.nhieu@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.updater.ui;
+
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.cp.xemelios.updater.installed.InstalledModel;
+import fr.gouv.finances.cp.xemelios.updater.profils.ComponentModel;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import java.util.ArrayList;
+import javax.swing.ListSelectionModel;
+import javax.swing.event.ListSelectionEvent;
+import javax.swing.event.ListSelectionListener;
+import javax.swing.table.AbstractTableModel;
+import org.apache.log4j.Logger;
+
+/**
+ * PnlComposants
+ * @author franck
+ */
+public class PnlComposants extends javax.swing.JPanel {
+
+ private static Logger logger = Logger.getLogger(PnlComposants.class);
+ private final PropertiesExpansion applicationProperties;
+ private ComposantsTableModel cTableModel;
+ private InstalledModel im;
+ private String installedFileLocation;
+
+
+ /**
+ *
+ * @param applicationProperties
+ */
+ public PnlComposants(PropertiesExpansion applicationProperties) {
+ this.applicationProperties = applicationProperties;
+ installedFileLocation = applicationProperties.getProperty(Constants.SYS_PROP_INSTALLED_FILENAME);
+ cTableModel = new ComposantsTableModel();
+ try {
+ im = InstalledModel.readFromFile(installedFileLocation);
+ logger.debug("installedFileLocation="+installedFileLocation);
+ logger.debug("im.fileLocation="+im.getFileLocation());
+ cTableModel.setComposants(im.getComponents());
+ initComponents();
+
+ //jLabelSite.setFont(new java.awt.Font("Tahoma", 0, 11));
+
+ jButtonEditer.setEnabled(false);
+ jButtonSupprimer.setEnabled(false);
+
+ jxTableComposants.setShowGrid(false);
+ jxTableComposants.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
+ jxTableComposants.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
+
+ @Override
+ public void valueChanged(ListSelectionEvent e) {
+ boolean bEditable = false;
+ int row = jxTableComposants.getSelectedRow();
+ if(row != -1) {
+ // Site
+ jLabelSite.setText(im.getComponents().get(row).getUri());
+ // bouton Editer et Supprimer disabled si composant issu d'un profil
+ // enabled si composant ajouté manuellement
+ bEditable = im.getComponents().get(row).isEditable();
+ }
+ jButtonEditer.setEnabled(bEditable);
+ jButtonSupprimer.setEnabled(bEditable);
+ }
+ });
+ } catch (Exception ex) {
+ logger.error(ex);
+ DisplayExceptionDlg exdlg = new DisplayExceptionDlg(ex);
+ }
+ }
+
+ private class ComposantsTableModel extends AbstractTableModel {
+
+ public ArrayList<ComponentModel> composants;
+
+ public ComposantsTableModel() {
+ this.composants = new ArrayList<ComponentModel>();
+ }
+
+ @Override
+ public int getRowCount() {
+ return composants.size();
+ }
+
+ @Override
+ public int getColumnCount() {
+ return 1;
+ }
+
+ @Override
+ public Object getValueAt(int rowIndex, int columnIndex) {
+ return composants.get(rowIndex).getDescription();
+ }
+
+ @Override
+ public Class<?> getColumnClass(int columnIndex) {
+ return String.class;
+ }
+
+ @Override
+ public String getColumnName(int column) {
+ return "Description";
+ }
+
+ @Override
+ public boolean isCellEditable(int rowIndex, int columnIndex) {
+ return false;
+ }
+
+ public void setComposants(ArrayList<ComponentModel> composants) {
+ this.composants = composants;
+ }
+
+
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ @SuppressWarnings("unchecked")
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ jLabel1 = new javax.swing.JLabel();
+ jLabel2 = new javax.swing.JLabel();
+ jLabelSite = new javax.swing.JLabel();
+ jButtonAjouter = new javax.swing.JButton();
+ jButtonEditer = new javax.swing.JButton();
+ jButtonSupprimer = new javax.swing.JButton();
+ jScrollPane1 = new javax.swing.JScrollPane();
+ jxTableComposants = new org.jdesktop.swingx.JXTable();
+
+ setPreferredSize(new java.awt.Dimension(472, 465));
+ setRequestFocusEnabled(false);
+
+ jLabel1.setFont(jLabel1.getFont().deriveFont(jLabel1.getFont().getStyle() | java.awt.Font.BOLD));
+ jLabel1.setText("Liste d'abonnements aux composants");
+
+ jLabel2.setFont(jLabel2.getFont().deriveFont(jLabel2.getFont().getStyle() | java.awt.Font.BOLD));
+ jLabel2.setText("Site");
+
+ jButtonAjouter.setText("Ajouter");
+ jButtonAjouter.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ jButtonAjouterActionPerformed(evt);
+ }
+ });
+
+ jButtonEditer.setText("Editer");
+ jButtonEditer.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ jButtonEditerActionPerformed(evt);
+ }
+ });
+
+ jButtonSupprimer.setText("Supprimer");
+ jButtonSupprimer.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ jButtonSupprimerActionPerformed(evt);
+ }
+ });
+
+ jxTableComposants.setModel(cTableModel);
+ jScrollPane1.setViewportView(jxTableComposants);
+
+ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
+ this.setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(jLabel1)
+ .addGroup(layout.createSequentialGroup()
+ .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 361, Short.MAX_VALUE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(jButtonSupprimer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addComponent(jButtonEditer, javax.swing.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE)
+ .addComponent(jButtonAjouter, javax.swing.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE)))
+ .addGroup(layout.createSequentialGroup()
+ .addGap(32, 32, 32)
+ .addComponent(jLabelSite))
+ .addComponent(jLabel2))
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(jLabel1)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addComponent(jButtonAjouter)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(jButtonEditer)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(jButtonSupprimer))
+ .addGroup(layout.createSequentialGroup()
+ .addComponent(jScrollPane1)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(jLabel2)
+ .addComponent(jLabelSite))))
+ .addGap(26, 26, 26))
+ );
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void jButtonAjouterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAjouterActionPerformed
+ // TODO add your handling code here:
+ DlgComposantEdition nd = new DlgComposantEdition(MainWindow.getInstance(), new ComponentModel());
+ nd.setTitle("Ajout d'un composant");
+ nd.setLocationRelativeTo(MainWindow.getInstance());
+ nd.setInstalledModelFileLocation(installedFileLocation);
+ nd.setEnvironement(applicationProperties.getProperty(Constants.SYS_PROP_MAJ_CONFIG));
+ nd.setVisible(true);
+
+ try {
+ im = InstalledModel.readFromFile(installedFileLocation);
+ cTableModel.setComposants(im.getComponents());
+ cTableModel.fireTableDataChanged();
+ } catch (Exception ex) {
+ logger.error(ex);
+ DisplayExceptionDlg exdlg = new DisplayExceptionDlg(ex);
+ }
+ }//GEN-LAST:event_jButtonAjouterActionPerformed
+
+ private void jButtonEditerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEditerActionPerformed
+ // TODO add your handling code here:
+ int row = jxTableComposants.getSelectedRow();
+ ComponentModel cm = im.getComponents().get(row);
+ DlgComposantEdition nd = new DlgComposantEdition(MainWindow.getInstance(), cm);
+ nd.setTitle("Edition d'un composant");
+ nd.setLocationRelativeTo(MainWindow.getInstance());
+ nd.setInstalledModelFileLocation(installedFileLocation);
+ nd.setEnvironement(applicationProperties.getProperty(Constants.SYS_PROP_MAJ_CONFIG));
+ nd.setVisible(true);
+ try {
+ im = InstalledModel.readFromFile(installedFileLocation);
+ cTableModel.setComposants(im.getComponents());
+ cTableModel.fireTableDataChanged();
+ } catch (Exception ex) {
+ logger.error(ex);
+ DisplayExceptionDlg exdlg = new DisplayExceptionDlg(ex);
+ }
+ }//GEN-LAST:event_jButtonEditerActionPerformed
+
+ private void jButtonSupprimerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSupprimerActionPerformed
+ // TODO add your handling code here:
+ //im.getComponents().remove(jxTableComposants.getSelectedRow());
+ int row = jxTableComposants.getSelectedRow();
+ im.removeComponent(im.getComponents().get(row).getUUID());
+ try {
+ im.saveInstalledModel();
+ im = InstalledModel.readFromFile(installedFileLocation); // pas spécialement nécessaire
+ cTableModel.setComposants(im.getComponents());
+ cTableModel.fireTableRowsDeleted(row, row);
+ //cTableModel.fireTableDataChanged();
+ } catch (Exception ex) {
+ logger.error(ex);
+ DisplayExceptionDlg exdlg = new DisplayExceptionDlg(ex);
+ }
+
+ }//GEN-LAST:event_jButtonSupprimerActionPerformed
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JButton jButtonAjouter;
+ private javax.swing.JButton jButtonEditer;
+ private javax.swing.JButton jButtonSupprimer;
+ private javax.swing.JLabel jLabel1;
+ private javax.swing.JLabel jLabel2;
+ private javax.swing.JLabel jLabelSite;
+ private javax.swing.JScrollPane jScrollPane1;
+ private org.jdesktop.swingx.JXTable jxTableComposants;
+ // End of variables declaration//GEN-END:variables
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ * 2010 F.Nhieu - franck.nhieu@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.updater.update;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import fr.gouv.finances.cp.xemelios.updater.profils.ComponentModel;
+import javax.xml.namespace.QName;
+
+public class ComponentRefModel implements XmlMarshallable {
+
+ public static final transient String TAG = "component-ref";
+ public static final transient QName QN = new QName(TAG);
+ private String uri, version;
+
+ public ComponentRefModel(QName tag) {
+ super();
+ }
+
+ @Override
+ public void addCharacterData(String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ uri = attributes.getValue("uri");
+ version = attributes.getValue("version");
+ return this;
+ }
+
+ @Override
+ public void marshall(XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("uri", uri);
+ output.addAttribute("version", version);
+ output.endTag(TAG);
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ if (uri == null) {
+ throw new InvalidXmlDefinition("uri attribute is mandatory for element " + TAG);
+ }
+ if (version == null) {
+ throw new InvalidXmlDefinition("version attribute is mandatory for element " + TAG);
+ }
+ }
+
+ @Override
+ public ComponentRefModel clone() {
+ ComponentRefModel cr = new ComponentRefModel(QN);
+ cr.uri = uri;
+ cr.version = version;
+ return cr;
+ }
+
+ public void setUri(String uri) {
+ this.uri = uri;
+ }
+
+ public String getUri() {
+ return uri;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ @Override
+ public String toString() {
+ return uri + " (" + version + ")";
+ }
+
+ public boolean equals(ComponentRefModel crm) {
+ return crm.getUri().equals(uri);
+ }
+
+ public boolean equals(ComponentModel crm) {
+ return crm.getUri().equals(uri);
+ }
+
+ public boolean equals(String id) {
+ return this.uri.equals(id);
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.updater.update;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import javax.xml.namespace.QName;
+
+public class ConfigurationModel implements XmlMarshallable {
+
+ public static final transient String TAG = "configurator";
+ public static final transient QName QN = new QName(TAG);
+ private String className;
+ //private ArrayList<ParamModel> params;
+
+ public ConfigurationModel(QName tagName) {
+ super();
+ //params = new ArrayList<ParamModel>();
+ }
+
+ @Override
+ public void addCharacterData(String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
+ //if(ParamModel.QN.equals(tagName)) params.add((ParamModel)child);
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ className = attributes.getValue("class");
+ return this;
+ }
+
+ @Override
+ public void marshall(XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("class", className);
+ //for(Iterator<ParamModel> it=params.iterator();it.hasNext();)
+ // it.next().marshall(output);
+ output.endTag(TAG);
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ }
+
+ @Override
+ public ConfigurationModel clone() {
+ ConfigurationModel cm = new ConfigurationModel(QN);
+ cm.className = this.className;
+ //for(Iterator<ParamModel> it=params.iterator();it.hasNext();)
+ // cm.params.add(it.next());
+ return cm;
+ }
+
+ public String getClassName() {
+ return className;
+ }
+
+ public void setClassName(String className) {
+ this.className = className;
+ }
+
+ /*
+ public ArrayList<ParamModel> getParams() {
+ return params;
+ }
+
+ public void setParams(ArrayList<ParamModel> params) {
+ this.params = params;
+ }
+ */
+ @Override
+ public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2010 axYus - www.axyus.com
+ * 2010 F.Nhieu - franck.nhieu@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+/**
+ * Modèle de l'élèment "delete" de "/xemelios-component/version/files/" du fichier "update.xml"
+ * Contient le nom d'un fichier à effacer dans l'attribut "name".
+ */
+package fr.gouv.finances.cp.xemelios.updater.update;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import javax.xml.namespace.QName;
+
+public class DeleteModel implements XmlMarshallable {
+
+ public static final transient String TAG = "delete";
+ public static final transient QName QN = new QName(TAG);
+ private String name;
+
+ public DeleteModel(QName tag) {
+ super();
+ }
+
+ public DeleteModel() {
+ super();
+ }
+
+ @Override
+ public void addCharacterData(String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ name = attributes.getValue("name");
+ return this;
+ }
+
+ @Override
+ public void marshall(XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("name", name);
+ output.endTag(TAG);
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ }
+
+ @Override
+ public DeleteModel clone() {
+ DeleteModel dm = new DeleteModel(QN);
+ dm.name = name;
+ return dm;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String toString() {
+ return getName();
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.updater.update;
+
+import java.util.ArrayList;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import javax.xml.namespace.QName;
+
+public class FileListModel implements XmlMarshallable {
+
+ public static final transient String TAG = "files";
+ public static final transient QName QN = new QName(TAG);
+ private String root;
+ public ArrayList<FileModel> files;
+ public ArrayList<DeleteModel> deletes;
+
+ public FileListModel() {
+ super();
+ files = new ArrayList<FileModel>();
+ deletes = new ArrayList<DeleteModel>();
+ }
+
+ public FileListModel(QName tag) {
+ super();
+ files = new ArrayList<FileModel>();
+ deletes = new ArrayList<DeleteModel>();
+ }
+
+ @Override
+ public void addCharacterData(String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
+ if(child instanceof FileModel) files.add((FileModel)child);
+ else if(child instanceof DeleteModel) deletes.add((DeleteModel)child);
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ root = attributes.getValue("root");
+ return this;
+ }
+
+ @Override
+ public void marshall(XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("root", root);
+ for(FileModel fm:files) fm.marshall(output);
+ for(DeleteModel dm:deletes) dm.marshall(output);
+ output.endTag(TAG);
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ }
+
+ @Override
+ public FileListModel clone() {
+ FileListModel flm = new FileListModel(QN);
+ flm.root = root;
+ for(FileModel fm:files) flm.files.add(fm);
+ for(DeleteModel dm:deletes) flm.deletes.add(dm);
+ return flm;
+ }
+
+ public ArrayList<FileModel> getFiles() {
+ return files;
+ }
+
+ public void setFiles(ArrayList<FileModel> files) {
+ this.files = files;
+ }
+
+ public ArrayList<DeleteModel> getDeletes() {
+ return deletes;
+ }
+
+ public void setDeletes(ArrayList<DeleteModel> deletes) {
+ this.deletes = deletes;
+ }
+
+ public String getRoot() {
+ return root;
+ }
+
+ public void setRoot(String root) {
+ this.root = root;
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.updater.update;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import javax.xml.namespace.QName;
+
+public class FileModel implements XmlMarshallable {
+
+ public static final transient String TAG = "file";
+ public static final transient QName QN = new QName(TAG);
+ private String name, source, dest, md5, unpackedMd5;
+ public FileModel(QName tag) {
+ super();
+ }
+
+ @Override
+ public void addCharacterData(String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ name = attributes.getValue("name");
+ source = attributes.getValue("source");
+ dest = attributes.getValue("dest");
+ md5 = attributes.getValue("md5");
+ unpackedMd5 = attributes.getValue("unpacked-md5");
+ return this;
+ }
+
+ @Override
+ public void marshall(XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("name", name);
+ output.addAttribute("source", source);
+ output.addAttribute("dest", dest);
+ output.addAttribute("md5", md5);
+ output.addAttribute("unpacked-md5", unpackedMd5);
+ output.endTag(TAG);
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ }
+
+ @Override
+ public FileModel clone() {
+ FileModel fm = new FileModel(QN);
+ fm.name = name;
+ fm.source = source;
+ fm.dest = dest;
+ return fm;
+ }
+
+ public String getDest() {
+ return dest;
+ }
+
+ public void setDest(String dest) {
+ this.dest = dest;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getSource() {
+ return source;
+ }
+
+ public void setSource(String source) {
+ this.source = source;
+ }
+
+ @Override
+ public String toString() {
+ return getName();
+ }
+
+ public String getMd5() {
+ return md5;
+ }
+
+ public void setMd5(String md5) {
+ this.md5 = md5;
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
+
+ public String getUnpackedMd5() {
+ return unpackedMd5;
+ }
+
+ public void setUnpackedMd5(String unpackedMd5) {
+ this.unpackedMd5 = unpackedMd5;
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2011 axYus - http://www.axyus.com
+ * 2011 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS_NB.
+ *
+ * XEMELIOS_NB 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 2 of the License, or
+ * (at your option) any later version.
+ *
+ * XEMELIOS_NB 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 Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with XEMELIOS_NB; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+
+package fr.gouv.finances.cp.xemelios.updater.update;
+
+import fr.gouv.finances.dgfip.xemelios.common.config.TexteModel;
+import javax.xml.namespace.QName;
+
+/**
+ *
+ * @author cmarchand
+ */
+public class NoteModel extends TexteModel {
+ public static final transient QName QN = new QName("note");
+
+ public NoteModel(QName qn) {
+ super(qn);
+ }
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.updater.update;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import javax.xml.namespace.QName;
+
+public class ParamModel implements XmlMarshallable {
+
+ public static final transient String TAG = "param";
+ public static final transient QName QN = new QName(TAG);
+ private String name;
+ private StringBuilder paramValue;
+
+ public ParamModel(QName tagName) {
+ super();
+ paramValue = new StringBuilder();
+ }
+
+ public void addCharacterData(String cData) throws SAXException {
+ paramValue.append(cData);
+ }
+
+ public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
+ }
+
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ name = attributes.getValue("name");
+ return this;
+ }
+
+ public void marshall(XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("name", name);
+ output.addCharacterData(getParamValue());
+ output.endTag(TAG);
+
+ }
+
+ public void validate() throws InvalidXmlDefinition {
+ }
+
+ public ParamModel clone() {
+ ParamModel pm = new ParamModel(QN);
+ pm.name = this.name;
+ pm.paramValue.append(this.getParamValue());
+ return pm;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getParamValue() {
+ return paramValue.toString();
+ }
+
+ public void setParamValue(StringBuilder paramValue) {
+ this.paramValue = paramValue;
+ }
+
+ public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
+ return null;
+ }
+
+ public QName getQName() {
+ return QN;
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2005 axYus - www.axyus.com
+ * 2005 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.updater.update;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import javax.xml.namespace.QName;
+
+public class RequireModel implements XmlMarshallable {
+
+ public static final transient String TAG = "requires";
+ public static final transient QName QN = new QName(TAG);
+ private ArrayList<ComponentRefModel> components;
+
+ public RequireModel() {
+ super();
+ components = new ArrayList<ComponentRefModel>();
+ }
+
+ public RequireModel(QName tag) {
+ super();
+ components = new ArrayList<ComponentRefModel>();
+ }
+
+ @Override
+ public void addCharacterData(String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
+ components.add((ComponentRefModel) child);
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ return this;
+ }
+
+ @Override
+ public void marshall(XmlOutputter output) {
+ output.startTag(TAG);
+ for (int i = 0; i < components.size(); i++) {
+ components.get(i).marshall(output);
+ }
+ output.endTag(TAG);
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ for (Iterator<ComponentRefModel> it = components.iterator(); it.hasNext();) {
+ it.next().validate();
+ }
+ }
+
+ @Override
+ public RequireModel clone() {
+ RequireModel rm = new RequireModel(QN);
+ for (ComponentRefModel crm : components) {
+ rm.components.add(crm);
+ }
+ return rm;
+ }
+
+ public ArrayList<ComponentRefModel> getComponents() {
+ return components;
+ }
+
+ public void setComponents(ArrayList<ComponentRefModel> components) {
+ this.components = components;
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2010 axYus - www.axyus.com
+ * 2010 F.Nhieu - franck.nhieu@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+/**
+ * Modèle de l'élèment "update.xml"
+ * Contient l'ensemble des informations d'un composant.
+ */
+package fr.gouv.finances.cp.xemelios.updater.update;
+
+import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.cp.xemelios.updater.profils.ComponentModel;
+import fr.gouv.finances.dgfip.xemelios.common.NetAccess;
+import java.io.InputStream;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.methods.GetMethod;
+import java.util.ArrayList;
+import javax.xml.namespace.QName;
+import org.apache.log4j.Logger;
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+/**
+ *
+ * @author franck.nhieu
+ */
+public class UpdateModel implements XmlMarshallable {
+ private static Logger logger = Logger.getLogger(UpdateModel.class);
+
+ /**
+ *
+ */
+ public static final transient String TAG = "xemelios-component";
+ public static final transient QName QN = new QName(TAG);
+ public static final transient int NOT_FOUND = -1;
+
+ private String description, type, last_version, original_location, generate_date, environment_type;
+ private ArrayList<VersionModel> versions;
+
+ private String ComponentUri; // Contient l'URI du composant utilisé lors de la lecture de update.xml
+
+ /**
+ *
+ */
+ public UpdateModel() {
+ super();
+ versions = new ArrayList<VersionModel>();
+ }
+
+ /**
+ *
+ * @param description
+ * @param type
+ * @param last_version
+ * @param original_location
+ * @param generate_date
+ * @param environment_type
+ */
+ public UpdateModel(String description, String type, String last_version, String original_location, String generate_date, String environment_type) {
+ this.description = description;
+ this.type = type;
+ this.last_version = last_version;
+ this.original_location = original_location;
+ this.generate_date = generate_date;
+ this.environment_type = environment_type;
+ }
+
+ public UpdateModel(QName QN) {
+ super();
+ versions = new ArrayList<VersionModel>();
+ }
+
+ public static UpdateModel loadModel(ComponentModel cm, String environment) throws Exception {
+ UpdateModel um = new UpdateModel();
+ um.ComponentUri = cm.getUri();
+ try {
+ String urlLocation = cm.getUri() + "/" + environment + "/update.xml";
+ logger.debug("urlLocation="+urlLocation);
+
+ HttpClient client = NetAccess.getHttpClient(MainWindow.getInstance().getEnvProperties());
+ GetMethod meth = new GetMethod(urlLocation);
+ meth.addRequestHeader("Pragma", "no-cache");
+ int httpRet = client.executeMethod(meth);
+ if (httpRet > 300) {
+ throw new Exception("URL urlLocation "+urlLocation+" : "+meth.getStatusText());
+ }
+ InputStream is = meth.getResponseBodyAsStream();
+ UpdateParser up = new UpdateParser();
+ up.parse(is);
+ is.close();
+ um = (UpdateModel) up.getMarshallable();
+ um.ComponentUri = cm.getUri();
+ logger.debug("UpdateModel: desc="+um.description);
+ logger.debug("UpdateModel: lver="+um.last_version);
+ logger.debug("UpdateModel: type="+um.type);
+ return um;
+ } catch (Exception ex) {
+ logger.error(ex);
+ throw new Exception(ex);
+ }
+ }
+
+ public String getComponentUri() {
+ return ComponentUri;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public String getEnvironment_type() {
+ return environment_type;
+ }
+
+ public String getGenerate_date() {
+ return generate_date;
+ }
+
+ public String getLast_version() {
+ return last_version;
+ }
+
+ public String getOriginal_location() {
+ return original_location;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public ArrayList<VersionModel> getVersions() {
+ return versions;
+ }
+
+ public VersionModel getVersionModel(String version) {
+ for(VersionModel vm:versions) {
+ if(vm.getVersion().equals(version))
+ return vm;
+ }
+ return null;
+ }
+
+ public VersionModel getLastVersionModel() {
+ for(VersionModel vm:versions) {
+ if(vm.getVersion().equals(last_version))
+ return vm;
+ }
+ return null;
+ }
+
+ public int getVersionModelIdx(String version) {
+ for(int i=0; i<versions.size(); i++) {
+ if(versions.get(i).getVersion().equals(version))
+ return i;
+ }
+ return NOT_FOUND;
+ }
+
+ public int getLastVersionModelIdx() {
+ for(int i=0; i<versions.size(); i++) {
+ if(versions.get(i).getVersion().equals(last_version))
+ return i;
+ }
+ return NOT_FOUND;
+ }
+
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public void setEnvironment_type(String environment_type) {
+ this.environment_type = environment_type;
+ }
+
+ public void setGenerate_date(String generate_date) {
+ this.generate_date = generate_date;
+ }
+
+ public void setLast_version(String last_version) {
+ this.last_version = last_version;
+ }
+
+ public void setOriginal_location(String original_location) {
+ this.original_location = original_location;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public void setVersions(ArrayList<VersionModel> versions) {
+ this.versions = versions;
+ }
+
+
+ @Override
+ public void addCharacterData(String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(XmlMarshallable child, QName tag) throws SAXException {
+ versions.add((VersionModel) child);
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ description = attributes.getValue("description");
+ type = attributes.getValue("type");
+ last_version = attributes.getValue("last-version");
+ original_location = attributes.getValue("original-location");
+ generate_date = attributes.getValue("generate-date");
+ environment_type = attributes.getValue("environment-type");
+ return this;
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public void marshall(XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("description", description);
+ output.addAttribute("type", type);
+ output.addAttribute("last-version", last_version);
+ output.addAttribute("original-location", original_location);
+ output.addAttribute("environment-type", environment_type);
+ for (VersionModel vm : versions) {
+ vm.marshall(output);
+ }
+ output.endTag(TAG);
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ if (description == null) {
+ throw new InvalidXmlDefinition("description attribute is mandatory for element " + TAG);
+ }
+ if (type == null) {
+ throw new InvalidXmlDefinition("type attribute is mandatory for element " + TAG);
+ }
+ if (last_version == null) {
+ throw new InvalidXmlDefinition("last-version attribute is mandatory for element " + TAG);
+ }
+ if (original_location == null) {
+ throw new InvalidXmlDefinition("original-location attribute is mandatory for element " + TAG);
+ }
+ if (environment_type == null) {
+ throw new InvalidXmlDefinition("environment-type attribute is mandatory for element " + TAG);
+ }
+ for (VersionModel vm : versions) {
+ vm.validate();
+ }
+ }
+
+ /**
+ *
+ * @return
+ */
+ @Override
+ public QName getQName() {
+ return QN;
+ }
+
+ @Override
+ public UpdateModel clone() {
+ UpdateModel u = new UpdateModel(description, type, last_version, original_location, generate_date, environment_type);
+ for (VersionModel vm : versions) {
+ u.versions.add(vm);
+ }
+ return u;
+ }
+
+ @Override
+ public String toString() {
+ return description+"/"+environment_type+"/"+generate_date+"/"+last_version+"/"+original_location+"/"+type;
+ }
+
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2010 axYus - www.axyus.com
+ * 2010 F.Nhieu - franck.nhieu@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.updater.update;
+
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshalParser;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
+import java.util.HashMap;
+import javax.xml.namespace.QName;
+import javax.xml.parsers.FactoryConfigurationError;
+import javax.xml.parsers.ParserConfigurationException;
+import org.apache.log4j.Logger;
+import org.xml.sax.SAXException;
+
+/**
+ * Modèle de l'élèment "update.xml"
+ * Contient l'ensemble des composants d'un profil.
+ * @author franck.nhieu
+ */
+public class UpdateParser extends XmlMarshalParser {
+ private static Logger logger = Logger.getLogger(UpdateParser.class);
+ public static final transient QName XEMELIOS_UPDATE = new QName("xemelios-component");
+
+
+ public UpdateParser(HashMap mapping) throws SAXException, ParserConfigurationException, FactoryConfigurationError {
+ super(mapping, FactoryProvider.getSaxParserFactory());
+ }
+
+ public UpdateParser() throws SAXException, ParserConfigurationException, FactoryConfigurationError {
+ super(new Mapping(),true, FactoryProvider.getSaxParserFactory());
+ }
+
+ private static class Mapping extends HashMap<QName, Class> {
+ public Mapping() {
+ put(XEMELIOS_UPDATE, UpdateModel.class);
+ put(VersionModel.QN, VersionModel.class);
+ put(FileListModel.QN, FileListModel.class);
+ put(FileModel.QN, FileModel.class);
+ put(DeleteModel.QN, DeleteModel.class);
+ put(RequireModel.QN, RequireModel.class);
+ put(ComponentRefModel.QN, ComponentRefModel.class);
+ put(ConfigurationModel.QN, ConfigurationModel.class);
+ put(NoteModel.QN, NoteModel.class);
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright
+ * 2010 axYus - www.axyus.com
+ * 2010 F.Nhieu - franck.nhieu@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+/**
+ * Modèle de l'élèment "version" du fichier "update.xml"
+ * Contient l'ensemble des fichiers à copier et à effacer, les composants requis
+ * ainsi que les classes de configuraiton à executer pour une version d'un
+ * composant donné.
+ */
+package fr.gouv.finances.cp.xemelios.updater.update;
+
+import fr.gouv.finances.cp.utils.xml.marshal.InvalidXmlDefinition;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlAttributes;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshallable;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import java.util.ArrayList;
+import javax.xml.namespace.QName;
+import org.apache.log4j.Logger;
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+
+/**
+ *
+ * @author franck.nhieu
+ */
+public class VersionModel implements XmlMarshallable {
+
+ private static Logger logger = Logger.getLogger(VersionModel.class);
+ public static final transient String TAG = "version";
+ public static final transient QName QN = new QName(TAG);
+ private String version, date;
+ private FileListModel files;
+ private RequireModel requires;
+ private ArrayList<ConfigurationModel> configurators;
+ private ArrayList<NoteModel> notes;
+
+ public VersionModel() {
+ super();
+ files = new FileListModel();
+ requires = new RequireModel();
+ configurators = new ArrayList<ConfigurationModel>();
+ notes = new ArrayList<NoteModel>();
+ }
+
+ public VersionModel(QName tag) {
+ this();
+ }
+
+ public VersionModel(String version, String date, FileListModel files, RequireModel requires, ArrayList<ConfigurationModel> configurators) {
+ this();
+ this.version = version;
+ this.date = date;
+ this.files = files;
+ this.requires = requires;
+ this.configurators = configurators;
+ }
+
+ public ArrayList<ConfigurationModel> getConfigurators() {
+ return configurators;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public String getDate() {
+ return date;
+ }
+
+ public FileListModel getFiles() {
+ return files;
+ }
+
+ public RequireModel getRequires() {
+ return requires;
+ }
+
+ public void setConfigurators(ArrayList<ConfigurationModel> configurators) {
+ this.configurators = configurators;
+ }
+
+ public void setDate(String date) {
+ this.date = date;
+ }
+
+ public void setFiles(FileListModel files) {
+ this.files = files;
+ }
+
+ public void setRequires(RequireModel requires) {
+ this.requires = requires;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ @Override
+ public void addCharacterData(String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(XmlMarshallable child, QName tag) throws SAXException {
+ if (child instanceof ConfigurationModel) {
+ configurators.add((ConfigurationModel) child);
+ } else if (child instanceof RequireModel) {
+ requires = ((RequireModel) child);
+ } else if (child instanceof FileListModel) {
+ files = ((FileListModel) child);
+// cela pourrait être omis
+ } else if(child instanceof NoteModel) {
+ notes.add((NoteModel)child);
+ }
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ version = attributes.getValue("version");
+ date = attributes.getValue("date");
+ return this;
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public void marshall(XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("version", version);
+ output.addAttribute("date", date);
+ files.marshall(output);
+ requires.marshall(output);
+ for (ConfigurationModel cm : configurators) {
+ cm.marshall(output);
+ }
+ // volontairement, on ne marshall pas les notes.
+ output.endTag(TAG);
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ if (version == null) {
+ throw new InvalidXmlDefinition("version attribute is mandatory for element " + TAG);
+ }
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
+
+ @Override
+ public VersionModel clone() {
+ ArrayList<ConfigurationModel> cf = new ArrayList<ConfigurationModel>();
+ for (ConfigurationModel cm : configurators) {
+ cf.add(cm);
+ }
+ VersionModel vm = new VersionModel(version, date, files.clone(), requires.clone(), cf);
+ vm.notes = notes;
+ return this;
+ }
+
+ @Override
+ public String toString() {
+ return version + "/" + date;
+ }
+
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+package fr.gouv.finances.cp.xemelios.utils;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.StringWriter;
+import java.io.Writer;
+
+import org.apache.commons.lang.StringEscapeUtils;
+import org.w3c.dom.Attr;
+import org.w3c.dom.CDATASection;
+import org.w3c.dom.Comment;
+import org.w3c.dom.Document;
+import org.w3c.dom.DocumentFragment;
+import org.w3c.dom.DocumentType;
+import org.w3c.dom.Element;
+import org.w3c.dom.Entity;
+import org.w3c.dom.EntityReference;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.w3c.dom.Notation;
+import org.w3c.dom.ProcessingInstruction;
+import org.w3c.dom.Text;
+
+/**
+ * TextWriter takes a Document, DocumentFragment, or Element and streams it
+ * as text or HTML to an output source (or a String)
+ *
+ */
+
+public final class TextWriter {
+ private static final String DefaultIndentBuffer;
+ private String defaultEncoding = "ISO-8859-1";
+ static {
+ StringBuffer sb = new StringBuffer(256);
+ for ( int i = 0; i < 256; i++ )
+ sb.append(' ');
+ DefaultIndentBuffer = sb.toString();
+ }
+
+ private Node node;
+ private boolean produceHTML;
+ private boolean prettyPrint;
+ private int indentSize = 4;
+ private int indentLevel = 0;
+ private String indentTemplate = DefaultIndentBuffer;
+ private StringBuffer textBuffer = new StringBuffer();
+
+ public TextWriter(Node node, boolean produceHTML, boolean prettyPrint, int indentSize) {
+ this.node = node;
+ this.produceHTML = produceHTML;
+ this.prettyPrint = prettyPrint;
+ this.indentSize = indentSize;
+ }
+
+ public TextWriter(Node node, boolean produceHTML, boolean prettyPrint) {
+ this.node = node;
+ this.produceHTML = produceHTML;
+ this.prettyPrint = prettyPrint;
+ }
+
+ public TextWriter(Node node, boolean produceHTML) {
+ this.node = node;
+ this.produceHTML = produceHTML;
+ }
+
+ public TextWriter(Node node) {
+ this.node = node;
+ }
+ public TextWriter(Node node,String encoding) {
+ this.node=node;
+ if(encoding!=null)
+ this.defaultEncoding=encoding;
+ }
+
+ public boolean isProduceHTML() {
+ return produceHTML;
+ }
+
+ public void setProduceHTML(boolean produceHTML) {
+ this.produceHTML = produceHTML;
+ }
+
+ public boolean isPrettyPrint() {
+ return prettyPrint;
+ }
+
+ public void setPrettyPrint(boolean prettyPrint) {
+ this.prettyPrint = prettyPrint;
+ }
+
+ private void writeNode(Writer writer, Node node) throws IOException {
+ short type = node.getNodeType();
+ switch ( type ) {
+
+ case Node.DOCUMENT_NODE:
+ document(writer, (Document)node);
+ break;
+
+ case Node.DOCUMENT_FRAGMENT_NODE:
+ documentFragment(writer, (DocumentFragment)node);
+ break;
+
+ case Node.DOCUMENT_TYPE_NODE:
+ documentType(writer, (DocumentType)node);
+ break;
+
+ case Node.ELEMENT_NODE:
+ element(writer, (Element)node);
+ break;
+
+ case Node.ATTRIBUTE_NODE:
+ attribute(writer, (Attr)node);
+ break;
+
+ case Node.ENTITY_REFERENCE_NODE:
+ entityReference(writer, (EntityReference)node);
+ break;
+
+ case Node.ENTITY_NODE:
+ entity(writer, (Entity)node);
+ break;
+
+ case Node.NOTATION_NODE:
+ notation(writer, (Notation)node);
+ break;
+
+ case Node.PROCESSING_INSTRUCTION_NODE:
+ procInst(writer, (ProcessingInstruction)node);
+ break;
+
+ case Node.TEXT_NODE:
+ text(writer, (Text)node);
+ break;
+
+ case Node.CDATA_SECTION_NODE:
+ cDataSection(writer, (CDATASection)node);
+ break;
+
+ case Node.COMMENT_NODE:
+ comment(writer, (Comment)node);
+ break;
+ }
+ }
+
+ private String getChildText(Node node) {
+ StringBuffer sb = new StringBuffer();
+ NodeList l = node.getChildNodes();
+ int size = l.getLength();
+ for ( int i = 0; i < size; i++ ) {
+ Node n = l.item(i);
+ if ( n.getNodeType() == Node.TEXT_NODE ) {
+ Text t = (Text)n;
+ sb.append(t.getData());
+ }
+ else
+ return null;
+ }
+ return sb.toString();
+ }
+
+ private void writeChildren(Writer writer, Node node) throws IOException {
+ NodeList l = node.getChildNodes();
+ int size = l.getLength();
+ for ( int i = 0; i < size; i++ ) {
+ Node n = l.item(i);
+ writeNode(writer, n);
+ }
+ }
+
+
+ private void document(Writer writer, Document doc) throws IOException {
+ if ( !produceHTML ) {
+ writer.write("<?xml version=\"1.0\" encoding=\"");
+ writer.write(defaultEncoding);
+ writer.write("\"?>\n");
+ }
+ writeChildren(writer, doc);
+ }
+
+ private void documentFragment(Writer writer, DocumentFragment fragment) throws IOException {
+ writeChildren(writer, fragment);
+ }
+
+ private void documentType(Writer writer, DocumentType docType) throws IOException {
+ writer.write("<!DOCTYPE ");
+ writer.write(docType.getName());
+ String pubID = docType.getPublicId();
+ String sysID = docType.getSystemId();
+ if ( pubID != null ) {
+ writer.write(" PUBLIC ");
+ writer.write(pubID);
+ if ( sysID != null ) {
+ writer.write(' ');
+ writer.write(sysID);
+ }
+ }
+ else if ( sysID != null ) {
+ writer.write(" SYSTEM ");
+ writer.write(sysID);
+ }
+
+ String is = docType.getInternalSubset();
+ if ( is != null ) {
+ writer.write(" [");
+ writer.write(is);
+ writer.write("]");
+ }
+ writer.write(">\n");
+ }
+
+ private void element(Writer writer, Element elem) throws IOException {
+ if ( prettyPrint ) {
+ checkTextBuffer(writer);
+ indent(writer);
+ }
+
+ String n = elem.getTagName();
+ writer.write('<');
+ writeText(writer, n);
+
+ NamedNodeMap a = elem.getAttributes();
+ int size = a.getLength();
+ for ( int i = 0; i < size; i++ ) {
+ Attr att = (Attr)a.item(i);
+ writer.write(' ');
+ writeNode(writer, att);
+ }
+
+ if ( elem.hasChildNodes() ) {
+ writer.write('>');
+
+ if ( prettyPrint ) {
+ String text = getChildText(elem);
+ if ( text != null )
+ writeEscapedText(writer, normalizeString(text), false);
+ else {
+ writer.write('\n');
+ indentLevel++;
+ writeChildren(writer, elem);
+ checkTextBuffer(writer);
+ indentLevel--;
+ indent(writer);
+ }
+ }
+ else
+ writeChildren(writer, elem);
+
+ writer.write("</");
+ writeText(writer, n);
+ writer.write('>');
+ }
+ else {
+ if ( produceHTML )
+ writer.write(">");
+ else
+ writer.write("/>");
+ }
+
+ if ( prettyPrint )
+ writer.write('\n');
+ }
+
+ private void attribute(Writer writer, Attr attr) throws IOException {
+ writeText(writer, attr.getName());
+ writer.write("=\"");
+ //writeEscapedText(writer, attr.getValue(), true);
+ writer.write(StringEscapeUtils.escapeXml(attr.getValue()));
+ writer.write("\"");
+ }
+
+ private void entityReference(Writer writer, EntityReference entityRef) throws IOException {
+ }
+
+ private void entity(Writer writer, Entity entity) throws IOException {
+ }
+
+ private void notation(Writer writer, Notation notation) throws IOException {
+ if ( prettyPrint ) {
+ checkTextBuffer(writer);
+ indent(writer);
+ }
+
+ writer.write("<!NOTATION ");
+ writer.write(notation.getNodeName());
+ String pubID = notation.getPublicId();
+ String sysID = notation.getSystemId();
+ if ( pubID != null ) {
+ writer.write(" PUBLIC ");
+ writer.write(pubID);
+ if ( sysID != null ) {
+ writer.write(' ');
+ writer.write(sysID);
+ }
+ }
+ else if ( sysID != null ) {
+ writer.write(" SYSTEM ");
+ writer.write(sysID);
+ }
+ writer.write(">\n");
+ }
+
+ private void procInst(Writer writer, ProcessingInstruction pi) throws IOException {
+ if ( prettyPrint ) {
+ checkTextBuffer(writer);
+ indent(writer);
+ }
+
+ writer.write("<?");
+ writeText(writer, pi.getTarget());
+ writer.write(" ");
+ writeText(writer, pi.getData());
+ writer.write("?>\n");
+ }
+
+ private void text(Writer writer, Text text) throws IOException {
+ if ( prettyPrint )
+ textBuffer.append(text.getData());
+ else
+ writeEscapedText(writer, text.getData(), false);
+ }
+
+ private void cDataSection(Writer writer, CDATASection cdata) throws IOException {
+ if ( prettyPrint ) {
+ checkTextBuffer(writer);
+ indent(writer);
+ }
+
+ writer.write("<![CDATA[");
+ writer.write(cdata.getData());
+ writer.write("]]>");
+
+ if ( prettyPrint )
+ writer.write('\n');
+ }
+
+ private void comment(Writer writer, Comment comment) throws IOException {
+ if ( prettyPrint ) {
+ checkTextBuffer(writer);
+ indent(writer);
+ }
+
+ writer.write("<!--");
+ writeText(writer, comment.getData());
+ writer.write("-->");
+
+ if ( prettyPrint )
+ writer.write('\n');
+ }
+
+ private void writeText(Writer writer, String text) throws IOException {
+ if ( text != null )
+ writer.write(text);
+ }
+
+ private void writeEscapedText(Writer writer, String text, boolean attr) throws IOException {
+ if ( text != null ) {
+ char[] value = text.toCharArray();
+ String outval = null;
+ int start = 0;
+ int len = 0;
+ for ( int i = 0; i < value.length; i++ ) {
+ char c = value[i];
+ switch ( c ) {
+ case '\"':
+ outval = """;
+ break;
+
+ case '<':
+ outval = "<";
+ break;
+
+ case '>':
+ outval = ">";
+ break;
+
+ case '&':
+ if ( produceHTML && attr )
+ len++;
+ else
+ outval = "&";
+ break;
+
+ case '\'':
+ if ( produceHTML )
+ len++;
+ else
+ outval = "'";
+ break;
+
+ case ' ':
+ case '\n':
+ case '\r':
+ case '\t':
+ len++;
+ continue;
+
+ default:
+// if ( c < ' ' || c == 127 ) {
+// outval = "&#x" + Integer.toHexString(c) + ";";
+// break;
+// }
+// else {
+ len++;
+ continue;
+// }
+ }
+
+ if ( outval != null ) {
+ if ( len > 0 ) {
+ String s = new String(value,start,len);
+ writer.write(value, start, len);
+ }
+ writer.write(outval);
+ start = i + 1;
+ len = 0;
+ outval = null;
+ }
+ }
+ if ( len > 0 )
+ writer.write(value, start, len);
+ }
+ }
+
+ private void checkTextBuffer(Writer writer) throws IOException {
+ if ( textBuffer.length() > 0 ) {
+ String val = normalizeString(textBuffer.toString());
+ textBuffer.setLength(0);
+ if ( val.length() > 0 ) {
+ indent(writer);
+ writeEscapedText(writer, val, false);
+ writer.write('\n');
+ }
+ }
+ }
+
+ private void indent(Writer writer) throws IOException {
+ indent(writer, indentLevel);
+ }
+
+ private void indent(Writer writer, int level) throws IOException {
+ int size = level * indentSize;
+ if ( size > 0 ) {
+ if ( indentTemplate.length() < size ) {
+ StringBuffer sb = new StringBuffer(indentTemplate);
+ for ( int i = indentTemplate.length(); i < size; i++ )
+ sb.append(' ');
+ indentTemplate = sb.toString();
+ }
+ writer.write(indentTemplate.substring(0, size));
+ }
+ }
+
+ private String normalizeString(String value) {
+ char[] c = value.toCharArray();
+ char[] n = new char[c.length];
+ boolean white = true;
+ int pos = 0;
+ for ( int i = 0; i < c.length; i++ ) {
+ if ( " \t\n\r".indexOf(c[i]) != -1 ) {
+ if ( !white ) {
+ n[pos++] = ' ';
+ white = true;
+ }
+ }
+ else {
+ n[pos++] = c[i];
+ white = false;
+ }
+ }
+ if ( white && pos > 0 )
+ pos--;
+ return new String(n, 0, pos);
+ }
+
+ /**
+ * write writes the specified node to the writer as text.
+ *
+ * @param node The Node to write
+ * @param writer The Writer to write to
+ */
+ public static void write(Node node, Writer writer) throws IOException {
+ new TextWriter(node).write(writer);
+ }
+
+ /**
+ * writeHTML writes the specified node to the writer as HTML.
+ *
+ * @param node The Node to write
+ * @param writer The Writer to write to
+ */
+ public static void writeHTML(Node node, Writer writer) throws IOException {
+ new TextWriter(node, true).write(writer);
+ }
+
+ /**
+ * writePretty writes the specified node to the writer as pretty text.
+ *
+ * @param node The Node to write
+ * @param writer The Writer to write to
+ */
+ public static void writePretty(Node node, Writer writer) throws IOException {
+ new TextWriter(node, false, true).write(writer);
+ }
+
+ /**
+ * writePrettyHTML writes the specified node to the writer as pretty HTML.
+ *
+ * @param node The Node to write
+ * @param writer The Writer to write to
+ */
+ public static void writePrettyHTML(Node node, Writer writer) throws IOException {
+ new TextWriter(node, true, true).write(writer);
+ }
+
+ /**
+ * write writes the node to the writer as text.
+ *
+ * @param writer The Writer to write to
+ */
+ public void write(Writer writer) throws IOException {
+ try {
+ BufferedWriter buf = new BufferedWriter(writer, 4096);
+ writeNode(buf, node);
+ buf.flush();
+ }
+ catch ( Exception e ) {
+ e.printStackTrace(System.err);
+ }
+ }
+
+ /**
+ * write writes the specified node to the OutputStream as text.
+ *
+ * @param node The Node to write
+ * @param output The OutputStream to write to
+ */
+ public static void write(Node node, OutputStream output) throws IOException {
+ new TextWriter(node).write(output);
+ }
+
+ /**
+ * writeHTML writes the specified node to the OutputStream as HTML.
+ *
+ * @param node The Node to write
+ * @param output The OutputStream to write to
+ */
+ public static void writeHTML(Node node, OutputStream output) throws IOException {
+ new TextWriter(node, true).write(output);
+ }
+
+ /**
+ * writePretty writes the specified node to the OutputStream as pretty text.
+ *
+ * @param node The Node to write
+ * @param output The OutputStream to write to
+ */
+ public static void writePretty(Node node, OutputStream output) throws IOException {
+ new TextWriter(node, false, true).write(output);
+ }
+
+ /**
+ * writePrettyHTML writes the specified node to the OutputStream as pretty HTML.
+ *
+ * @param node The Node to write
+ * @param output The OutputStream to write to
+ */
+ public static void writePrettyHTML(Node node, OutputStream output) throws IOException {
+ new TextWriter(node, true, true).write(output);
+ }
+
+ /**
+ * write writes the node to the OutputStream as text.
+ *
+ * @param output The OutputStream to write to
+ */
+ public void write(OutputStream output) throws IOException {
+ try {
+ OutputStreamWriter o = new OutputStreamWriter(output, "UTF8");
+ BufferedWriter buf = new BufferedWriter(o, 4096);
+ writeNode(buf, node);
+ buf.flush();
+ }
+ catch ( Exception e ) {
+ e.printStackTrace(System.err);
+ }
+ }
+
+ /**
+ * toString returns the node as a String.
+ *
+ * @param node The Node to convert
+ * @return The String value
+ */
+ public static String toString(Node node) {
+ return new TextWriter(node).toString();
+ }
+ public static String toString(Node node,String encoding) {
+ return new TextWriter(node,encoding).toString();
+ }
+
+ /**
+ * toHTMLString returns the node as a HTML String.
+ *
+ * @param node The Node to convert
+ * @return The String value
+ */
+ public static String toHTMLString(Node node) {
+ return new TextWriter(node, true).toString();
+ }
+
+ /**
+ * toPrettyString returns the node as a Pretty String.
+ *
+ * @param node The Node to convert
+ * @return The String value
+ */
+ public static String toPrettyString(Node node) {
+ return new TextWriter(node, false, true).toString();
+ }
+
+ /**
+ * toPrettyHTMLString returns the node as a Pretty HTML String.
+ *
+ * @param node The Node to convert
+ * @return The String value
+ */
+ public static String toPrettyHTMLString(Node node) {
+ return new TextWriter(node, true, true).toString();
+ }
+
+ /**
+ * toString returns the node as a String.
+ *
+ * @return The String value
+ */
+ @Override
+ public String toString() {
+ StringWriter writer = new StringWriter();
+ try {
+ write(writer);
+ return writer.toString();
+ }
+ catch ( Exception e ) {
+ e.printStackTrace(System.err);
+ return null;
+ }
+ }
+}
+
+
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.widgets;
+
+import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.WidgetModel;
+import fr.gouv.finances.cp.xemelios.ui.resulttable.EtatResultTableModel;
+
+/**
+ *
+ * @author chm
+ */
+public abstract class AbstractWidget {
+ private WidgetModel wm;
+ private ElementModel em;
+
+ /** Creates a new instance of Widget */
+ public AbstractWidget(WidgetModel wm, ElementModel em) {
+ super();
+ this.wm=wm;
+ this.em=em;
+ }
+ public final WidgetModel getWidgetModel() { return wm; }
+ public final ElementModel getElementModel() { return em; }
+
+ public abstract void run(EtatResultTableModel etrm,int row);
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.widgets.generic;
+
+import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.WidgetModel;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.dgfip.xemelios.data.DataHandler;
+import fr.gouv.finances.cp.xemelios.ui.resulttable.EtatResultTableModel;
+import fr.gouv.finances.cp.xemelios.widgets.AbstractWidget;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
+import java.io.File;
+import java.io.FileOutputStream;
+import javax.swing.JFileChooser;
+import javax.swing.JOptionPane;
+import javax.swing.filechooser.FileFilter;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import org.apache.log4j.Logger;
+import org.w3c.dom.Document;
+
+/**
+ *
+ * @author chm
+ */
+public class SaveAs extends AbstractWidget {
+ private static Logger logger = Logger.getLogger(SaveAs.class);
+
+ /** Creates a new instance of SaveAs */
+ public SaveAs(WidgetModel wm, ElementModel em) {
+ super(wm,em);
+ }
+ @Override
+ public void run(EtatResultTableModel etrm,int row) {
+ try {
+ DataHandler dh = etrm.getRowAt(row,0);
+ Document doc = dh.getDocument();
+ String encoding = dh.getDocumentEncoding();
+ TransformerFactory tf = FactoryProvider.getTransformerFactory();
+ Transformer t = tf.newTransformer();
+ t.setOutputProperty(OutputKeys.ENCODING,encoding);
+ JFileChooser chooser = new JFileChooser();
+ chooser.setDialogTitle("Enregistrer "+("male".equals(getWidgetModel().getParam("gender").getValue())?"le":"la")+" "+getElementModel().getTitre()+" sous...");
+ // @todo: mettre les bons filtres
+// chooser.addChoosableFileFilter(new LocalFileFilter("XML","Fichiers XML"));
+// chooser.addChoosableFileFilter(new LocalFileFilter(getElementModel().getParent().getParent().getExtension(),getElementModel().getParent().getParent().getTitre()));
+// chooser.addChoosableFileFilter(new FileFilter() {
+// public boolean accept(File f) { return true; }
+// public String getDescription() { return "Tous les fichiers"; }
+// });
+ chooser.setFileFilter(new FileFilter(){
+ @Override
+ public boolean accept(File f) {
+ return f.isDirectory() || f.getName().toUpperCase().endsWith(".XML");
+ }
+ @Override
+ public String getDescription() { return "Fichier XML"; }
+ });
+ File saveTo = null;
+ boolean bContinue = true;
+ while(bContinue) {
+ if(JFileChooser.APPROVE_OPTION==chooser.showSaveDialog(MainWindow.instance)) {
+ File f = chooser.getSelectedFile();
+ String fileName = f.getAbsolutePath();
+ int len = fileName.length();
+ if(fileName.substring(len-4).indexOf('.')<0) {
+ fileName=fileName+".xml";
+ f = new File(fileName);
+ }
+ if(f.exists()) {
+ int ret = JOptionPane.showConfirmDialog(MainWindow.instance,f.getAbsolutePath()+"\nexiste. Voulez-vous l'écraser ?","Ecrasement de fichier",JOptionPane.YES_NO_CANCEL_OPTION);
+ switch (ret) {
+ case JOptionPane.NO_OPTION: break;
+ case JOptionPane.YES_OPTION: saveTo=f;
+ case JOptionPane.CANCEL_OPTION: bContinue=false;
+ }
+ } else {
+ saveTo = f;
+ bContinue=false;
+ }
+ } else {
+ bContinue = false;
+ }
+ }
+ if(saveTo!=null) {
+ logger.debug("writting");
+ FileOutputStream fos = new FileOutputStream(saveTo,false);
+ StreamResult sr = new StreamResult(fos);
+ t.transform(new DOMSource(doc),sr);
+ fos.flush(); fos.close();
+ }
+ } catch(Exception ex) {
+ logger.error("in run: ",ex);
+ }
+ }
+
+ private static class LocalFileFilter extends FileFilter {
+ private String ext, description;
+ public LocalFileFilter(String ext, String desc) {
+ super();
+ this.ext=ext;
+ this.description=desc;
+ }
+ @Override
+ public boolean accept(File f) {
+ return f.isDirectory() || f.getName().toUpperCase().equals(ext);
+ }
+
+ @Override
+ public String getDescription() { return description; }
+ }
+
+}
--- /dev/null
+/*
+ * Copyright
+ * 2007 axYus - www.axyus.com
+ * 2007 C.Marchand - christophe.marchand@axyus.com
+ *
+ * This file is part of XEMELIOS.
+ *
+ * XEMELIOS 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.
+ *
+ * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+package fr.gouv.finances.cp.xemelios.widgets.generic;
+
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.WidgetModel;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.dgfip.xemelios.data.DataHandler;
+import fr.gouv.finances.cp.xemelios.ui.resulttable.EtatResultTableModel;
+import fr.gouv.finances.cp.xemelios.widgets.AbstractWidget;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
+import fr.gouv.finances.dgfip.xemelios.utils.FileUtils;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.transform.stream.StreamSource;
+import org.w3c.dom.Document;
+
+/**
+ *
+ * @author chm
+ */
+public class ViewCode extends AbstractWidget {
+ private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(ViewCode.class);
+
+ public ViewCode(WidgetModel wm, ElementModel em) {
+ super(wm,em);
+ }
+
+ @Override
+ public void run(EtatResultTableModel etrm, int row) {
+ try {
+ DataHandler dh = etrm.getRowAt(row,0);
+ Document doc = dh.getDocument();
+ String encoding = dh.getDocumentEncoding();
+ TransformerFactory tf = FactoryProvider.getTransformerFactory();
+ Transformer t = tf.newTransformer(new StreamSource(new File(new File(MainWindow.instance.getEnvProperties().replace("${"+Constants.SYS_PROP_RESOURCES_LOCATION+"}")),"XMLPrettyPrint.xsl")));
+ File tmp = File.createTempFile("xemelios-data-",".xml",FileUtils.getTempDir());
+ FileOutputStream fos = new FileOutputStream(tmp,false);
+ StreamResult sr = new StreamResult(fos);
+ t.setParameter("title", getElementModel().getParent().getParent().getTitre());
+ t.transform(new DOMSource(doc),sr);
+ fos.flush(); fos.close();
+ MainWindow.instance.displayHtmlStream(tmp, getElementModel().getParent());
+ Transformer t2 = tf.newTransformer();
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ t2.transform(new DOMSource(doc), new StreamResult(baos));
+ baos.flush(); baos.close();
+ logger.debug(baos.toString());
+ } catch(Exception ex) {
+ // TODO
+ }
+ }
+
+}
--- /dev/null
+Manifest-version: 1.0
+Jar-Version: @version@
+Jar-Content: @name@
\ No newline at end of file
--- /dev/null
+Manifest-version: 1.0
+Jar-Version: @version@
+Jar-Content: @name@
+Main-Class: fr.gouv.finances.cp.xemelios.controls.editors.CommandLineController
+Class-Path: lib/core-xemelios.jar lib/commons-dbcp-1.2.2.jar lib/commons-httpclient-3.1-rc1.jar lib/commons-io-1.4.jar lib/commons-pool-1.3.jar lib/jacksum.jar lib/jxl.jar lib/log4j.jar lib/relaxngDatatype.jar lib/saxon9-dom.jar lib/saxon9-dom4j.jar lib/saxon9-jdom.jar lib/saxon9-s9api.jar lib/saxon9-sql.jar lib/saxon9-xom.jar lib/saxon9-xpath.jar lib/saxon9-xqj.jar lib/saxon9.jar lib/swing-worker.jar lib/xercesImpl.jar lib/xml-apis.jar lib/activation.jar lib/bc-jce-jdk13-129.jar lib/commons-codec-1.3.jar lib/xml-marshall.jar lib/xemelios.jar lib/forms-1.0.5.jar lib/swing-layout-1.0.3.jar lib/swingx-0.8.0.jar lib/core-renderer.jar lib/iText-2.0.8.jar lib/controls-pesv2.jar
--- /dev/null
+<?xml version="1.0"?>
+<!--
+ Copyright
+ 2009 axYus - www.axyus.com
+ 2009 C.Marchand - christophe.marchand@axyus.com
+
+ This file is part of XEMELIOS.
+
+ XEMELIOS 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.
+
+ XEMELIOS 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 XEMELIOS; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+-->
+
+<xsl:stylesheet version="1.0"
+ xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
+ xmlns="http://www.w3.org/1999/xhtml">
+<xsl:param name="title"/>
+ <xsl:output method="xml" indent="yes"/>
+
+ <xsl:variable name="debug" select="'true'"/>
+
+ <xsl:template match="/">
+ <html>
+ <head>
+ <title>Source XML de <xsl:value-of select="$title"/></title>
+ <style type="text/css">
+ span { font-family: monospace; font-size: 12px; }
+ .expander-content {
+ padding-left: 1em;
+ }
+
+ .expander {
+ text-align: center;
+ vertical-align: top;
+ width: 1em;
+ display: inline-block;
+ margin-left: -1em;
+ }
+
+ #top > .expander-open, #top > .expander-closed {
+ margin-left: 1em;
+ }
+
+ .expander-closed > .expander-content {
+ display: none;
+ }
+ .comment {
+ font-family: monospace;
+ font-size: 12px;
+ white-space: pre;
+ }
+ #top > .expander-open {
+ font-family: monospace;
+ font-size: 12px;
+ white-space: pre;
+ }
+ *|*:root {
+ background-color: white;
+ }
+ #viewsource {
+ font-family: monospace;
+ font-size: 12px;
+ font-weight: normal;
+ color: black;
+ white-space: pre;
+ }
+ #viewsource.wrap {
+ white-space: pre-wrap;
+ }
+ pre {
+ font: inherit;
+ color: inherit;
+ white-space: inherit;
+ margin: 0;
+ }
+ .start-tag {
+ color: purple;
+ font-weight: bold;
+ font-size: 12px;
+ }
+ .end-tag {
+ color: purple;
+ font-weight: bold;
+ font-size: 12px;
+ }
+ .comment {
+ color: green;
+ font-style: italic;
+ }
+ .cdata {
+ color: #CC0066;
+ }
+ .doctype {
+ color: steelblue;
+ font-style: italic;
+ }
+ .pi {
+ color: orchid;
+ font-style: italic;
+ }
+ .entity {
+ color:#FF4500;
+ font-weight: normal;
+ }
+ .text {
+ font-weight: normal;
+ }
+ .attribute-name {
+ color: black;
+ font-weight: bold;
+ }
+ .attribute-value {
+ color: blue;
+ font-weight: normal;
+ }
+ .summary {
+ display: block;
+ background-color: #FFFFCC;
+ width: 90%;
+ border: solid;
+ border-width: 1pt;
+ font-family: sans-serif;
+ }
+ .popup {
+ font-weight: normal;
+ }
+ .markupdeclaration {
+ color: steelblue;
+ font-style: italic;
+ }
+ .error, .error > .start-tag, .error > .end-tag,
+ .error > .comment, .error > .cdata, .error > .doctype,
+ .error > .pi, .error > .entity, .error > .attribute-name,
+ .error > .attribute-value {
+ color: red;
+ font-weight: bold;
+ }
+ </style>
+ </head>
+ <body><xsl:apply-templates/></body>
+ </html>
+ </xsl:template>
+
+ <xsl:template match="*">
+ <xsl:if test="not(namespace-uri(.) = 'http://projets.admisource.gouv.fr/xemelios/namespaces#added' or namespace-uri(.) = 'http://projets.admisource.gouv.fr/xemelios/namespaces#anomally' or starts-with(local-name(.),'added:') or starts-with(local-name(.),'ano:')) or $debug='true'">
+ <div>
+ <xsl:text><</xsl:text>
+ <span class="start-tag"><xsl:value-of select="name(.)"/></span>
+ <xsl:apply-templates select="@*"/>
+ <xsl:text>/></xsl:text>
+ </div>
+ </xsl:if>
+ </xsl:template>
+
+ <xsl:template match="*[node()]">
+ <xsl:if test="not(namespace-uri(.) = 'http://projets.admisource.gouv.fr/xemelios/namespaces#added' or namespace-uri(.) = 'http://projets.admisource.gouv.fr/xemelios/namespaces#anomally' or starts-with(local-name(.),'added:') or starts-with(local-name(.),'ano:')) or $debug='true'">
+ <div>
+ <xsl:text><</xsl:text>
+ <span class="start-tag"><xsl:value-of select="name(.)"/></span>
+ <xsl:apply-templates select="@*"/>
+ <xsl:text>></xsl:text>
+
+ <span class="text"><xsl:value-of select="."/></span>
+
+ <xsl:text></</xsl:text>
+ <span class="end-tag"><xsl:value-of select="name(.)"/></span>
+ <xsl:text>></xsl:text>
+ </div>
+ </xsl:if>
+ </xsl:template>
+
+ <xsl:template match="*[* or processing-instruction() or comment() or string-length(.) > 50]">
+ <xsl:if test="not(namespace-uri(.) = 'http://projets.admisource.gouv.fr/xemelios/namespaces#added' or namespace-uri(.) = 'http://projets.admisource.gouv.fr/xemelios/namespaces#anomally' or starts-with(local-name(.),'added:') or starts-with(local-name(.),'ano:')) or $debug='true'">
+ <div class="expander-open">
+ <xsl:call-template name="expander"/>
+
+ <xsl:text><</xsl:text>
+ <span class="start-tag"><xsl:value-of select="name(.)"/></span>
+ <xsl:apply-templates select="@*"/>
+ <xsl:text>></xsl:text>
+
+ <div class="expander-content"><xsl:apply-templates/></div>
+
+ <xsl:text></</xsl:text>
+ <span class="end-tag"><xsl:value-of select="name(.)"/></span>
+ <xsl:text>></xsl:text>
+ </div>
+ </xsl:if>
+ </xsl:template>
+
+ <xsl:template match="@*">
+ <xsl:if test="not(namespace-uri(.) = 'http://projets.admisource.gouv.fr/xemelios/namespaces#added' or namespace-uri(.) = 'http://projets.admisource.gouv.fr/xemelios/namespaces#anomally' or starts-with(local-name(.),'added:') or starts-with(local-name(.),'ano:')) or $debug='true'">
+ <xsl:text> </xsl:text>
+ <span class="attribute-name"><xsl:value-of select="name(.)"/></span>
+ <xsl:text>=</xsl:text>
+ <span class="attribute-value">"<xsl:value-of select="."/>"</span>
+ </xsl:if>
+ </xsl:template>
+
+ <xsl:template match="text()">
+ <xsl:if test="normalize-space(.)">
+ <xsl:value-of select="."/>
+ </xsl:if>
+ </xsl:template>
+
+ <xsl:template match="processing-instruction()">
+ <div class="pi">
+ <xsl:text><?</xsl:text>
+ <xsl:value-of select="name(.)"/>
+ <xsl:text> </xsl:text>
+ <xsl:value-of select="."/>
+ <xsl:text>?></xsl:text>
+ </div>
+ </xsl:template>
+
+ <xsl:template match="processing-instruction()[string-length(.) > 50]">
+ <div class="expander-open">
+ <xsl:call-template name="expander"/>
+
+ <span class="pi">
+ <xsl:text> <?</xsl:text>
+ <xsl:value-of select="name(.)"/>
+ </span>
+ <div class="expander-content pi"><xsl:value-of select="."/></div>
+ <span class="pi">
+ <xsl:text>?></xsl:text>
+ </span>
+ </div>
+ </xsl:template>
+
+ <xsl:template match="comment()">
+ <div class="comment">
+ <xsl:text><!--</xsl:text>
+ <xsl:value-of select="."/>
+ <xsl:text>--></xsl:text>
+ </div>
+ </xsl:template>
+
+ <xsl:template match="comment()[string-length(.) > 50]">
+ <div class="expander-open">
+ <xsl:call-template name="expander"/>
+
+ <span class="comment">
+ <xsl:text><!--</xsl:text>
+ </span>
+ <div class="expander-content comment">
+ <xsl:value-of select="."/>
+ </div>
+ <span class="comment">
+ <xsl:text>--></xsl:text>
+ </span>
+ </div>
+ </xsl:template>
+
+ <xsl:template name="expander">
+ <!--div class="expander">−</div-->
+ </xsl:template>
+
+</xsl:stylesheet>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" ?>\r
+<!DOCTYPE log4j:configuration PUBLIC "-//Apache Software Foundation//DTD log4j Configuration 1.0//EN" "log4j.dtd">\r
+\r
+<log4j:configuration threshold="all" debug="false">\r
+\r
+ <appender name="rollingFile" class="org.apache.log4j.RollingFileAppender">\r
+ <param name="File" value="xemelios.log" />\r
+ <param name="MaxFileSize" value="100KB"/>\r
+ <param name="MaxBackupIndex" value="5"/>\r
+ <layout class="org.apache.log4j.PatternLayout">\r
+ <param name="ConversionPattern" value="%-5p [%c{2}] %t %d{HH:mm:ss,SSS}: %m%n"/>\r
+ </layout>\r
+ </appender>\r
+ \r
+ <appender name="console.appender" class="org.apache.log4j.ConsoleAppender">\r
+ <layout class="org.apache.log4j.PatternLayout">\r
+ <param name="ConversionPattern" value="%-5p [%c{3}] %t: %m%n"/>\r
+ </layout>\r
+ </appender>\r
+ \r
+ <logger name="httpclient">\r
+ <level value="error"/>\r
+ <appender-ref ref="console.appender"/>\r
+ </logger>\r
+ \r
+ <logger name="org.apache.commons">\r
+ <level value="info"/>\r
+ <appender-ref ref="console.appender"/>\r
+ </logger>\r
+\r
+ <logger name="fr.gouv.finances">\r
+ <level value="info"/>\r
+ <appender-ref ref="rollingFile"/>\r
+ </logger>\r
+\r
+ <logger name="fr.gouv.finances.dgfip.xemelios.data.utils.jdbc">\r
+ <level value="error"/>\r
+ <appender-ref ref="rollingFile"/>\r
+ </logger>\r
+\r
+</log4j:configuration>\r
--- /dev/null
+<html xmlns:o="urn:schemas-microsoft-com:office:office"\r
+xmlns:x="urn:schemas-microsoft-com:office:excel"\r
+xmlns="http://www.w3.org/TR/REC-html40">\r
+\r
+<head>\r
+<meta http-equiv=Content-Type content="text/html; charset=windows-1252">\r
+<meta name=ProgId content=Excel.Sheet>\r
+<style>\r
+<!--table\r
+ {mso-displayed-decimal-separator:"\.";\r
+ mso-displayed-thousand-separator:" ";}\r
+@page\r
+ {margin:.98in .79in .98in .79in;\r
+ mso-header-margin:.49in;\r
+ mso-footer-margin:.49in;}\r
+tr\r
+ {mso-height-source:auto;}\r
+col\r
+ {mso-width-source:auto;}\r
+br\r
+ {mso-data-placement:same-cell;}\r
+.style0\r
+ {mso-number-format:General;\r
+ text-align:general;\r
+ vertical-align:bottom;\r
+ white-space:nowrap;\r
+ mso-rotate:0;\r
+ mso-background-source:auto;\r
+ mso-pattern:auto;\r
+ color:windowtext;\r
+ font-size:10.0pt;\r
+ font-weight:400;\r
+ font-style:normal;\r
+ text-decoration:none;\r
+ font-family:Arial;\r
+ mso-generic-font-family:auto;\r
+ mso-font-charset:0;\r
+ border:none;\r
+ mso-protection:locked visible;\r
+ mso-style-name:Normal;\r
+ mso-style-id:0;}\r
+td\r
+ {mso-style-parent:style0;\r
+ padding-top:1px;\r
+ padding-right:1px;\r
+ padding-left:1px;\r
+ mso-ignore:padding;\r
+ color:windowtext;\r
+ font-size:10.0pt;\r
+ font-weight:400;\r
+ font-style:normal;\r
+ text-decoration:none;\r
+ font-family:Arial;\r
+ mso-generic-font-family:auto;\r
+ mso-font-charset:0;\r
+ mso-number-format:General;\r
+ text-align:general;\r
+ vertical-align:bottom;\r
+ border:none;\r
+ mso-background-source:auto;\r
+ mso-pattern:auto;\r
+ mso-protection:locked visible;\r
+ white-space:nowrap;\r
+ mso-rotate:0;}\r
+.axyusTitre\r
+ {\r
+ font-size:14.0pt;\r
+ font-weight:bold;\r
+ text-align:left;}\r
+.axyusNomsChamps\r
+ {\r
+ font-size:12.0pt;\r
+ font-weight:bold;\r
+ text-align:left;}\r
+.axyusText\r
+ {mso-style-parent:style0;\r
+ mso-number-format:"\@";\r
+ text-align:left;}\r
+.axyusInteger\r
+ {mso-style-parent:style0;\r
+ mso-number-format:0;\r
+ white-space:normal;}\r
+.axyusFloat\r
+ {mso-style-parent:style0;\r
+ mso-number-format:"0\.00";\r
+ white-space:normal;}\r
+.axyusDate\r
+ {mso-style-parent:style0;\r
+ mso-number-format:"Short Date";}\r
+-->\r
+</style>\r
+\r
+</head>\r