//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.Constants;
import fr.gouv.finances.dgfip.xemelios.common.ToolException;
// Recuperer le path du navigateuir dans le registre
// 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]);
-
- }
+ public static Logger logger = Logger.getLogger(StartUrl.class);
+
+ public static void startUrl(final 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) {
+
+ final String osName = System.getProperty("os.name");
+ try {
+ if (osName.startsWith("Mac OS")) {
+ // Mac OS X can handle file types itself (thank goodness!)
+ final Class fileMgr = Class.forName("com.apple.eio.FileManager");
+ final 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")) {
+ final 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) {
+ throw new Exception("Could not find PDF Viewer");
+ } else { // got a pdf viewer, so launch it
+ final 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")) {
+ final 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) {
+ throw new Exception("Could not find web browser");
+ } else {
+ Runtime.getRuntime().exec(new String[] { browser, url });
+ }
+ } else {
+ // try with browser
+ final 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) {
+ throw new Exception("Could not find web browser");
+ } else {
+ Runtime.getRuntime().exec(new String[] { browser, url });
+ }
+ }
+ }
+ } catch (final Exception e) { // bollux!
+ JOptionPane.showMessageDialog(null, e.getMessage());
+ }
+ }
+
+ public static void main(final 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]);
+
+ }
}
import java.awt.BorderLayout;
import java.awt.Dialog;
import java.awt.FlowLayout;
+import java.awt.Frame;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
+import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.PrintWriter;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
-import fr.gouv.finances.dgfip.utils.WordWrap;
-import java.awt.Window;
import org.apache.log4j.Logger;
+import fr.gouv.finances.dgfip.utils.WordWrap;
+
/**
- * A dialog to display exceptions. You can use helper-methods
- * {@link #displayException(Dialog,Throwable)} and {@link #displayException(Frame,Throwable)}
+ * 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);
- }
- }
- }
+ 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(final Window owner, final Throwable toDisplay) throws HeadlessException {
+ super(owner, "Erreur", Dialog.ModalityType.APPLICATION_MODAL);
+ this.initialize(toDisplay);
+ }
+
+ public DisplayExceptionDlg(final Throwable toDisplay) throws HeadlessException {
+ super();
+ this.setModal(true);
+ this.initialize(toDisplay);
+ }
+
+ protected void initialize(Throwable toDisplay) {
+ logger.error("", toDisplay);
+ while (toDisplay.getCause() != null) {
+ toDisplay = toDisplay.getCause();
+ }
+ final JPanel pane = new JPanel(new BorderLayout());
+ final String[] msg = beautify(toDisplay.getMessage());
+ final JPanel msgPane = new JPanel(new VerticalFlowLayout());
+ for (final String element : msg) {
+ msgPane.add(new JLabel(element));
+ }
+ pane.add(msgPane, BorderLayout.NORTH);
+ final StringWriter sw = new StringWriter();
+ final PrintWriter pw = new PrintWriter(sw);
+ while (toDisplay != null) {
+ toDisplay.printStackTrace(pw);
+ pw.println("caused by...");
+ toDisplay = toDisplay.getCause();
+ }
+ pw.flush();
+ final String ex = sw.toString();
+ pw.close();
+ final JTextArea ml = new JTextArea(ex);
+ ml.setColumns(60);
+ ml.setRows(20);
+ this.center = new JPanel();
+ this.center.add(new JScrollPane(ml));
+ pane.add(this.center, BorderLayout.CENTER);
+ this.center.setVisible(false);
+ final JPanel buttonPane = new JPanel(new FlowLayout(FlowLayout.CENTER));
+ buttonPane.add(this.pbClose = new JButton("Fermer"));
+ buttonPane.add(this.pbHideShow = new JButton("Afficher"));
+ pane.add(buttonPane, BorderLayout.SOUTH);
+ this.setContentPane(pane);
+ this.pbClose.addActionListener(this);
+ this.pack();
+ this.setLocationRelativeTo(this.getOwner());
+ this.pbHideShow.addActionListener(new java.awt.event.ActionListener() {
+
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent e) {
+ final boolean visible = DisplayExceptionDlg.this.center.isVisible();
+ if (visible) {
+ DisplayExceptionDlg.this.center.setVisible(false);
+ DisplayExceptionDlg.this.pbHideShow.setText("Afficher");
+ } else {
+ DisplayExceptionDlg.this.center.setVisible(true);
+ DisplayExceptionDlg.this.pbHideShow.setText("Cacher");
+ }
+ DisplayExceptionDlg.this.pack();
+ }
+ });
+ this.setVisible(true);
+ }
+
+ /**
+ * Invoked when an action occurs.
+ */
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ this.dispose();
+ }
+
+ /**
+ * Displays <tt>toDisplay</tt> exception in a EDT-thread-safe way
+ *
+ * @param owner
+ * @param toDisplay
+ */
+ public static void displayException(final Window owner, final Throwable toDisplay) {
+ final 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(final Dialog owner, final Throwable toDisplay) {
+ final 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(final String msg) {
+ if (msg == null) {
+ return new String[0];
+ }
+ final String s = WordWrap.wrap(msg, 80);
+ final StringTokenizer st = new StringTokenizer(s, "\n\r\f");
+ final 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 final Throwable t;
+
+ public Displayer(final Window owner, final Throwable t) {
+ super();
+ this.fOwner = owner;
+ this.t = t;
+ }
+
+ public Displayer(final Dialog owner, final Throwable t) {
+ super();
+ this.dOwner = owner;
+ this.t = t;
+ }
+
+ @Override
+ public void run() {
+ if (this.fOwner != null) {
+ new DisplayExceptionDlg(this.fOwner, this.t);
+ } else {
+ new DisplayExceptionDlg(this.dOwner, this.t);
+ }
+ }
+ }
}
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;
* @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);
-// }
+ /**
+ * 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 final String question;
+ private JTextField dfCode, dfLibelle;
+ private JComboBox cbxData;
+ private TreeSet<Pair> defaultValues;
+ private Timer timer = null;
+
+ public DlgGetPair(final JFrame owner, final String question) {
+ this(owner, question, TITLE);
+ }
+
+ public DlgGetPair(final JFrame owner, final String question, final String title) {
+ super(owner, title, true);
+ this.question = question;
+ this.initialize();
+ }
+
+ public DlgGetPair(final JFrame owner, final String question, final TreeSet<Pair> values) {
+ this(owner, question, values, TITLE);
+ }
+
+ public DlgGetPair(final JFrame owner, final String question, final TreeSet<Pair> values, final String title) {
+ super(owner, title, true);
+ this.question = question;
+ this.defaultValues = values;
+ this.initialize();
+ }
+
+ public DlgGetPair(final JFrame owner, final String question, final TreeSet<Pair> values, final String title, final Pair initialValue) {
+ this(owner, question, values, title);
+ if (initialValue != null) {
+ if (initialValue.key != null && initialValue.key.trim().length() > 0) {
+ this.dfCode.setText(initialValue.key);
+ if (this.cbxData != null) {
+ this.cbxData.setEnabled(false);
+ }
+ this.dfCode.setEnabled(false);
+ this.dfLibelle.grabFocus();
+ this.dfLibelle.setText(initialValue.libelle);
+ // try to find an existing lib to this code
+ if (values != null) {
+ Pair p = null;
+ for (final Pair p1 : values) {
+ if (p1.equals(initialValue)) {
+ p = p1;
+ }
+ }
+ if (p != null) {
+ this.dfLibelle.setText(p.libelle);
+ }
+ }
+ } else {
+ this.dfLibelle.setText(initialValue.libelle);
+ }
+ }
+ }
+
+ public void initialize() {
+ final int sepInfo = 2;
+ final int lineInfo = sepInfo + 2;
+ final int sepData = lineInfo + 2;
+ final int existingData = sepData + (this.defaultValues != null ? 2 : 0);
+ final int codeLine = existingData + 2;
+
+ final int libelleLine = codeLine + 2;
+ final int buttonLine = libelleLine + 2;
+
+ JTextArea area = null;
+ this.cbxData = null;
+
+ this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
+
+ final 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
+ (this.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
+ final CellConstraints cc = new CellConstraints();
+ final PanelBuilder pb = new PanelBuilder(fl);
+ final 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 (this.defaultValues != null) {
+ pb.add(iF.newLabel("Valeurs possibles", "normal"), cc.xy(3, existingData));
+ final Vector<Pair> data = new Vector<Pair>();
+ data.add(new Pair("", ""));
+ data.addAll(this.defaultValues);
+ pb.add(this.cbxData = new JComboBox(data), cc.xy(5, existingData));
+ this.cbxData.addItemListener(new ItemListener() {
+ @Override
+ public void itemStateChanged(final ItemEvent e) {
+ if (e.getStateChange() == ItemEvent.SELECTED) {
+ final JComboBox cbxData = (JComboBox) e.getSource();
+ final Pair p = (Pair) cbxData.getSelectedItem();
+ DlgGetPair.this.dfCode.setText(p.key);
+ DlgGetPair.this.dfLibelle.setText(p.libelle);
+ }
+ DlgGetPair.this.resetTimer();
+ }
+ });
+ }
+ pb.add(iF.newLabel("Code", "normal"), cc.xy(3, codeLine));
+ pb.add(this.dfCode = new JTextField(), cc.xy(5, codeLine));
+ pb.add(iF.newLabel("Libellé", "normal"), cc.xy(3, libelleLine));
+ pb.add(this.dfLibelle = new JTextField(), cc.xy(5, libelleLine));
+
+ final JPanel bPane = new JPanel(new FlowLayout(FlowLayout.CENTER));
+ this.pbCancel = new JButton(this.escapeAction);
+ this.pbOk = new JButton("Ok");
+ bPane.add(this.pbOk);
+ bPane.add(this.pbCancel);
+
+ pb.add(bPane, cc.xyw(2, buttonLine, 4));
+
+ this.dfCode.setColumns(15);
+ this.add(pb.getPanel());
+
+ area.setEditable(false);
+ area.setLineWrap(true);
+ area.setRows(3);
+ area.setBackground(this.getBackground());
+ area.setText(this.question);
+
+ if (this.defaultValues != null && this.defaultValues.size() > 0) {
+ this.cbxData.setSelectedIndex(1);
+ }
+
+ // timer stop !
+ this.dfCode.addKeyListener(new KeyListener() {
+ @Override
+ public void keyTyped(final KeyEvent e) {
+ DlgGetPair.this.resetTimer();
+ }
+
+ @Override
+ public void keyPressed(final KeyEvent e) {
+ DlgGetPair.this.resetTimer();
+ }
+
+ @Override
+ public void keyReleased(final KeyEvent e) {
+ DlgGetPair.this.resetTimer();
+ }
+ });
+ this.dfLibelle.addKeyListener(new KeyListener() {
+ @Override
+ public void keyTyped(final KeyEvent e) {
+ DlgGetPair.this.resetTimer();
+ }
+
+ @Override
+ public void keyPressed(final KeyEvent e) {
+ DlgGetPair.this.resetTimer();
+ }
+
+ @Override
+ public void keyReleased(final KeyEvent e) {
+ DlgGetPair.this.resetTimer();
+ DlgGetPair.this.resetTimer();
+ }
+ });
+ this.dfCode.addFocusListener(new FocusListener() {
+ @Override
+ public void focusGained(final FocusEvent e) { /* resetTimer(); */
+ }
+
+ @Override
+ public void focusLost(final FocusEvent e) {
+ DlgGetPair.this.resetTimer();
+ }
+ });
+ this.dfLibelle.addFocusListener(new FocusListener() {
+ @Override
+ public void focusGained(final FocusEvent e) {
+ DlgGetPair.this.resetTimer();
+ }
+
+ @Override
+ public void focusLost(final FocusEvent e) {
+ DlgGetPair.this.resetTimer();
+ }
+ });
+ this.pbOk.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ DlgGetPair.this.checkReponse();
+ }
+ });
+ this.getRootPane().setDefaultButton(this.pbOk);
+ this.pack();
+ this.setLocationRelativeTo(this.getParent());
+ }
+
+ @Override
+ protected JRootPane createRootPane() {
+ final KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
+ final JRootPane rp = new JRootPane();
+ this.escapeAction = new AbstractAction("Annuler") {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ DlgGetPair.this.ret = false;
+ DlgGetPair.this.setVisible(false);
+ }
+ };
+ rp.registerKeyboardAction(this.escapeAction, "TOTOTOTO", ks, JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
+ }
+
+ protected void checkReponse() {
+ if (this.dfCode.getText() != null && this.dfCode.getText().length() > 0 && this.dfLibelle.getText() != null && this.dfLibelle.getText().length() > 0) {
+ this.setVisible(false);
+ this.ret = true;
+ } else {
+ JOptionPane.showMessageDialog(this, "Le code ainsi que le libelle sont obligatoires", "Erreur de saisie", JOptionPane.WARNING_MESSAGE);
+ this.ret = false;
+ }
+ }
+
+ public String getCode() {
+ return this.dfCode.getText();
+ }
+
+ public String getLibelle() {
+ return this.dfLibelle.getText();
+ }
+
+ public boolean run() {
+ if (this.dfCode.getText() != null && this.dfCode.getText().length() > 0) {
+ // mise en place d'un compteur pour auto-cliquer
+ final int delay = 1000;
+ final ActionListener taskPerformer = new ActionListener() {
+ private int sec = 30;
+
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ if (this.sec == 0) {
+ if (evt.getSource() instanceof Timer) {
+ // Timer timer = (Timer)evt.getSource();
+ DlgGetPair.this.timer.stop();
+ DlgGetPair.this.timer = null;
+ }
+ DlgGetPair.this.pbOk.doClick();
+ } else {
+ final String msg = "Ok (" + (this.sec--) + " sec.)";
+ DlgGetPair.this.pbOk.setText(msg);
+ }
+ }
+ };
+ this.timer = new Timer(delay, taskPerformer);
+ this.timer.start();
+ }
+ this.setVisible(true);
+ this.toFront();
+ return this.ret;
+ }
+
+ @Override
+ public void setVisible(final boolean b) {
+ this.dfCode.grabFocus();
+ super.setVisible(b);
+ }
+
+ private void resetTimer() {
+ if (this.timer != null) {
+ this.timer.stop();
+ this.timer = null;
+ }
+ this.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);
+ // }
}
/**
* 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;
+
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 3690757289103865651L;
+ private final 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);
-
+ /**
+ * @throws java.awt.HeadlessException
+ */
+ public DlgSelectFromList(final Set<String> data) throws HeadlessException {
+ super();
+ this.data = data;
+ this.initComponents();
+ }
+
+ /**
+ * @param owner
+ * @throws java.awt.HeadlessException
+ */
+ public DlgSelectFromList(final Frame owner, final Set<String> data) throws HeadlessException {
+ super(owner, true);
+ this.data = data;
+ this.initComponents();
+ }
+
+ /**
+ * @param owner
+ * @param title
+ * @throws java.awt.HeadlessException
+ */
+ public DlgSelectFromList(final Frame owner, final String title, final Set<String> data) throws HeadlessException {
+ super(owner, title, true);
+ this.data = data;
+ this.initComponents();
+ }
+
+ /**
+ * @param owner
+ * @throws java.awt.HeadlessException
+ */
+ public DlgSelectFromList(final Dialog owner, final Set<String> data) throws HeadlessException {
+ super(owner, "Valeurs", true);
+ this.data = data;
+ this.initComponents();
+ }
+
+ /**
+ * @param owner
+ * @param title
+ * @throws java.awt.HeadlessException
+ */
+ public DlgSelectFromList(final Dialog owner, final String title, final Set<String> data) throws HeadlessException {
+ super(owner, title, true);
+ this.data = data;
+ this.initComponents();
+ }
+
+ public void initComponents() {
+ final int sepInfo = 2;
+ final int lineInfo = sepInfo + 2;
+ final int sepData = lineInfo + 2;
+ final int dataLine = sepData + 2;
+ final int buttonLine = dataLine + 2;
+
+ final Vector<String> dataFL = new Vector<String>();
+ dataFL.addAll(this.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));
+ final 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
+ final CellConstraints cc = new CellConstraints();
+ final PanelBuilder pb = new PanelBuilder(fl);
+
+ // JScrollPane scroller;
+ this.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(this.list), cc.xy(3, dataLine, "fill, fill"));
+
+ final JPanel bPane = new JPanel(new FlowLayout(FlowLayout.CENTER));
+ this.pbCancel = new JButton(this.escapeAction);
+ this.pbOk = new JButton("Ok");
+ bPane.add(this.pbOk);
+ bPane.add(this.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.setBackground(this.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);
+ this.pbOk.setDefaultCapable(true);
+ this.pbOk.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ DlgSelectFromList.this.selectedValue = (String) DlgSelectFromList.this.list.getSelectedValue();
+ DlgSelectFromList.this.ret = true;
+ DlgSelectFromList.this.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);
- }
- }
+ this.list.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(final MouseEvent e) {
+ if (e.getClickCount() == 2) {
+ // int index = list.locationToIndex(e.getPoint());
+ DlgSelectFromList.this.selectedValue = (String) DlgSelectFromList.this.list.getSelectedValue();
+ DlgSelectFromList.this.ret = true;
+ DlgSelectFromList.this.setVisible(false);
+ }
+ }
});
-
- setContentPane(pb.getPanel());
-
- getRootPane().setDefaultButton(pbOk);
- pack();
- setLocationRelativeTo(getParent());
-
- }
+
+ this.setContentPane(pb.getPanel());
+
+ this.getRootPane().setDefaultButton(this.pbOk);
+ this.pack();
+ this.setLocationRelativeTo(this.getParent());
+
+ }
+
public boolean run() {
- setVisible(true);
- return ret;
+ this.setVisible(true);
+ return this.ret;
+ }
+
+ public String getSelectedValue() {
+ return this.selectedValue;
}
- 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);
- }
+ final KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
+ final JRootPane rp = new JRootPane();
+ this.escapeAction = new AbstractAction("Annuler") {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ DlgSelectFromList.this.ret = false;
+ DlgSelectFromList.this.setVisible(false);
+ }
};
- rp.registerKeyboardAction(escapeAction,"TOTOTOTO",ks,JComponent.WHEN_IN_FOCUSED_WINDOW);
- return rp;
+ rp.registerKeyboardAction(this.escapeAction, "TOTOTOTO", ks, JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
}
}
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintJobAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
+import javax.print.attribute.ResolutionSyntax;
import javax.print.attribute.standard.Chromaticity;
import javax.print.attribute.standard.ColorSupported;
import javax.print.attribute.standard.MediaPrintableArea;
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.
+ * 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 int DEFAULT_DPI = 72;
- public static float DEFAULT_PAGE_WIDTH_INCH = 8.5f;
+ public static float DEFAULT_PAGE_WIDTH_INCH = 8.5f;
- public static float DEFAULT_PAGE_HEIGHT_INCH = 11f;
+ public static float DEFAULT_PAGE_HEIGHT_INCH = 11f;
- int x = 100;
+ int x = 100;
- int y = 80;
+ int y = 80;
- GraphicsConfiguration gc;
+ GraphicsConfiguration gc;
- PrintService[] services;
+ PrintService[] services;
- PrintService defaultService;
+ PrintService defaultService;
- DocFlavor flavor;
+ DocFlavor flavor;
- PrintRequestAttributeSet attributes;
+ PrintRequestAttributeSet attributes;
- Vector<PrintJobListener> pjlListeners = new Vector<PrintJobListener>();
+ Vector<PrintJobListener> pjlListeners = new Vector<PrintJobListener>();
- Vector<PrintServiceAttributeListener> pjalListeners = new Vector<PrintServiceAttributeListener>();
+ Vector<PrintServiceAttributeListener> pjalListeners = new Vector<PrintServiceAttributeListener>();
- Vector<PrintServiceAttributeListener> psalListeners = 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 ); } }
- */
+ public HtmlPrinter() {
+ this.gc = null;
+ this.attributes = new HashPrintRequestAttributeSet();
+ this.flavor = null;
+ this.defaultService = PrintServiceLookup.lookupDefaultPrintService();
+ this.services = PrintServiceLookup.lookupPrintServices(this.flavor, this.attributes);
+
+ // do something with the supported docflavors
+ final DocFlavor[] df = this.defaultService.getSupportedDocFlavors();
+ for (final DocFlavor element : df) {
+ // if there is a default service, but no other services
+ if (this.defaultService != null && (this.services == null || this.services.length == 0)) {
+ this.services = new PrintService[1];
+ this.services[0] = this.defaultService;
+ }
+ }
+ }
+
+ /**
+ * Set the GraphicsConfiguration to display the print dialog on.
+ *
+ * @param gc
+ * a GraphicsConfiguration object
+ */
+ public void setGraphicsConfiguration(final GraphicsConfiguration gc) {
+ this.gc = gc;
+ }
+
+ public void setServices(final PrintService[] services) {
+ this.services = services;
+ }
+
+ public void setDefaultService(final PrintService service) {
+ this.defaultService = service;
+ }
+
+ public void setDocFlavor(final DocFlavor flavor) {
+ this.flavor = flavor;
+ }
+
+ public void setPrintRequestAttributes(final PrintRequestAttributeSet attributes) {
+ this.attributes = attributes;
+ }
+
+ public void setPrintDialogLocation(final int x, final int y) {
+ this.x = x;
+ this.y = y;
+ }
+
+ public void addPrintJobListener(final PrintJobListener pjl) {
+ this.pjlListeners.addElement(pjl);
+ }
+
+ public void removePrintJobListener(final PrintJobListener pjl) {
+ this.pjlListeners.removeElement(pjl);
+ }
+
+ public void addPrintServiceAttributeListener(final PrintServiceAttributeListener psal) {
+ this.psalListeners.addElement(psal);
+ }
+
+ public void removePrintServiceAttributeListener(final PrintServiceAttributeListener psal) {
+ this.psalListeners.removeElement(psal);
+ }
+
+ public boolean printJEditorPane(final JEditorPane jep, final PrintService ps) {
+ if (ps == null || jep == null) {
+ return false;
+ }
+
+ // get the root view of the preview pane
+ final 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);
+ final int y = (int) rv.getPreferredSpan(View.Y_AXIS);
+
+ // find out if the print has been set to colour mode
+ final DocPrintJob dpj = ps.createPrintJob();
+ final 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
+
+ final PrinterResolution pr = (PrinterResolution) pjas.get(PrinterResolution.class);
+
+ int dpi;
+ float pageX, pageY;
+ if (pr != null) {
+ dpi = pr.getFeedResolution(ResolutionSyntax.DPI);
+ } else {
+ dpi = DEFAULT_DPI;
+ }
+ final 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;
+ }
+ final int pixelsPerPageY = (int) (dpi * pageY);
+
+ // mod: Add 'pixelsPerPageX' and 'minY'; used in place of 'x' and 'y',
+ // respectively, in the remainder of the method
+ final int pixelsPerPageX = (int) (dpi * pageX); // mod: needed to correctly
+ // scale images with lines
+ // pre-wrapped longer than
+ // page width
+ final 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;
+ }
+ final BufferedImage img = new BufferedImage(pixelsPerPageX, minY, imgMode);
+ final 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
+ final Iterator writers = ImageIO.getImageWritersByFormatName("jpeg");
+ final ImageWriter writer = (ImageWriter) writers.next();
+ final ByteArrayOutputStream out = new ByteArrayOutputStream();
+ final 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
+ final int numberOfPages = (int) Math.ceil(minY / (double) pixelsPerPageY);
+
+ // print each page
+ for (int i = 0; i < numberOfPages; i++) {
+ final int startY = i * pixelsPerPageY;
+
+ // get a subimage which is exactly the size of one page
+ final BufferedImage subImg = img.getSubimage(0, startY, pixelsPerPageX, Math.min(y - startY, pixelsPerPageY)); // mod:
+ // changed
+ // to
+ // correctly
+ // calculate
+ // the
+ // 'subImg'
+ // crop
+ writer.write(subImg);
+
+ final SimpleDoc sd = new SimpleDoc(out.toByteArray(), DocFlavor.BYTE_ARRAY.JPEG, null);
+ this.printDocument(sd, ps);
+
+ // reset the ByteArray so we can start the next page
+ out.reset();
+ }
+ } catch (final PrintException e) {
+ e.printStackTrace();
+ return false;
+ } catch (final 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(final Doc doc, final PrintService ps) throws PrintException {
+ if (ps == null) {
+ return false;
+ }
+
+ this.addAllPrintServiceAttributeListeners(ps);
+
+ final DocPrintJob dpj = ps.createPrintJob();
+ this.addAllPrintJobListeners(dpj);
+
+ dpj.print(doc, this.attributes);
+ return true;
+ }
+
+ public PrintService showPrintDialog() {
+ return ServiceUI.printDialog(this.gc, this.x, this.y, this.services, this.defaultService, this.flavor, this.attributes);
+ }
+
+ private void addAllPrintServiceAttributeListeners(final PrintService ps) {
+ // add all listeners that are currently added to this object
+ for (int i = 0; i < this.psalListeners.size(); i++) {
+ final PrintServiceAttributeListener p = this.psalListeners.get(i);
+ ps.addPrintServiceAttributeListener(p);
+ }
+ }
+
+ private void addAllPrintJobListeners(final DocPrintJob dpj) {
+ // add all listeners that are currently added to this object
+ for (int i = 0; i < this.pjlListeners.size(); i++) {
+ final PrintJobListener p = this.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 ); } }
+ */
}
* @author chm
*/
public class IhmFactory {
- private Hashtable<String,Font> fonts=null;
- private Hashtable<String,Color> colors=null;
+ 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>();
+ this.fonts = new Hashtable<String, Font>();
+ this.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>
+ *
+ * @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) {
+ public JLabel newLabel(final String text, final String txtClass) {
String fontSpec = null;
String fontColor = null;
String backColor = null;
- if(txtClass!=null) {
- StringTokenizer st = new StringTokenizer(txtClass,":");
+ if (txtClass != null) {
+ final StringTokenizer st = new StringTokenizer(txtClass, ":");
fontSpec = st.nextToken();
- if(st.hasMoreTokens()) fontColor=st.nextToken();
- if(st.hasMoreTokens()) backColor=st.nextToken();
+ if (st.hasMoreTokens()) {
+ fontColor = st.nextToken();
+ }
+ if (st.hasMoreTokens()) {
+ backColor = st.nextToken();
+ }
+ }
+ final String fontName = "dialog-" + (fontSpec != null ? fontSpec.toLowerCase() : "");
+ final JLabel ret = new JLabel(text);
+ if (txtClass == null) {
+ return ret;
}
- String fontName = "dialog-"+(fontSpec!=null?fontSpec.toLowerCase():"");
- JLabel ret = new JLabel(text);
- if(txtClass==null) return ret;
- Font font = getFont(ret.getFont(),fontName);
+ final Font font = this.getFont(ret.getFont(), fontName);
ret.setFont(font);
- if(fontColor!=null) {
- Color col = decodeColor(fontColor);
- if(col!=null) ret.setForeground(col);
+ if (fontColor != null) {
+ final Color col = this.decodeColor(fontColor);
+ if (col != null) {
+ ret.setForeground(col);
+ }
}
- if(backColor!=null) {
- Color col = decodeColor(backColor);
- if(col!=null) ret.setBackground(col);
+ if (backColor != null) {
+ final Color col = this.decodeColor(backColor);
+ if (col != null) {
+ ret.setBackground(col);
+ }
}
return ret;
}
- public JLabel newLabel(String text) { return newLabel(text,null); }
-
-
+
+ public JLabel newLabel(final String text) {
+ return this.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>
+ *
+ * @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) {
+ protected Font getFont(final Font font, final String c) {
+ Font ret = this.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);
+ 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);
+ }
+ this.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);
+
+ public Color decodeColor(final String col) {
+ final String c = col.toLowerCase();
+ Color ret = this.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) {
+ final String s = col.toUpperCase();
+ final int r = Integer.parseInt(s.substring(1, 2));
+ final int g = Integer.parseInt(s.substring(3, 4));
+ final int b = Integer.parseInt(s.substring(5, 6));
+ ret = new Color(r, g, b);
}
}
- if(ret!=null) colors.put(col,ret);
+ if (ret != null) {
+ this.colors.put(col, ret);
+ }
}
return ret;
}
- public JButton newButton(String text) {
- JButton ret = new JButton(text);
- addInfoMgr(ret);
+
+ public JButton newButton(final String text) {
+ final JButton ret = new JButton(text);
+ this.addInfoMgr(ret);
return ret;
}
- public JButton newButton(Icon icon) {
- JButton ret = new JButton(icon);
- addInfoMgr(ret);
+
+ public JButton newButton(final Icon icon) {
+ final JButton ret = new JButton(icon);
+ this.addInfoMgr(ret);
return ret;
}
- public JButton newButton(String text, Icon icon) {
- JButton ret = new JButton(text,icon);
- addInfoMgr(ret);
+
+ public JButton newButton(final String text, final Icon icon) {
+ final JButton ret = new JButton(text, icon);
+ this.addInfoMgr(ret);
return ret;
}
- public JButton newButton(Action action) {
- JButton ret = new JButton(action);
- addInfoMgr(ret);
+
+ public JButton newButton(final Action action) {
+ final JButton ret = new JButton(action);
+ this.addInfoMgr(ret);
return ret;
}
- protected void addInfoMgr(JButton button) {
+
+ protected void addInfoMgr(final 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);
+ public void mouseEntered(final 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 void mouseExited(final MouseEvent e) {
+ ((JButton) e.getSource()).setBorderPainted(false);
+ ((JButton) e.getSource()).setOpaque(false);
}
});
}
- public static ImageIcon getIconFromResource(String resName) {
+
+ public static ImageIcon getIconFromResource(final String resName) {
return getIconFromResource(resName, IhmFactory.class.getClassLoader());
}
- public static ImageIcon getIconFromResource(String resName, ClassLoader classLoader) {
- Iterator it = ImageIO.getImageReadersBySuffix(StringUtilities.getFileNameSuffix(resName));
- if(it.hasNext()) {
- ImageReader ir = (ImageReader)it.next();
- InputStream is = classLoader.getResourceAsStream(resName);
+
+ public static ImageIcon getIconFromResource(final String resName, final ClassLoader classLoader) {
+ final Iterator it = ImageIO.getImageReadersBySuffix(StringUtilities.getFileNameSuffix(resName));
+ if (it.hasNext()) {
+ final ImageReader ir = (ImageReader) it.next();
+ final InputStream is = classLoader.getResourceAsStream(resName);
try {
- MemoryCacheImageInputStream fiis = new MemoryCacheImageInputStream(is);
+ final MemoryCacheImageInputStream fiis = new MemoryCacheImageInputStream(is);
ir.setInput(fiis);
- BufferedImage bi = ir.read(0);
+ final BufferedImage bi = ir.read(0);
fiis.close();
- ImageIcon icon = new ImageIcon(bi);
+ final ImageIcon icon = new ImageIcon(bi);
return icon;
- } catch(IOException ioEx) {
+ } catch (final IOException ioEx) {
return null;
}
}
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 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 ;-))
+ * 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;
+ /**
+ * 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 final Icon[] waiters = new Icon[12];
+ private Timer timer;
+ private ProgressPainter currentPainter;
+ private Icon transparent;
+
+ public JWaiter() {
+ super();
+ this.initIcons();
+ this.setPreferredSize(new Dimension(20, 20));
+ this.setIcon(this.transparent);
+ }
+
+ // @Override
+ // public void setVisible(boolean aFlag) {
+ // super.setVisible(aFlag);
+ // if(aFlag) {
+ // startProgress();
+ // } else {
+ // stopProgress();
+ // }
+ // }
+
+ public void startProgress() {
+ if (this.timer == null) {
+ this.timer = new Timer();
+ }
+ if (this.currentPainter != null) {
+ return;
+ }
+ this.currentPainter = new ProgressPainter();
+ this.timer.schedule(this.currentPainter, 0, 50);
+ }
+
+ public void stopProgress() {
+ if (this.currentPainter == null) {
+ return;
+ }
+ this.currentPainter.cancel();
+ this.currentPainter = null;
+ this.setIcon(this.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();
-// }
-// }
+ private void initIcons() {
+ final String[] names = { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12" };
+ for (int i = 0; i < 12; i++) {
+ final String name = names[i];
+ final String resName = "fr/gouv/finances/cp/xemelios/updater/ui/res/wait-" + name + ".png";
+ final ImageIcon ii = IhmFactory.getIconFromResource(resName);
+ this.waiters[i] = ii;
+ }
+ this.transparent = IhmFactory.getIconFromResource("fr/gouv/finances/cp/xemelios/ui/resources/blank.png");
+ }
- 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 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 final long startTime;
+ private int lastIndex;
- public ProgressPainter() {
- super();
- startTime = System.currentTimeMillis();
- }
+ public ProgressPainter() {
+ super();
+ this.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;
- }
- }
- }
+ @Override
+ public void run() {
+ final long delay = (System.currentTimeMillis() - this.startTime) / 100;
+ final int pos = (int) (delay % 12);
+ if (pos != this.lastIndex) {
+ try {
+ SwingUtilities.invokeAndWait(new Runnable() {
+ @Override
+ public void run() {
+ JWaiter.this.setIcon(JWaiter.this.waiters[pos]);
+ }
+ });
+ } catch (final Exception ex) {
+ }
+ this.lastIndex = pos;
+ }
+ }
+ }
}
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; }
- }
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+ // public static void main(String[] args) {}
+ private Runner currentRunner = null;
+
+ public RamViewer() {
+ super();
+ this.initComponents();
+ }
+
+ protected void initComponents() {
+ this.setPreferredSize(new Dimension(100, 20));
+ this.currentRunner = new Runner(this);
+ this.currentRunner.start();
+ }
+
+ @Override
+ public void paint(final Graphics g) {
+ if (!this.isVisible()) {
+ return;
+ }
+ final int width = this.getSize().width;
+ final int height = this.getSize().height;
+ // Image offscreenImg = createImage(width,height);
+ final Graphics offG = g;
+ if (g == null) {
+ return;
+ }
+ final long freeRam = Runtime.getRuntime().freeMemory();
+ final long totalRam = Runtime.getRuntime().totalMemory();
+ // long maxRam = Runtime.getRuntime().maxMemory();
+
+ final int freeWidth = (int) (width * freeRam / totalRam);
+ final int totalWidth = /* (int)(width * totalRam / maxRam ); */width - freeWidth;
+ offG.setColor(this.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);
+ final Font f = new Font("Arial", Font.BOLD, 12);
+ final FontMetrics fm = this.getFontMetrics(f);
+ offG.setFont(f);
+ final DecimalFormat df = new DecimalFormat("0.0' MB'");
+ final 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(final RamViewer viewer) {
+ super();
+ this.viewer = viewer;
+ }
+
+ @Override
+ public void run() {
+ this.setPriority(Thread.MAX_PRIORITY);
+ while (!this.stop) {
+ this.viewer.paint(this.viewer.getGraphics());
+ try {
+ sleep(1000);
+ } catch (final Throwable t) {
+ }
+ }
+ }
+
+ public void stopIt() {
+ this.stop = true;
+ }
+ }
}
import java.io.ObjectInputStream;
/**
- * Similar to {@link VerticalFlowLayout}, but resize all components to make them the same size.
- * License LGPL
+ * 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 + "]";
- }
+ /**
+ * 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(final 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(final int align, final int hgap, final int vgap) {
+ this.hgap = hgap;
+ this.vgap = vgap;
+ this.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 this.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(final 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 this.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(final 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 this.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(final 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
+ */
+ @Override
+ public void addLayoutComponent(final String name, final 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
+ */
+ @Override
+ public void removeLayoutComponent(final 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
+ */
+ @Override
+ public Dimension preferredLayoutSize(final Container target) {
+ synchronized (target.getTreeLock()) {
+ final Dimension dim = new Dimension(0, 0);
+ final int nmembers = target.getComponentCount();
+ boolean firstVisibleComponent = true;
+
+ for (int i = 0; i < nmembers; i++) {
+ final Component m = target.getComponent(i);
+ if (m.isVisible()) {
+ final Dimension d = m.getPreferredSize();
+ dim.width = Math.max(dim.width, d.width);
+ if (firstVisibleComponent) {
+ firstVisibleComponent = false;
+ } else {
+ dim.height += this.vgap;
+ }
+ dim.height += d.height;
+ }
+ }
+ final Insets insets = target.getInsets();
+ dim.width += insets.left + insets.right + this.hgap * 2;
+ dim.height += insets.top + insets.bottom + this.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
+ */
+ @Override
+ public Dimension minimumLayoutSize(final Container target) {
+ synchronized (target.getTreeLock()) {
+ final Dimension dim = new Dimension(0, 0);
+ final int nmembers = target.getComponentCount();
+
+ for (int i = 0; i < nmembers; i++) {
+ final Component m = target.getComponent(i);
+ if (m.isVisible()) {
+ final Dimension d = m.getMinimumSize();
+ dim.width = Math.max(dim.width, d.width);
+ if (i > 0) {
+ dim.height += this.vgap;
+ }
+ dim.height += d.height;
+ }
+ }
+ final Insets insets = target.getInsets();
+ dim.width += insets.left + insets.right + this.hgap * 2;
+ dim.height += insets.top + insets.bottom + this.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(final Container target, final int x, int y, final int width, final int height, final int columnStart, final int columnEnd, final boolean ltr) {
+ synchronized (target.getTreeLock()) {
+ switch (this.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++) {
+ final 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() + this.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
+ */
+ @Override
+ public void layoutContainer(final Container target) {
+ synchronized (target.getTreeLock()) {
+ this.computeDimensions(target);
+ final Insets insets = target.getInsets();
+ final int maxheight = target.getHeight() - (insets.top + insets.bottom + this.vgap * 2);
+ final int nmembers = target.getComponentCount();
+ int x = insets.left + this.hgap, y = 0;
+ int columnw = 0, start = 0;
+
+ final boolean ltr = target.getComponentOrientation().isLeftToRight();
+
+ for (int i = 0; i < nmembers; i++) {
+ final Component m = target.getComponent(i);
+ if (m.isVisible()) {
+ // Dimension d = m.getPreferredSize();
+ m.setSize(this.maxDimension);
+
+ if ((y == 0) || ((y + this.maxDimension.height) <= maxheight)) {
+ if (y > 0) {
+ y += this.vgap;
+ }
+ y += this.maxDimension.height;
+ columnw = Math.max(columnw, this.maxDimension.width);
+ } else {
+ this.moveComponents(target, x, insets.top + this.vgap, columnw, maxheight - y, start, i, ltr);
+ y = this.maxDimension.height;
+ x += this.hgap + columnw;
+ columnw = this.maxDimension.width;
+ start = i;
+ }
+ }
+ }
+ this.moveComponents(target, x, insets.top + this.vgap, columnw, maxheight - y, start, nmembers, ltr);
+ }
+ }
+
+ private void computeDimensions(final Container target) {
+ this.maxDimension = new Dimension(0, 0);
+ for (int i = 0; i < target.getComponentCount(); i++) {
+ final Component m = target.getComponent(i);
+ if (m.isVisible()) {
+ final Dimension d = m.getPreferredSize();
+ this.maxDimension.setSize(Math.max(this.maxDimension.getWidth(), d.getWidth()), Math.max(this.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(final ObjectInputStream stream) throws IOException, ClassNotFoundException {
+ stream.defaultReadObject();
+
+ if (this.serialVersionOnStream < 1) {
+ // "newAlign" field wasn't present, so use the old "align" field.
+ this.setAlignment(this.align);
+ }
+ this.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 (this.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 this.getClass().getName() + "[hgap=" + this.hgap + ",vgap=" + this.vgap + str + "]";
+ }
}
public class UiUtils {
public static void invokeInEDT(final Thread runner, final boolean waitForComplete) {
- if(SwingUtilities.isEventDispatchThread()) {
+ if (SwingUtilities.isEventDispatchThread()) {
runner.run();
- if(waitForComplete) {
+ if (waitForComplete) {
try {
runner.join();
- } catch(Throwable t) {}
+ } catch (final Throwable t) {
+ }
}
- }
- else {
- if(waitForComplete) {
+ } else {
+ if (waitForComplete) {
try {
SwingUtilities.invokeAndWait(runner);
- } catch(Throwable t) {}
+ } catch (final Throwable t) {
+ }
} else {
SwingUtilities.invokeLater(runner);
}
import java.io.ObjectInputStream;
/**
- * Similar to <tt>FlowLayout</tt>, but arranges items vertically
- * License : LGPL
+ * 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 + "]";
- }
+ /**
+ * 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(final 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(final int align, final int hgap, final int vgap) {
+ this.hgap = hgap;
+ this.vgap = vgap;
+ this.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 this.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(final 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 this.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(final 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 this.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(final 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
+ */
+ @Override
+ public void addLayoutComponent(final String name, final 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
+ */
+ @Override
+ public void removeLayoutComponent(final 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
+ */
+ @Override
+ public Dimension preferredLayoutSize(final Container target) {
+ synchronized (target.getTreeLock()) {
+ final Dimension dim = new Dimension(0, 0);
+ final int nmembers = target.getComponentCount();
+ boolean firstVisibleComponent = true;
+
+ for (int i = 0; i < nmembers; i++) {
+ final Component m = target.getComponent(i);
+ if (m.isVisible()) {
+ final Dimension d = m.getPreferredSize();
+ dim.width = Math.max(dim.width, d.width);
+ if (firstVisibleComponent) {
+ firstVisibleComponent = false;
+ } else {
+ dim.height += this.vgap;
+ }
+ dim.height += d.height;
+ }
+ }
+ final Insets insets = target.getInsets();
+ dim.width += insets.left + insets.right + this.hgap * 2;
+ dim.height += insets.top + insets.bottom + this.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
+ */
+ @Override
+ public Dimension minimumLayoutSize(final Container target) {
+ synchronized (target.getTreeLock()) {
+ final Dimension dim = new Dimension(0, 0);
+ final int nmembers = target.getComponentCount();
+
+ for (int i = 0; i < nmembers; i++) {
+ final Component m = target.getComponent(i);
+ if (m.isVisible()) {
+ final Dimension d = m.getMinimumSize();
+ dim.width = Math.max(dim.width, d.width);
+ if (i > 0) {
+ dim.height += this.vgap;
+ }
+ dim.height += d.height;
+ }
+ }
+ final Insets insets = target.getInsets();
+ dim.width += insets.left + insets.right + this.hgap * 2;
+ dim.height += insets.top + insets.bottom + this.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(final Container target, final int x, int y, final int width, final int height, final int columnStart, final int columnEnd, final boolean ltr) {
+ synchronized (target.getTreeLock()) {
+ switch (this.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++) {
+ final 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() + this.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
+ */
+ @Override
+ public void layoutContainer(final Container target) {
+ synchronized (target.getTreeLock()) {
+ final Insets insets = target.getInsets();
+ final int maxheight = target.getHeight() - (insets.top + insets.bottom + this.vgap * 2);
+ final int nmembers = target.getComponentCount();
+ int x = insets.left + this.hgap, y = 0;
+ int columnw = 0, start = 0;
+
+ final boolean ltr = target.getComponentOrientation().isLeftToRight();
+
+ for (int i = 0; i < nmembers; i++) {
+ final Component m = target.getComponent(i);
+ if (m.isVisible()) {
+ final Dimension d = m.getPreferredSize();
+ m.setSize(d.width, d.height);
+
+ if ((y == 0) || ((y + d.height) <= maxheight)) {
+ if (y > 0) {
+ y += this.vgap;
+ }
+ y += d.height;
+ columnw = Math.max(columnw, d.width);
+ } else {
+ this.moveComponents(target, x, insets.top + this.vgap, columnw, maxheight - y, start, i, ltr);
+ y = d.height;
+ x += this.hgap + columnw;
+ columnw = d.width;
+ start = i;
+ }
+ }
+ }
+ this.moveComponents(target, x, insets.top + this.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(final ObjectInputStream stream) throws IOException, ClassNotFoundException {
+ stream.defaultReadObject();
+
+ if (this.serialVersionOnStream < 1) {
+ // "newAlign" field wasn't present, so use the old "align" field.
+ this.setAlignment(this.align);
+ }
+ this.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 (this.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 this.getClass().getName() + "[hgap=" + this.hgap + ",vgap=" + this.vgap + str + "]";
+ }
}
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.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JWindow;
+import javax.swing.RepaintManager;
+import javax.swing.SwingConstants;
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
import fr.gouv.finances.cp.utils.ui.IhmFactory;
import fr.gouv.finances.cp.utils.ui.UiUtils;
+import fr.gouv.finances.cp.xemelios.debug.CheckThreadViolationRepaintManager;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
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.DISPLAY_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();
- }
- }
- }
+ /**
+ * 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 final PropertiesExpansion applicationProperties;
+
+ static {
+ if ("true".equals(System.getProperty(Constants.SYS_PROP_DEBUG_UI))) {
+ RepaintManager.setCurrentManager(new CheckThreadViolationRepaintManager());
+ }
+ }
+
+ public Splash(final PropertiesExpansion applicationProperties, final String[] args) {
+ super();
+ this.applicationProperties = applicationProperties;
+ instance = this;
+ final Displayer displayer = new Displayer(this);
+ UiUtils.invokeInEDT(displayer, true);
+ final Starter starter = new Starter(applicationProperties, args, this);
+ starter.run();
+
+ }
+
+ protected void initialize() {
+ JFrame.setDefaultLookAndFeelDecorated(true);
+ // IhmFactory iF = IhmFactory.newInstance();
+ final ImageIcon ii = IhmFactory.getIconFromResource(ImageResources.SPLASH);
+ final JPanel pane = new JPanel(new BorderLayout());
+ pane.add(new JLabel(ii), BorderLayout.CENTER);
+ pane.add(this.progress = new JProgressBar(SwingConstants.HORIZONTAL, 0, MAX_PROGRESS), BorderLayout.SOUTH);
+ this.getContentPane().add(pane);
+ this.pack();
+ final Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
+ this.setLocation((int) (screen.getWidth() - this.getWidth()) / 2, (int) (screen.getHeight() - this.getHeight()) / 2);
+ this.addFocusListener(new java.awt.event.FocusListener() {
+ @Override
+ public void focusGained(final java.awt.event.FocusEvent e) {
+ Splash.this.toFront();
+ }
+
+ @Override
+ public void focusLost(final java.awt.event.FocusEvent e) {
+ Splash.this.toFront();
+ }
+ });
+ }
+
+ @Override
+ public void pushProgress() {
+ final Thread runner = new Thread() {
+ @Override
+ public void run() {
+ int p = Splash.this.requiredProgress;
+ p++;
+ if (p < MAX_PROGRESS) {
+ Splash.this.progress.setValue(p);
+
+ } else if (p == MAX_PROGRESS) {
+ Splash.this.progress.setValue(MAX_PROGRESS);
+ }
+ Splash.this.requiredProgress = p;
+ }
+ };
+ UiUtils.invokeInEDT(runner, true);
+ }
+
+ @Override
+ public void completeProgress() {
+ final Thread runner = new Thread() {
+ @Override
+ public void run() {
+ Splash.this.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(final 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(final 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) {
+ final PropertiesExpansion pe = new PropertiesExpansion();
+ for (final String key : System.getProperties().stringPropertyNames()) {
+ pe.setProperty(key, System.getProperty(key));
+ }
+ final Splash splash = new Splash(pe, args);
+ }
+
+ private static final class Displayer extends Thread {
+ private Splash splash = null;
+
+ public Displayer(final Splash splash) {
+ this.splash = splash;
+ }
+
+ @Override
+ public void run() {
+ this.splash.initialize();
+ this.splash.setVisible(true);
+ }
+
+ public Splash getSplash() {
+ return this.splash;
+ }
+ }
+
+ private final class Starter implements Runnable {
+ Splash sl;
+ String[] args = null;
+
+ public Starter(final PropertiesExpansion applicationProperties, final String[] args, final Splash sl) {
+ super();
+ this.args = args;
+ this.sl = sl;
+ }
+
+ @Override
+ public void run() {
+ try {
+ Thread.sleep(100);
+ } catch (final Throwable t) {
+ }
+ if (this.sl != null) {
+ this.sl.pushProgress();
+ }
+ final Thread runner = new Thread() {
+ @Override
+ public void run() {
+ try {
+ new MainWindow(Splash.this.applicationProperties, Constants.DISPLAY_NOM_APP, Starter.this.sl, Starter.this.args);
+ } catch (final Throwable t) {
+ t.printStackTrace();
+ }
+ }
+ };
+ UiUtils.invokeInEDT(runner, true);
+ try {
+ Thread.sleep(1000);
+ } catch (final Throwable t) {
+ }
+ if (this.sl != null) {
+ this.sl.setVisible(false);
+ this.sl.dispose();
+ }
+ }
+ }
}
/**
* 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;
- }
+ 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 final Properties props;
+ private final boolean showLogin;
+ private final boolean showPassword;
+
+ public LoginDialog(final JFrame owner, final boolean showLogin, final boolean showPassword) {
+ super(owner, DLG_TITLE, true);
+ this.showLogin = showLogin;
+ this.showPassword = showPassword;
+ final File f = new File(System.getProperty("user.home"), "xemelios.properties");
+ this.props = new Properties();
+ if (f.exists()) {
+ try {
+ this.props.load(new FileInputStream(f));
+ } catch (final IOException ioEx) {
+ }
+ }
+ this.initComposants();
+ }
+
+ protected void initComposants() {
+ final int sepInfo = 2;
+ final int lineInfo = sepInfo + 2;
+ final int sepData = lineInfo + 2;
+ final int userLine = sepData + 2;
+ final int pwdLine = userLine + 2;
+ final int buttonLine = pwdLine + 2;
+
+ JTextArea area = null;
+
+ final 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
+ final CellConstraints cc = new CellConstraints();
+ final PanelBuilder pb = new PanelBuilder(fl);
+ final 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));
+ this.loginTextField = new JTextField();
+ if (this.showLogin) {
+ pb.add(iF.newLabel("Utilisateur", "normal"), cc.xy(3, userLine));
+ pb.add(this.loginTextField, cc.xy(5, userLine));
+ }
+ if (this.showPassword) {
+ pb.add(iF.newLabel("Mot de passe", "normal"), cc.xy(3, pwdLine));
+ pb.add(this.passwordField = new JPasswordField(), cc.xy(5, pwdLine));
+ }
+
+ final JPanel bPane = new JPanel(new FlowLayout(FlowLayout.CENTER));
+ this.pbCancel = new JButton(this.escapeAction);
+ this.pbOk = new JButton("Ok");
+ bPane.add(this.pbOk);
+ bPane.add(this.pbCancel);
+
+ pb.add(bPane, cc.xyw(2, buttonLine, 4));
+
+ this.passwordField.setColumns(15);
+ this.add(pb.getPanel());
+
+ area.setEditable(false);
+ area.setLineWrap(true);
+ area.setRows(3);
+ area.setBackground(this.getBackground());
+
+ area.setText("Veuillez vos informations de connexions\r\npour accéder à " + Constants.NOM_APP);
+
+ this.pbOk.setDefaultCapable(true);
+ this.pbOk.addActionListener(new ActionListener() {
+
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ if (LoginDialog.this.showLogin && (LoginDialog.this.loginTextField.getText() == null || LoginDialog.this.loginTextField.getText().length() == 0)) {
+ JOptionPane.showMessageDialog(LoginDialog.this, "L'identifiant est obligatoire", "Erreur", JOptionPane.ERROR_MESSAGE);
+ LoginDialog.this.loginTextField.grabFocus();
+ return;
+ }
+ if (LoginDialog.this.showPassword && LoginDialog.this.passwordField.getPassword().length == 0) {
+ JOptionPane.showMessageDialog(LoginDialog.this, "Le mot de passe est obligatoire", "Erreur", JOptionPane.ERROR_MESSAGE);
+ LoginDialog.this.passwordField.grabFocus();
+ return;
+ }
+ LoginDialog.this.userName = LoginDialog.this.loginTextField.getText();
+ LoginDialog.this.password = new String(LoginDialog.this.passwordField.getPassword());
+ LoginDialog.this.ret = true;
+ LoginDialog.this.props.setProperty("last.login", LoginDialog.this.userName);
+ try {
+ LoginDialog.this.props.store(new FileOutputStream(new File(System.getProperty("user.home"), "xemelios.properties")), "");
+ } catch (final IOException ioEx) {
+ }
+ LoginDialog.this.setVisible(false);
+ }
+ });
+ this.getRootPane().setDefaultButton(this.pbOk);
+ this.pack();
+ this.setLocationRelativeTo(this.getParent());
+ }
+
+ public boolean run() {
+ final String lastLogin = this.props.getProperty("last.login");
+ this.loginTextField.setText(lastLogin);
+ this.passwordField.setText("");
+ if (lastLogin != null && lastLogin.length() > 0) {
+ this.passwordField.grabFocus();
+ } else {
+ this.loginTextField.grabFocus();
+ }
+ this.setVisible(true);
+ return this.ret;
+ }
+
+ public String getPassword() {
+ return this.password;
+ }
+
+ public String getUserName() {
+ return this.userName;
+ }
+
+ @Override
+ protected JRootPane createRootPane() {
+ final KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
+ final JRootPane rp = new JRootPane();
+ this.escapeAction = new AbstractAction("Annuler") {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ LoginDialog.this.ret = false;
+ LoginDialog.this.setVisible(false);
+ }
+ };
+ rp.registerKeyboardAction(this.escapeAction, "TOTOTOTO", ks, JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
+ }
}
*/
package fr.gouv.finances.cp.xemelios.controls;
-
-
/**
* @author jp.tessier
- *
+ *
*/
public interface Assistant {
- public void setDlgContrl(DlgControl dlgContrl);
-
+ public void setDlgContrl(DlgControl dlgContrl);
+
}
*/
package fr.gouv.finances.cp.xemelios.controls;
+import java.util.Hashtable;
+import java.util.TreeSet;
+import java.util.Vector;
+
+import javax.swing.SwingUtilities;
+import javax.xml.namespace.NamespaceContext;
+
+import org.apache.log4j.Logger;
+
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.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.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;
- }
- }
+ private static final Logger logger = Logger.getLogger(DefaultControlContentHandler.class);
+ private final DocumentModel dm;
+ private final MainWindow frame;
+
+ public DefaultControlContentHandler(final DocumentModel dm, final NamespaceContext nsCtx, final DocumentControlModel docCtrlMod, final Hashtable<String, Object> parameters, final MainWindow frame, final String file, final ControlProgressListener cpl) {
+ super(dm.getId(), nsCtx, docCtrlMod, parameters, file, cpl);
+ this.frame = frame;
+ this.dm = dm;
+ }
+
+ @Override
+ public Pair getCollectivite(final String documentModelId, final String fileName) throws ToolException {
+ Pair ret = null;
+ if (ret == null) {
+ final QueryCollectivite qc = new QueryCollectivite(fileName);
+ qc.setDefaultCollectivite(this.collectivite);
+ if (SwingUtilities.isEventDispatchThread()) {
+ qc.run();
+ } else {
+ try {
+ SwingUtilities.invokeAndWait(qc);
+ } catch (final Throwable t) {
+ }
+ }
+ ret = qc.getRet();
+ if (ret == null) {
+ throw new ToolException("Action interrompue", ToolException.ERROR_INTERRUPTED);
+
+ }
+ }
+ return ret;
+ }
+
+ @Override
+ public Pair getBudget(final String documentModelId, final Pair collectivite, final String fileName) throws ToolException, UnauthorizedException {
+ Pair ret = null;
+ if (ret == null) {
+ final TreeSet<Pair> existing = new TreeSet<Pair>();
+ try {
+ existing.addAll(DataLayerManager.getImplementation().getBudgets(this.dm, collectivite, this.frame.getConnectedUser()));
+ } catch (final DataConfigurationException e) {
+ logger.error("in getBudget", e);
+ } catch (final DataAccessException e) {
+ logger.error("in getBudget", e);
+ }
+ final Vector<Pair> budgetsDm = this.dm.getDefaultBudgets();
+ existing.addAll(budgetsDm);
+ if (this.budget != null && (this.budget.libelle == null || this.budget.libelle.length() == 0)) {
+ if (existing.contains(this.budget)) {
+ for (Pair p : existing) {
+ if (p.key.equals(this.budget.key)) {
+ return p;
+ }
+ }
+ }
+ }
+ final QueryBudget qb = new QueryBudget(fileName, existing, collectivite.libelle);
+ if (SwingUtilities.isEventDispatchThread()) {
+ qb.run();
+ } else {
+ try {
+ SwingUtilities.invokeAndWait(qb);
+ } catch (final 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 final String fileName;
+ private Pair defaultCollectivite = null;
+
+ public Pair getDefaultCollectivite() {
+ return this.defaultCollectivite;
+ }
+
+ public void setDefaultCollectivite(final Pair defaultCollectivite) {
+ this.defaultCollectivite = defaultCollectivite;
+ }
+
+ public QueryCollectivite(final String fileName) {
+ super();
+ this.fileName = fileName;
+ }
+
+ @Override
+ public void run() {
+ final DlgGetPair dlg = new DlgGetPair(DefaultControlContentHandler.this.frame, "Sur quelle collectivité porte ce document : " + this.fileName + " ?", null, null, DefaultControlContentHandler.this.collectivite);
+ if (dlg.run()) {
+ this.ret = new Pair(dlg.getCode(), dlg.getLibelle());
+ } else {
+ DefaultControlContentHandler.this.importInterupted = true;
+ // dlgControl.notifyImportInterupted();
+ // dlgControl.setVisible(false);
+ DefaultControlContentHandler.this.getControlProgressListener().notifyImportInterrupted(true);
+ }
+ }
+
+ public Pair getRet() {
+ return this.ret;
+ }
+ }
+
+ protected class QueryBudget implements Runnable {
+
+ private final String fileName;
+ private final TreeSet<Pair> existing;
+ private Pair ret;
+ private String collectivite = null;
+
+ public QueryBudget(final String fileName, final TreeSet<Pair> existing, final String collectivite) {
+ super();
+ this.fileName = fileName;
+ this.existing = existing;
+ this.collectivite = collectivite;
+ }
+
+ @Override
+ public void run() {
+ DlgGetPair dlg = null;
+ dlg = new DlgGetPair(DefaultControlContentHandler.this.frame, "Sur quel budget porte ce document : " + this.fileName + " ?", this.existing, this.collectivite, DefaultControlContentHandler.this.budget);
+
+ if (dlg.run()) {
+ this.ret = new Pair(dlg.getCode(), dlg.getLibelle());
+ } else {
+ if (!DefaultControlContentHandler.this.importInterupted) {
+ // dlgControl.notifyImportInterupted();
+ DefaultControlContentHandler.this.importInterupted = true;
+ DefaultControlContentHandler.this.getControlProgressListener().notifyImportInterrupted(false);
+ }
+ }
+ logger.debug("fin de QueryBudget.run()");
+ }
+
+ public Pair getRet() {
+ logger.debug("QueryBudget.getRet()");
+ return this.ret;
+ }
+ }
}
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
+import java.awt.image.ImageObserver;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import fr.gouv.finances.dgfip.xemelios.swing.InfiniteGlassPane;
/**
- *
- * @author chm
+ *
+ * @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;
- protected MainControlWrapper mc;
- private static String lastInputDirectory;
- private AbstractAction escapeAction;
- private MainControl.Triplet triplet;
- private String versionPubliee = null;
-
- /** Creates new form DlgControl
- * @param parent
- * @param documentModel
- * @param mc
- */
- public DlgControl(java.awt.Frame parent, DocumentModel documentModel, MainControlWrapper mc) {
- super(parent, false);
- 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)).getAbsolutePath();
- }
- this.documentModel = documentModel;
- this.mc = mc;
- try {
- initComponents();
- } catch (Exception e) {
- logger.debug("InitComp",e);
- }
- if(MainWindow.getInstance().getEnvProperties()!=null && MainWindow.getInstance().getEnvProperties().get(Constants.SYS_PROP_MAJ_CONFIG)!=null){
- String typeMaj = MainWindow.getInstance().getEnvProperties().get(Constants.SYS_PROP_MAJ_CONFIG).toString();
- // Recuperation de la version installée du module si en private
- if(typeMaj != null && typeMaj.length() > 0 && Constants.MAJ_PRIVATE.equals(typeMaj)){
- try {
- File f = new File(MainWindow.getInstance().getEnvProperties().get(Constants.SYS_PROP_INSTALLED_FILENAME).toString());
- logger.debug("Composants installés : "+f.getAbsolutePath());
- Builder builder = new Builder();
- Document doc = builder.build(f);
- Nodes versions = doc.query("/xemelios-installed/component[@uri='http://xemelios.org/updatesV5/"+documentModel.getId()+"']/@version");
- logger.debug("Versions.size : "+versions.size());
- if(versions.size()>0){
- versionPubliee = versions.get(0).getValue();
- logger.debug("Version="+versionPubliee);
+ private static final Logger logger = Logger.getLogger(DlgControl.class);
+ private static final long serialVersionUID = -4196631171841258162L;
+ private final DocumentModel documentModel;
+ protected MainControlWrapper mc;
+ private static String lastInputDirectory;
+ private AbstractAction escapeAction;
+ private String versionPubliee = null;
+
+ /**
+ * Creates new form DlgControl
+ *
+ * @param parent
+ * @param documentModel
+ * @param mc
+ */
+ public DlgControl(final java.awt.Frame parent, final DocumentModel documentModel, final MainControlWrapper mc) {
+ super(parent, false);
+ final Properties homeProperties = this.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)).getAbsolutePath();
+ }
+ this.documentModel = documentModel;
+ this.mc = mc;
+ try {
+ this.initComponents();
+ } catch (final Exception e) {
+ logger.debug("InitComp", e);
+ }
+ if (MainWindow.getInstance().getEnvProperties() != null && MainWindow.getInstance().getEnvProperties().get(Constants.SYS_PROP_MAJ_CONFIG) != null) {
+ final String typeMaj = MainWindow.getInstance().getEnvProperties().get(Constants.SYS_PROP_MAJ_CONFIG).toString();
+ // Recuperation de la version installée du module si en private
+ if (typeMaj != null && typeMaj.length() > 0 && Constants.MAJ_PRIVATE.equals(typeMaj)) {
+ try {
+ final File f = new File(MainWindow.getInstance().getEnvProperties().get(Constants.SYS_PROP_INSTALLED_FILENAME).toString());
+ logger.debug("Composants installés : " + f.getAbsolutePath());
+ final Builder builder = new Builder();
+ final Document doc = builder.build(f);
+ final Nodes versions = doc.query("/xemelios-installed/component[@uri='http://xemelios.org/updatesV5/" + documentModel.getId() + "']/@version");
+ logger.debug("Versions.size : " + versions.size());
+ if (versions.size() > 0) {
+ this.versionPubliee = versions.get(0).getValue();
+ logger.debug("Version=" + this.versionPubliee);
}
- } catch (Exception e) {
- logger.debug("Probeleme de récupération de la version du document model",e);
+ } catch (final Exception e) {
+ logger.debug("Probeleme de récupération de la version du document model", e);
}
- }
- }
- if(versionPubliee==null){
- setTitle("Contrôler un flux");
- } else {
- setTitle(new StringBuilder("Contrôler un flux - ").append(documentModel.getTitre()).append(" ").append(versionPubliee).toString());
- }
-
- InfiniteGlassPane glassPane = new InfiniteGlassPane();
- this.setGlassPane(glassPane);
- paneErrors.setVisible(false);
- mc.setDlgControl(this);
- table.packAll();
- setLocationRelativeTo(getParent());
- pbOk.setDefaultCapable(true);
- getRootPane().setDefaultButton(pbOk);
- pack();
- }
-
- @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 = new javax.swing.JLabel();
- javax.swing.JButton pbBrowse = new javax.swing.JButton();
- dfFileToImport = new javax.swing.JTextField();
- javax.swing.JLabel lblParams = new javax.swing.JLabel();
- jScrollPane1 = new javax.swing.JScrollPane();
- table = new JParamTable(createModel());
- pbOk = new javax.swing.JButton();
- pbCancel = new javax.swing.JButton();
- assitantPanel = createAdditionalComponent();
- paneErrors = new javax.swing.JScrollPane();
- paneErrorsHtml = new javax.swing.JEditorPane();
- jSeparator1 = new javax.swing.JSeparator();
-
- setTitle("Contrôler un flux");
-
- lblFileToImport.setText("Fichier à contrôler");
-
- pbBrowse.setText("...");
- pbBrowse.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- browse(evt);
- }
- });
-
- lblParams.setText("Paramètres");
-
- table.setModel(createModel());
- table.setSortable(false);
- jScrollPane1.setViewportView(table);
-
- pbOk.setText("Contrôler");
- 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);
- }
- });
-
- paneErrors.setViewportView(paneErrorsHtml);
-
- 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(assitantPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE))
- .add(layout.createSequentialGroup()
- .add(12, 12, 12)
- .add(lblFileToImport))
- .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
- .addContainerGap()
- .add(pbCancel)
- .add(18, 18, 18)
- .add(pbOk))
- .add(layout.createSequentialGroup()
- .addContainerGap()
- .add(dfFileToImport, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 516, Short.MAX_VALUE)
- .add(18, 18, 18)
- .add(pbBrowse))
- .add(layout.createSequentialGroup()
- .addContainerGap()
- .add(lblParams))
- .add(layout.createSequentialGroup()
- .addContainerGap()
- .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
- .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE)
- .add(paneErrors, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE)))
- .add(layout.createSequentialGroup()
- .addContainerGap()
- .add(jSeparator1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE)))
- .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))
- .add(5, 5, 5)
- .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
- .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
- .add(assitantPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 103, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
- .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
- .add(lblParams)
- .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
- .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE)
- .add(18, 18, 18)
- .add(paneErrors, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 139, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
- .add(18, 18, 18)
- .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
- ValidatorParams validatorpes = doChecks();
- if((validatorpes!=null && validatorpes.isValid()) || validatorpes==null) {
- // TODO : modifier la facon dont on stocke la dernière configuration utilisée
- /*try {
- mc.writeControlConfigFile();
- } catch(IOException ioEx) {
- logger.error("while writting control config file",ioEx);
- }*/
- runControl(validatorpes);
- } else if(validatorpes!=null){
- paneErrors.setVisible(true);
- pack();
- StringBuilder sb = new StringBuilder("<html><head><style>body { font-size: 10px;font-family: arial;}</style></head><body>");
-
- Hashtable<String,ArrayList<String>> errors = validatorpes.getErrors();
- Enumeration<String> keys = errors.keys();
- while(keys.hasMoreElements()){
- String key = keys.nextElement();
- ArrayList<String> thisErrors = errors.get(key);
- if(thisErrors.size()>0){
+ }
+ }
+ if (this.versionPubliee == null) {
+ this.setTitle("Contrôler un flux");
+ } else {
+ this.setTitle(new StringBuilder("Contrôler un flux - ").append(documentModel.getTitre()).append(" ").append(this.versionPubliee).toString());
+ }
+
+ final InfiniteGlassPane glassPane = new InfiniteGlassPane();
+ this.setGlassPane(glassPane);
+ this.paneErrors.setVisible(false);
+ mc.setDlgControl(this);
+ this.table.packAll();
+ this.setLocationRelativeTo(this.getParent());
+ this.pbOk.setDefaultCapable(true);
+ this.getRootPane().setDefaultButton(this.pbOk);
+ this.pack();
+ }
+
+ @Override
+ protected JRootPane createRootPane() {
+ final KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
+ final JRootPane rp = new JRootPane();
+ this.escapeAction = new AbstractAction("Annuler") {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ DlgControl.this.cancel(evt);
+ }
+ };
+ rp.registerKeyboardAction(this.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() {
+
+ final javax.swing.JLabel lblFileToImport = new javax.swing.JLabel();
+ final javax.swing.JButton pbBrowse = new javax.swing.JButton();
+ this.dfFileToImport = new javax.swing.JTextField();
+ final javax.swing.JLabel lblParams = new javax.swing.JLabel();
+ this.jScrollPane1 = new javax.swing.JScrollPane();
+ this.table = new JParamTable(this.createModel());
+ this.pbOk = new javax.swing.JButton();
+ this.pbCancel = new javax.swing.JButton();
+ this.assitantPanel = this.createAdditionalComponent();
+ this.paneErrors = new javax.swing.JScrollPane();
+ this.paneErrorsHtml = new javax.swing.JEditorPane();
+ this.jSeparator1 = new javax.swing.JSeparator();
+
+ this.setTitle("Contrôler un flux");
+
+ lblFileToImport.setText("Fichier à contrôler");
+
+ pbBrowse.setText("...");
+ pbBrowse.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgControl.this.browse(evt);
+ }
+ });
+
+ lblParams.setText("Paramètres");
+
+ this.table.setModel(this.createModel());
+ this.table.setSortable(false);
+ this.jScrollPane1.setViewportView(this.table);
+
+ this.pbOk.setText("Contrôler");
+ this.pbOk.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgControl.this.doControl(evt);
+ }
+ });
+
+ this.pbCancel.setText("Annuler");
+ this.pbCancel.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgControl.this.cancel(evt);
+ }
+ });
+
+ this.paneErrors.setViewportView(this.paneErrorsHtml);
+
+ final org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this.getContentPane());
+ this.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(this.assitantPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE))
+ .add(layout.createSequentialGroup().add(12, 12, 12).add(lblFileToImport))
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup().addContainerGap().add(this.pbCancel).add(18, 18, 18).add(this.pbOk))
+ .add(layout.createSequentialGroup().addContainerGap().add(this.dfFileToImport, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 516, Short.MAX_VALUE).add(18, 18, 18).add(pbBrowse))
+ .add(layout.createSequentialGroup().addContainerGap().add(lblParams))
+ .add(layout.createSequentialGroup().addContainerGap()
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(this.jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE).add(this.paneErrors, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE)))
+ .add(layout.createSequentialGroup().addContainerGap().add(this.jSeparator1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE))).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(this.dfFileToImport, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE).add(pbBrowse)).add(5, 5, 5)
+ .add(this.jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(this.assitantPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 103, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(lblParams).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(this.jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE).add(18, 18, 18).add(this.paneErrors, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 139, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE).add(18, 18, 18)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE).add(this.pbOk).add(this.pbCancel)).addContainerGap()));
+
+ this.pack();
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void cancel(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_cancel
+ this.setVisible(false);
+ }// GEN-LAST:event_cancel
+
+ private void doControl(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_doControl
+ // TODO: implement
+ final ValidatorParams validatorpes = this.doChecks();
+ if ((validatorpes != null && validatorpes.isValid()) || validatorpes == null) {
+ // TODO : modifier la facon dont on stocke la dernière configuration utilisée
+ /*
+ * try { mc.writeControlConfigFile(); } catch(IOException ioEx) { logger.error("while writting control config file",ioEx); }
+ */
+ this.runControl(validatorpes);
+ } else if (validatorpes != null) {
+ this.paneErrors.setVisible(true);
+ this.pack();
+ final StringBuilder sb = new StringBuilder("<html><head><style>body { font-size: 10px;font-family: arial;}</style></head><body>");
+
+ final Hashtable<String, ArrayList<String>> errors = validatorpes.getErrors();
+ final Enumeration<String> keys = errors.keys();
+ while (keys.hasMoreElements()) {
+ final String key = keys.nextElement();
+ final ArrayList<String> thisErrors = errors.get(key);
+ if (thisErrors.size() > 0) {
sb.append("<b>").append(key).append("</b>").append("<br/>").append("<ul>");
- for(String error:thisErrors){
+ for (final String error : thisErrors) {
sb.append(error);
}
sb.append("</ul>");
}
- }
- sb.append("</body><html>");
- paneErrorsHtml.setContentType("text/html");
- paneErrorsHtml.setText(sb.toString());
- this.repaint();
- }
- }//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.setApproveButtonText("Sélectionner");
- 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 ValidatorParams doChecks() {
- 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) {
- }
- }
- // Recuperation de la sauvegarde du dernier repertoire
- if(lastInputDirectory!=null) {
- if(props.getProperty(Constants.SYS_PROP_LAST_INPUT_DIRECTORY) == null){
- props.setProperty(Constants.SYS_PROP_LAST_INPUT_DIRECTORY,lastInputDirectory);
- } else {
- props.put(Constants.SYS_PROP_LAST_INPUT_DIRECTORY,lastInputDirectory);
- }
- }
- try {
- props.store(new FileOutputStream(propFile), "");
- } catch (Throwable t) {
- }
- if(dfFileToImport.getText()==null || dfFileToImport.getText().length()==0) {
- //JOptionPane.showMessageDialog(this,"Le fichier à importer est obligatoire","Erreur",JOptionPane.ERROR_MESSAGE);
- //dfFileToImport.grabFocus();
- ValidatorParams validator = getValidatorParams();
- if(validator!=null) {
- validator.setValidity(false);
- validator.addError("Fichier", "Le fichier à importer est obligatoire.");
- return validator;
- }
- return null;
- }
-
- TableModel jt = getTableModel();
- Vector<ParamModel> paramsModel = mc.getDocumentControl().getParams();
- ArrayList<Pair> params = new ArrayList<Pair>();
- for(int i=0;i<jt.getRowCount();i++){
- Pair p = new Pair(paramsModel.get(i).getId(),jt.getValueAt(i,1).toString());
- params.add(p);
- }
- paneErrors.setVisible(false);
- pack();
-
- ValidatorParams validator = getValidatorParams();
- if(validator!=null) {
- validator.setParams(params);
- validator.doCheck();
- }
- return validator;
- }
-
- private void runControl(ValidatorParams validator) {
- File fToCtrl = new File(dfFileToImport.getText());
- if(validator==null){
- 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(Exception t) {
- logger.error(t, t);
- }
- }
- 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.JPanel assitantPanel;
- private javax.swing.JTextField dfFileToImport;
- private javax.swing.JScrollPane jScrollPane1;
- private javax.swing.JSeparator jSeparator1;
- private javax.swing.JScrollPane paneErrors;
- private javax.swing.JEditorPane paneErrorsHtml;
- 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(); }
-
- protected JPanel createAdditionalComponent() {
- if(this.mc.getDocumentControl().getAssistant()!=null && this.mc.getDocumentControl().getAssistant().length() > 0){
- try {
- Assistant jp = (Assistant) Class.forName(this.mc.getDocumentControl().getAssistant()).newInstance();
- jp.setDlgContrl(this);
- return (JPanel)jp;
- } catch (Exception e) {
- logger.debug("Problème d'affectation de l'assistant !",e.getCause());
- }
- }
- return new JPanel();
- }
-
- public Vector<ParamModel> getParams(){
- return mc.getDocumentControl().getParams();
- }
-
- public TableModel getTableModel(){
- return table.getModel();
- }
-
- public JTable getTableParams(){
- return table;
- }
-
- private ValidatorParams getValidatorParams(){
- if(this.mc.getDocumentControl().getValideurSaisie()!=null && this.mc.getDocumentControl().getValideurSaisie().length() > 0){
- try {
- ValidatorParams val = (ValidatorParams) Class.forName(this.mc.getDocumentControl().getValideurSaisie()).newInstance();
- return val;
- } catch (Exception e) {
- logger.error("Problème d'affectation du valideur de saisie !",e);
- }
- }
- return null;
- }
-
- 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;
- }
+ }
+ sb.append("</body><html>");
+ this.paneErrorsHtml.setContentType("text/html");
+ this.paneErrorsHtml.setText(sb.toString());
+ this.repaint();
+ }
+ }// GEN-LAST:event_doControl
+
+ private void displayRapport(final MainControl.Triplet infoRapport) {
+ final 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("']");
+ final MainWindow mw = (MainWindow) this.getParent();
+ final 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(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_browse
+ final JFileChooser fc = new JFileChooser();
+ fc.setApproveButtonText("Sélectionner");
+ fc.addChoosableFileFilter(new FileFilter() {
+ @Override
+ public boolean accept(final File f) {
+ return f.isDirectory() || f.getName().toUpperCase().endsWith("XML");
+ }
+
+ @Override
+ public String getDescription() {
+ return "Fichiers XML";
+ }
+ });
+
+ if (this.documentModel.getExtension() != null) {
+ fc.addChoosableFileFilter(new FileFilter() {
+ @Override
+ public boolean accept(final File f) {
+ return f.isDirectory() || f.getName().toUpperCase().endsWith(DlgControl.this.documentModel.getExtension().toUpperCase());
+ }
+
+ @Override
+ public String getDescription() {
+ return DlgControl.this.documentModel.getLibelleExtension();
+ }
+ });
+ }
+
+ if (lastInputDirectory != null) {
+ try {
+ fc.setCurrentDirectory(new File(lastInputDirectory));
+ } catch (final Throwable t) {
+ // on s'affranchit de la suppression du repertoire
+ }
+ }
+ if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
+ this.dfFileToImport.setText(fc.getSelectedFile().getAbsolutePath());
+ lastInputDirectory = fc.getSelectedFile().getParent();
+ }
+
+ }// GEN-LAST:event_browse
+
+ private ValidatorParams doChecks() {
+ final File propFile = new File(System.getProperty("user.home"), "xemelios.properties");
+ final Properties props = new Properties();
+ if (propFile.exists()) {
+ try {
+ props.load(new FileInputStream(propFile));
+ } catch (final IOException ioEx) {
+ }
+ }
+ // Recuperation de la sauvegarde du dernier repertoire
+ if (lastInputDirectory != null) {
+ if (props.getProperty(Constants.SYS_PROP_LAST_INPUT_DIRECTORY) == null) {
+ props.setProperty(Constants.SYS_PROP_LAST_INPUT_DIRECTORY, lastInputDirectory);
+ } else {
+ props.put(Constants.SYS_PROP_LAST_INPUT_DIRECTORY, lastInputDirectory);
+ }
+ }
+ try {
+ props.store(new FileOutputStream(propFile), "");
+ } catch (final Throwable t) {
+ }
+ if (this.dfFileToImport.getText() == null || this.dfFileToImport.getText().length() == 0) {
+ // JOptionPane.showMessageDialog(this,"Le fichier à importer est obligatoire","Erreur",JOptionPane.ERROR_MESSAGE);
+ // dfFileToImport.grabFocus();
+ final ValidatorParams validator = this.getValidatorParams();
+ if (validator != null) {
+ validator.setValidity(false);
+ validator.addError("Fichier", "Le fichier à importer est obligatoire.");
+ return validator;
+ }
+ return null;
+ }
+
+ final TableModel jt = this.getTableModel();
+ final Vector<ParamModel> paramsModel = this.mc.getDocumentControl().getParams();
+ final ArrayList<Pair> params = new ArrayList<Pair>();
+ for (int i = 0; i < jt.getRowCount(); i++) {
+ final Pair p = new Pair(paramsModel.get(i).getId(), jt.getValueAt(i, 1).toString());
+ params.add(p);
+ }
+ this.paneErrors.setVisible(false);
+ this.pack();
+
+ final ValidatorParams validator = this.getValidatorParams();
+ if (validator != null) {
+ validator.setParams(params);
+ validator.doCheck();
+ }
+ return validator;
+ }
+
+ private void runControl(final ValidatorParams validator) {
+ final File fToCtrl = new File(this.dfFileToImport.getText());
+ if (validator == null) {
+ if (!fToCtrl.exists()) {
+ JOptionPane.showMessageDialog(this, "Le fichier indiqué n'existe pas :\n" + this.dfFileToImport.getText(), "Erreur", JOptionPane.ERROR_MESSAGE);
+ return;
+ }
+ }
+ this.mc.setFileToControl(fToCtrl);
+ final Hashtable<String, Object> params = new Hashtable<String, Object>();
+ for (final ParamModel pm : this.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()) {
+ final StringTokenizer tokenizer = new StringTokenizer((String) pm.getValue(), DlgEditParam.SEPARATOR);
+ final int count = tokenizer.countTokens();
+ final 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());
+ }
+ this.mc.setParameters(params);
+ this.getGlassPane().setVisible(true);
+ try {
+ if (SwingUtilities.isEventDispatchThread()) {
+ logger.debug("invoke later");
+ SwingUtilities.invokeLater(this.mc);
+ } else {
+ logger.debug("invoke now");
+ this.mc.run();
+ }
+ } catch (final Exception t) {
+ logger.error(t, t);
+ }
+ }
+
+ public void stopVentilateur() {
+ this.getGlassPane().setVisible(false);
+ }
+
+ public void startVentilateur() {
+ this.getGlassPane().setVisible(true);
+ }
+
+ public void notifyImportFailed() {
+ JOptionPane.showMessageDialog(this, "L'import du rapport a échoué.", "", ImageObserver.ERROR);
+ this.setVisible(false);
+ }
+
+ @Override
+ public void notifyImportInterrupted(final boolean hide) {
+ JOptionPane.showMessageDialog(this, "L'import du rapport a été imterrompu.", "", JOptionPane.CANCEL_OPTION);
+ this.stopVentilateur();
+ if (hide) {
+ this.setVisible(false);
+ }
+ }
+
+ @Override
+ public void notifyTechniqueValidationFailed() {
+ this.setVisible(false);
+ }
+
+ @Override
+ public void notifyImportFinished(final MainControl.Triplet triplet) {
+ if (triplet != null) {
+ this.displayRapport(triplet);
+ }
+ this.setVisible(false);
+ }
+
+ private TableModel createModel() {
+ return new ParamTableModel(null);
+ }
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JPanel assitantPanel;
+ private javax.swing.JTextField dfFileToImport;
+ private javax.swing.JScrollPane jScrollPane1;
+ private javax.swing.JSeparator jSeparator1;
+ private javax.swing.JScrollPane paneErrors;
+ private javax.swing.JEditorPane paneErrorsHtml;
+ 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 final Vector<ParamModel> params;
+
+ public ParamTableModel(final Hashtable<String, Object> existingParams) {
+ super();
+ this.params = DlgControl.this.mc.getDocumentControl().getParams();
+
+ }
+
+ @Override
+ public void removeTableModelListener(final TableModelListener l) {
+ }
+
+ @Override
+ public void addTableModelListener(final TableModelListener l) {
+ }
+
+ @Override
+ public void setValueAt(final Object aValue, final int rowIndex, final int columnIndex) {
+ final ParamModel pm = this.getParam(rowIndex);
+ if (columnIndex == 1) {
+ pm.setValue(aValue, MainWindow.getInstance().getEnvProperties().getProperty(Constants.SYS_PROP_DATE_FORMAT));
+ }
+ }
+
+ @Override
+ public String getColumnName(final int columnIndex) {
+ if (columnIndex == 0) {
+ return "Paramètre";
+ }
+ return "Valeur";
+ }
+
+ @Override
+ public Class<?> getColumnClass(final int columnIndex) {
+ return String.class;
+ }
+
+ @Override
+ public boolean isCellEditable(final int rowIndex, final int columnIndex) {
+ return columnIndex == 1;
+ }
+
+ @Override
+ public Object getValueAt(final int rowIndex, final int columnIndex) {
+ final ParamModel pm = this.params.get(rowIndex);
+ if (columnIndex == 0) {
+ return pm.getName();
+ } else if (columnIndex == 1) {
+ return pm.getValue();
+ }
+ return "";
+ }
+
+ @Override
+ public int getRowCount() {
+ return this.params.size();
+ }
+
+ @Override
+ public int getColumnCount() {
+ return 2;
+ }
+
+ public ParamModel getParam(final int rowIndex) {
+ return this.params.get(rowIndex);
+ }
+ }
+
+ private class JParamTable extends JXTable {
+ private static final long serialVersionUID = -7291976269965161967L;
+ private MyCellRenderer cellRenderer;
+ private MyCellEditor cellEditor2;
+
+ public JParamTable(final TableModel model) {
+ super(model);
+ if (model instanceof ParamTableModel) {
+ this.cellRenderer = new MyCellRenderer((ParamTableModel) model);
+ this.cellEditor2 = new MyCellEditor((ParamTableModel) model);
+ }
+ }
+
+ @Override
+ public TableCellEditor getCellEditor(final int row, final int column) {
+ return this.cellEditor2;
+ }
+
+ @Override
+ public TableCellRenderer getCellRenderer(final int row, final int column) {
+ return this.cellRenderer;
+ }
+
+ @Override
+ public void setModel(final TableModel tableModel) {
+ super.setModel(tableModel);
+ if (tableModel != null && tableModel instanceof ParamTableModel && this.cellRenderer != null) {
+ this.cellRenderer.setModel((ParamTableModel) tableModel);
+ this.cellEditor2.setModel((ParamTableModel) tableModel);
+ }
+ }
+ }
+
+ private class MyCellRenderer extends DefaultTableCellRenderer {
+ private static final long serialVersionUID = 6185107566838768220L;
+ private ParamTableModel ptm;
+
+ public MyCellRenderer(final ParamTableModel ptm) {
+ super();
+ this.ptm = ptm;
+ }
+
+ @Override
+ public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) {
+ Component ret;
+ if (column == 0) {
+ ret = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
+ final JLabel lbl = (JLabel) ret;
+ lbl.setHorizontalAlignment(SwingConstants.LEFT);
+ } else {
+ final ParamModel pm = this.ptm.getParam(row);
+ JLabel lbl;
+ final 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())) {
+ final JCheckBox chk = new JCheckBox();
+ chk.setBackground(c.getBackground());
+ chk.setHorizontalAlignment(SwingConstants.CENTER);
+ if (pm.getValue() != null && pm.getValue() instanceof Boolean) {
+ final 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);
+ final double height = table.getRowHeight();
+ pbEdit.setSize((int) height, (int) height);
+ final JPanel pane = new JPanel();
+ final 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)));
+ final InputMap iMap = pane.getInputMap();
+ final Object actionKey = "helpButton";
+ iMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0), actionKey);
+ final ActionMap am = pane.getActionMap();
+ am.put(actionKey, new AbstractAction() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ pbEdit.doClick();
+ }
+ });
+ ret = pane;
+ }
+ }
+ return ret;
+ }
+
+ public void setModel(final ParamTableModel tpm) {
+ this.ptm = tpm;
+ }
+ }
+
+ private class MyCellEditor extends DefaultCellEditor {
+ private static final long serialVersionUID = 4213567233833281102L;
+ private final DefaultCellEditor chkEditor, cbxEditor, dfEditor;
+ private DefaultCellEditor currentEditor;
+ private JComponent editorComponent2;
+ private ParamTableModel ptm;
+ private PopupMenuListener cbxPopupListener;
+ private FocusListener chkFocusListener;
+
+ public MyCellEditor(final ParamTableModel ptm) {
+ super(new JTextField());
+ this.chkEditor = new DefaultCellEditor(new JCheckBox());
+ this.cbxEditor = new DefaultCellEditor(new JComboBox());
+ this.dfEditor = new DefaultCellEditor(new JTextField());
+ this.setClickCountToStart(1);
+ this.ptm = ptm;
+ }
+
+ @Override
+ public Component getTableCellEditorComponent(final JTable table, final Object value, final boolean isSelected, final int row, final int column) {
+ final ParamModel pm = this.ptm.getParam(row);
+ Component ret;
+ if (pm.getSelect() != null && !pm.getSelect().isMultiValued()) {
+ final JComboBox cbx = (JComboBox) this.cbxEditor.getTableCellEditorComponent(table, value, isSelected, row, column);
+ this.editorComponent2 = cbx;
+ if (this.cbxPopupListener == null) {
+ this.cbxPopupListener = new PopupMenuListener() {
+ @Override
+ public void popupMenuWillBecomeVisible(final PopupMenuEvent e) {
+ }
+
+ @Override
+ public void popupMenuWillBecomeInvisible(final PopupMenuEvent e) {
+ MyCellEditor.this.stopCellEditing();
+ }
+
+ @Override
+ public void popupMenuCanceled(final PopupMenuEvent e) {
+ }
+ };
+ cbx.addPopupMenuListener(this.cbxPopupListener);
+ }
+ cbx.removeAllItems();
+ int selectedItem = -1;
+ for (final 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;
+ this.currentEditor = this.cbxEditor;
+ } else if ("boolean".equals(pm.getDatatype())) {
+ final JCheckBox chk = (JCheckBox) this.chkEditor.getTableCellEditorComponent(table, value, isSelected, row, column);
+ chk.setHorizontalAlignment(SwingConstants.CENTER);
+ chk.setBackground(table.getCellRenderer(row, column).getTableCellRendererComponent(table, value, isSelected, DlgControl.this.hasFocus(), row, column).getBackground());
+ if (this.chkFocusListener == null) {
+ this.chkFocusListener = new FocusListener() {
+ @Override
+ public void focusGained(final FocusEvent e) {
+ }
+
+ @Override
+ public void focusLost(final FocusEvent e) {
+ MyCellEditor.this.stopCellEditing();
+ }
+ };
+ chk.addFocusListener(this.chkFocusListener);
+ }
+ ret = chk;
+ this.currentEditor = this.chkEditor;
+ this.editorComponent2 = chk;
+ } else {
+ final JTextField df = (JTextField) this.dfEditor.getTableCellEditorComponent(table, value, isSelected, row, column);
+ final Keymap km = df.getKeymap();
+ if (km.getAction(KeyStroke.getKeyStroke('\n')) == null) {
+ km.addActionForKeyStroke(KeyStroke.getKeyStroke('\n'), new AbstractAction() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ MyCellEditor.this.stopCellEditing();
+ }
+ });
+ }
+ ret = df;
+ this.currentEditor = this.dfEditor;
+ this.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);
+ }
+ final double height = table.getRowHeight();
+ pbEdit.setSize((int) height, (int) height);
+ final JPanel pane = new JPanel();
+ final 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(final FocusEvent e) {
+ }
+
+ @Override
+ public void focusLost(final FocusEvent e) {
+ MyCellEditor.this.stopCellEditing();
+ }
+ });
+ pane.addFocusListener(new FocusListener() {
+ @Override
+ public void focusGained(final FocusEvent e) {
+ MyCellEditor.this.editorComponent2.grabFocus();
+ }
+
+ @Override
+ public void focusLost(final FocusEvent e) {
+ }
+ });
+ final InputMap iMap = pane.getInputMap();
+ final Object actionKey = "helpButton";
+ iMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0), actionKey);
+ final ActionMap am = pane.getActionMap();
+ am.put(actionKey, new AbstractAction() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ pbEdit.doClick();
+ }
+ });
+ ret = pane;
+ }
+ return ret;
+ }
+
+ public void setModel(final ParamTableModel ptm) {
+ this.ptm = ptm;
+ }
+
+ @Override
+ public Object getCellEditorValue() {
+ return this.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(final ParamModel pm) {
+ super("...");
+ this.pm = pm;
+ this.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ ButtonEditParam.this.doEdit();
+ }
+ });
+ }
+
+ public ButtonEditParam(final ParamModel pm, final JComboBox cbx) {
+ this(pm);
+ this.cbx = cbx;
+ }
+
+ public ButtonEditParam(final ParamModel pm, final JTextField df) {
+ this(pm);
+ this.df = df;
+ }
+
+ private void doEdit() {
+ final DlgEditParam dep = new DlgEditParam(DlgControl.this, this.pm);
+ dep.setVisible(true);
+ if (this.cbx != null) {
+ final Object value = this.cbx.getSelectedItem();
+ this.cbx.removeAllItems();
+ int selectedItem = -1;
+ for (final OptionModel om : this.pm.getSelect().getOptions()) {
+ this.cbx.addItem(new Pair(om.getValue(), om.getLibelle()));
+ if (value != null && om.getValue().equals(value)) {
+ selectedItem = this.cbx.getItemCount() - 1;
+ }
+ }
+ if (selectedItem != -1) {
+ this.cbx.setSelectedIndex(selectedItem);
+ }
+ } else if (this.df != null) {
+ this.df.setText(this.pm.getValue().toString());
+ }
+ }
+ }
+
+ @Override
+ public void stopWaiting() {
+ this.stopVentilateur();
+ }
+
+ protected JPanel createAdditionalComponent() {
+ if (this.mc.getDocumentControl().getAssistant() != null && this.mc.getDocumentControl().getAssistant().length() > 0) {
+ try {
+ final Assistant jp = (Assistant) Class.forName(this.mc.getDocumentControl().getAssistant()).newInstance();
+ jp.setDlgContrl(this);
+ return (JPanel) jp;
+ } catch (final Exception e) {
+ logger.debug("Problème d'affectation de l'assistant !", e.getCause());
+ }
+ }
+ return new JPanel();
+ }
+
+ public Vector<ParamModel> getParams() {
+ return this.mc.getDocumentControl().getParams();
+ }
+
+ public TableModel getTableModel() {
+ return this.table.getModel();
+ }
+
+ public JTable getTableParams() {
+ return this.table;
+ }
+
+ private ValidatorParams getValidatorParams() {
+ if (this.mc.getDocumentControl().getValideurSaisie() != null && this.mc.getDocumentControl().getValideurSaisie().length() > 0) {
+ try {
+ final ValidatorParams val = (ValidatorParams) Class.forName(this.mc.getDocumentControl().getValideurSaisie()).newInstance();
+ return val;
+ } catch (final Exception e) {
+ logger.error("Problème d'affectation du valideur de saisie !", e);
+ }
+ }
+ return null;
+ }
+
+ private Properties getHomeProperties() {
+ final File f = new File(System.getProperty("user.home"), "xemelios.properties");
+ final Properties props = new Properties();
+ if (f.exists()) {
+ try {
+ props.load(new FileInputStream(f));
+ } catch (final IOException ioEx) {
+ }
+ }
+ return props;
+ }
public String getVersionComposent() {
- if(versionPubliee!=null){
- return new StringBuilder(documentModel.getTitre()).append(" ").append(versionPubliee).toString();
- }
- return null;
+ if (this.versionPubliee != null) {
+ return new StringBuilder(this.documentModel.getTitre()).append(" ").append(this.versionPubliee).toString();
+ }
+ return null;
}
}
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 javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
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
+ *
+ * @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();
- pbSelect = new javax.swing.JButton();
- jLabel1 = new javax.swing.JLabel();
-
- 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("Valider");
- 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);
- }
- });
-
- pbSelect.setText("Tout cocher");
- pbSelect.setMargin(new java.awt.Insets(2, 1, 2, 1));
- pbSelect.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- pbSelectActionPerformed(evt);
- }
- });
-
- jLabel1.setFont(new java.awt.Font("Tahoma", 2, 11)); // NOI18N
- jLabel1.setText("Sélection multiple : maintenir CTRL et sélectionner");
-
- 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(jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE)
- .add(jScrollPane1))
- .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
- .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
- .add(pbAdd, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE)
- .add(pbClose, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
- .add(pbRemove, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
- .add(pbSelect, 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(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
- .addContainerGap()
- .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
- .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 254, Short.MAX_VALUE)
- .add(layout.createSequentialGroup()
- .add(pbAdd)
- .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
- .add(pbRemove)
- .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
- .add(pbSelect)
- .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
- .add(pbClose)))
- .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
- .add(jLabel1)
- .add(13, 13, 13))
- );
-
- 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) {}
-
- Vector<String> data = new Vector<String>();
- for(OptionModel om2:pm.getSelect().getOptions()) {
- String key = om2.getValue();
- data.add(key);
- }
-
- Integer lastIndice = new Integer(data.size()-1); //indice de la dernière valeur ajoutée
- int[] indices = lst.getSelectedIndices(); //cases cochées précédemment
- int[] indicesTotal = new int[indices.length+1];
-
- for(int i=0;i<indicesTotal.length;i++) {
- if (i == indicesTotal.length-1){
- indicesTotal[i]=lastIndice.intValue();
- } else {
- indicesTotal[i]=indices[i];
- }
- }
-
- lst.setListData(data);
- lst.setSelectedIndices(indicesTotal);
-
- }//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
-
- private void pbSelectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbSelectActionPerformed
-
- Vector<Integer> selectedIndices = new Vector<Integer>();
- Vector<String> data = new Vector<String>();
- for(OptionModel om:pm.getSelect().getOptions()) {
- String key = om.getValue();
- selectedIndices.add(new Integer(data.size()));
- data.add(key);
- }
-
- //tout sélectionner
- int[] indices = new int[selectedIndices.size()];
- for(int i=0;i<indices.length;i++) indices[i]=selectedIndices.get(i).intValue();
- lst.setSelectedIndices(indices);
-
- }//GEN-LAST:event_pbSelectActionPerformed
-
-
- // Variables declaration - do not modify//GEN-BEGIN:variables
- private javax.swing.JLabel jLabel1;
- 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;
- private javax.swing.JButton pbSelect;
- // 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;
- }
- }
+ public static final String SEPARATOR = " ";
+ private final ParamModel pm;
+
+ /** Creates new form DlgEditParam */
+ public DlgEditParam(final java.awt.Frame parent, final ParamModel pm) {
+ super(parent, true);
+ this.pm = pm;
+ this.initAll();
+ }
+
+ public DlgEditParam(final java.awt.Dialog parent, final ParamModel pm) {
+ super(parent, true);
+ this.pm = pm;
+ this.initAll();
+ }
+
+ private void initAll() {
+ this.initComponents();
+ this.setLocationRelativeTo(this.getParent());
+ if (!this.pm.getSelect().isMultiValued()) {
+ final Vector<Pair> v = new Vector<Pair>();
+ for (final OptionModel om : this.pm.getSelect().getOptions()) {
+ final Pair p = new Pair(om.getValue(), om.getLibelle());
+ v.add(p);
+ }
+ this.lst.setListData(v);
+ this.pbAdd.setEnabled(true);
+ this.lst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
+ this.lst.addListSelectionListener(new ListSelectionListener() {
+ @Override
+ public void valueChanged(final ListSelectionEvent e) {
+ DlgEditParam.this.pbRemove.setEnabled(DlgEditParam.this.lst.getSelectedIndex() >= 0);
+ }
+ });
+ } else {
+ final Object oValue = this.pm.getValue();
+ final HashSet<String> values = new HashSet<String>();
+ if (oValue != null && oValue instanceof String) {
+ final String s = (String) oValue;
+ final StringTokenizer tokenizer = new StringTokenizer(s, SEPARATOR);
+ while (tokenizer.hasMoreTokens()) {
+ values.add(tokenizer.nextToken());
+ }
+ }
+ this.lst.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
+ this.lst.setCellRenderer(new MyCellRenderer());
+ final Vector<String> data = new Vector<String>();
+ final Vector<Integer> selectedIndices = new Vector<Integer>();
+ for (final OptionModel om : this.pm.getSelect().getOptions()) {
+ final String key = om.getValue();
+ if (values.contains(key)) {
+ selectedIndices.add(new Integer(data.size()));
+ }
+ data.add(key);
+ }
+ this.lst.setListData(data);
+ final int[] indices = new int[selectedIndices.size()];
+ for (int i = 0; i < indices.length; i++) {
+ indices[i] = selectedIndices.get(i).intValue();
+ }
+ this.lst.setSelectedIndices(indices);
+ if (this.pm.getSelect().isEditable()) {
+ this.pbAdd.setEnabled(true);
+ this.lst.addListSelectionListener(new ListSelectionListener() {
+ @Override
+ public void valueChanged(final ListSelectionEvent e) {
+ DlgEditParam.this.pbRemove.setEnabled(DlgEditParam.this.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() {
+
+ this.jScrollPane1 = new javax.swing.JScrollPane();
+ this.lst = new javax.swing.JList();
+ this.pbClose = new javax.swing.JButton();
+ this.pbAdd = new javax.swing.JButton();
+ this.pbRemove = new javax.swing.JButton();
+ this.pbSelect = new javax.swing.JButton();
+ this.jLabel1 = new javax.swing.JLabel();
+
+ this.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+ this.setTitle(this.pm.getName());
+
+ this.lst.setModel(new javax.swing.AbstractListModel() {
+ String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
+
+ @Override
+ public int getSize() {
+ return this.strings.length;
+ }
+
+ @Override
+ public Object getElementAt(final int i) {
+ return this.strings[i];
+ }
+ });
+ this.lst.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
+ this.jScrollPane1.setViewportView(this.lst);
+
+ this.pbClose.setText("Valider");
+ this.pbClose.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgEditParam.this.pbCloseActionPerformed(evt);
+ }
+ });
+
+ this.pbAdd.setText("Ajouter");
+ this.pbAdd.setEnabled(false);
+ this.pbAdd.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgEditParam.this.pbAddActionPerformed(evt);
+ }
+ });
+
+ this.pbRemove.setText("Supprimer");
+ this.pbRemove.setEnabled(false);
+ this.pbRemove.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgEditParam.this.pbRemoveActionPerformed(evt);
+ }
+ });
+
+ this.pbSelect.setText("Tout cocher");
+ this.pbSelect.setMargin(new java.awt.Insets(2, 1, 2, 1));
+ this.pbSelect.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgEditParam.this.pbSelectActionPerformed(evt);
+ }
+ });
+
+ this.jLabel1.setFont(new java.awt.Font("Tahoma", 2, 11)); // NOI18N
+ this.jLabel1.setText("Sélection multiple : maintenir CTRL et sélectionner");
+
+ final org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this.getContentPane());
+ this.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(this.jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE).add(this.jScrollPane1))
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(this.pbAdd, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE)
+ .add(this.pbClose, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).add(this.pbRemove, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .add(this.pbSelect, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)).addContainerGap()));
+
+ layout.linkSize(new java.awt.Component[] { this.pbAdd, this.pbClose, this.pbRemove }, org.jdesktop.layout.GroupLayout.HORIZONTAL);
+
+ 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(this.jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 254, Short.MAX_VALUE)
+ .add(layout.createSequentialGroup().add(this.pbAdd).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.pbRemove).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.pbSelect)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).add(this.pbClose))).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.jLabel1).add(13, 13, 13)));
+
+ this.pack();
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void pbAddActionPerformed(final java.awt.event.ActionEvent evt) { // GEN-FIRST:event_pbAddActionPerformed
+ final String s = JOptionPane.showInputDialog(this, "Valeur à ajouter :");
+ final OptionModel om = new OptionModel(s, s);
+ try {
+ this.pm.getSelect().addChild(om, OptionModel.QN);
+ } catch (final Throwable t) {
+ }
+
+ final Vector<String> data = new Vector<String>();
+ for (final OptionModel om2 : this.pm.getSelect().getOptions()) {
+ final String key = om2.getValue();
+ data.add(key);
+ }
+
+ final Integer lastIndice = new Integer(data.size() - 1); // indice de la dernière valeur ajoutée
+ final int[] indices = this.lst.getSelectedIndices(); // cases cochées précédemment
+ final int[] indicesTotal = new int[indices.length + 1];
+
+ for (int i = 0; i < indicesTotal.length; i++) {
+ if (i == indicesTotal.length - 1) {
+ indicesTotal[i] = lastIndice.intValue();
+ } else {
+ indicesTotal[i] = indices[i];
+ }
+ }
+
+ this.lst.setListData(data);
+ this.lst.setSelectedIndices(indicesTotal);
+
+ }// GEN-LAST:event_pbAddActionPerformed
+
+ private void pbRemoveActionPerformed(final java.awt.event.ActionEvent evt) { // GEN-FIRST:event_pbRemoveActionPerformed
+ if (this.pm.getSelect().isEditable()) {
+ if (!this.pm.getSelect().isMultiValued()) {
+ final Pair p = (Pair) this.lst.getSelectedValue();
+ if (p != null) {
+ final int index = this.lst.getSelectedIndex();
+ this.lst.remove(index);
+ this.pm.getSelect().getOptions().remove(index);
+ }
+ } else {
+ final Object[] values = this.lst.getSelectedValues();
+ final Vector<String> v = new Vector<String>();
+ for (final Object value : values) {
+ v.add((String) value);
+ }
+ final Vector<OptionModel> toDrop = new Vector<OptionModel>();
+ for (final OptionModel om : this.pm.getSelect().getOptions()) {
+ if (v.contains(om.getValue())) {
+ toDrop.add(om);
+ }
+ }
+ this.pm.getSelect().getOptions().removeAll(toDrop);
+ this.pm.setValue("", MainWindow.getInstance().getEnvProperties().getProperty(Constants.SYS_PROP_DATE_FORMAT));
+ final Vector<String> data = new Vector<String>();
+ for (final OptionModel om : this.pm.getSelect().getOptions()) {
+ final String key = om.getValue();
+ data.add(key);
+ }
+ this.lst.setListData(data);
+
+ }
+ }
+ }// GEN-LAST:event_pbRemoveActionPerformed
+
+ private void pbCloseActionPerformed(final java.awt.event.ActionEvent evt) { // GEN-FIRST:event_pbCloseActionPerformed
+ if (this.pm.getSelect().isMultiValued()) {
+ final StringBuffer sb = new StringBuffer();
+ final int[] indices = this.lst.getSelectedIndices();
+ for (final int i : indices) {
+ final String s = this.lst.getModel().getElementAt(i).toString();
+ sb.append(s).append(SEPARATOR);
+ }
+ if (sb.length() > 1) {
+ sb.deleteCharAt(sb.length() - 1);
+ }
+ this.pm.setValue(sb.toString(), MainWindow.getInstance().getEnvProperties().getProperty(Constants.SYS_PROP_DATE_FORMAT));
+ }
+ this.setVisible(false);
+ }// GEN-LAST:event_pbCloseActionPerformed
+
+ private void pbSelectActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbSelectActionPerformed
+
+ final Vector<Integer> selectedIndices = new Vector<Integer>();
+ final Vector<String> data = new Vector<String>();
+ for (final OptionModel om : this.pm.getSelect().getOptions()) {
+ final String key = om.getValue();
+ selectedIndices.add(new Integer(data.size()));
+ data.add(key);
+ }
+
+ // tout sélectionner
+ final int[] indices = new int[selectedIndices.size()];
+ for (int i = 0; i < indices.length; i++) {
+ indices[i] = selectedIndices.get(i).intValue();
+ }
+ this.lst.setSelectedIndices(indices);
+
+ }// GEN-LAST:event_pbSelectActionPerformed
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JLabel jLabel1;
+ 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;
+ private javax.swing.JButton pbSelect;
+
+ // End of variables declaration//GEN-END:variables
+
+ private class MyCellRenderer extends JCheckBox implements ListCellRenderer {
+ public MyCellRenderer() {
+ super();
+ this.setBorder(new LineBorder(Color.GRAY, 1));
+ }
+
+ @Override
+ public Component getListCellRendererComponent(final JList list, final Object value, final int index, final boolean isSelected, final boolean cellHasFocus) {
+ if (value != null) {
+ this.setText(value.toString());
+ } else {
+ this.setText("");
+ }
+ this.setSelected(isSelected);
+ this.setBorderPainted(cellHasFocus);
+ if (cellHasFocus) {
+ this.setBackground(list.getSelectionBackground());
+ this.setForeground(list.getSelectionForeground());
+ } else {
+ this.setBackground(list.getBackground());
+ this.setForeground(list.getForeground());
+ }
+ return this;
+ }
+ }
}
import fr.gouv.finances.dgfip.xemelios.importers.EtatImporteur;
/**
- *
+ *
* @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;
- private PropertiesExpansion applicationProperties;
-
- /** Creates a new instance of MainControlWrapper */
- public MainControlWrapper(DocumentModel dm,DocumentsModel docsMod,XemeliosUser user,PropertiesExpansion applicationProperties) {
- super();
- this.user=user;
- this.dm=dm;
- this.applicationProperties = applicationProperties;
- 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");
-
- mc.setVersionProvider(new JarVersionProvider());
- }
-
- 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, PropertiesExpansion.class);
- Object obj = cc.newInstance(user, applicationProperties);
- 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;
- }
+ 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;
+ private PropertiesExpansion applicationProperties;
+
+ /** Creates a new instance of MainControlWrapper */
+ public MainControlWrapper(final DocumentModel dm, final DocumentsModel docsMod, final XemeliosUser user, final PropertiesExpansion applicationProperties) {
+ super();
+ this.user = user;
+ this.dm = dm;
+ this.applicationProperties = applicationProperties;
+ final DocumentModel dm2 = dm;
+ final ControlsModel cm = this.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(final String documentModelId, final DocumentControlModel docCtrlMod, final Hashtable<String, Object> parameters, final String file, final ControlProgressListener cpl) {
+ return new DefaultControlContentHandler(dm2, dm2.getNamespaces(), dcm, parameters, MainWindow.getInstance(), file, this.getControlProgressListener());
+ }
+
+ };
+ if (dm.getTextToXmlTransformer() != null) {
+ this.mc.setTextToXmlTransformer(dm.getTextToXmlTransformer());
+ }
+
+ this.dmRapport = docsMod.getDocumentById("rapport");
+
+ this.mc.setVersionProvider(new JarVersionProvider());
+ }
+
+ private void importer(final DocumentModel dm, final Pair coll, final Pair budg, final File f, final boolean isRapport, final MainControl.Triplet triplet) {
+ try {
+ final Class clazz = Class.forName(dm.getImportClass());
+ final Constructor cc = clazz.getConstructor(XemeliosUser.class, PropertiesExpansion.class);
+ final Object obj = cc.newInstance(this.user, this.applicationProperties);
+ 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;
+ }
+ final EtatImporteur ei = (EtatImporteur) obj;
+ ei.setDocument(dm, coll, budg);
+ ei.setApplicationConfiguration(MainWindow.getInstance().getEnvProperties());
+ final ArrayList<File> array = new ArrayList<File>();
+ array.add(f);
+ final ImportContent fToImport = new ImportContent();
+ fToImport.setFilesToImport(array);
+
+ if (isRapport) {
+ MainWindow.instance.doImport(ei, fToImport, dm, this.dlgControl, triplet, true);
+ } else {
+ MainWindow.instance.doImport(ei, fToImport, dm, true);
+ }
+ } catch (final Exception ex) {
+ ex.printStackTrace();
+ } finally {
+
+ }
+ }
+
+ public void setDlgControl(final DlgControl dlgControl) {
+ this.dlgControl = dlgControl;
+ this.mc.setControlProgressListener(dlgControl);
+ }
+
+ /*
+ * public void writeControlConfigFile() throws IOException { mc.writeControlConfigFile(); }
+ */
+ public DocumentControlModel getDocumentControl() {
+ return this.mc.getDocumentControl();
+ }
+
+ public void setFileToControl(final File fToCtrl) {
+ this.mc.setFileToControl(fToCtrl);
+ }
+
+ public void setParameters(final Hashtable<String, Object> params) {
+ this.mc.setParameters(params);
+ }
+
+ @Override
+ public void run() {
+ this.mc.run();
+ switch (this.mc.getControlStatus()) {
+ case MainControl.STATUS_CONTROL_NO_ERROR: {
+ final int reponse = JOptionPane.showConfirmDialog(MainWindow.instance, "Le fichier " + this.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
+ this.importer(this.dm, this.mc.getCollectivite(), this.mc.getBudget(), this.mc.getFichierEnrichi(), false, null);
+ // Import du rapport si des anos sont présentes
+ this.importer(this.dmRapport, this.mc.getCollectivite(), this.mc.getBudget(), this.mc.getRapport(), true, new Triplet(this.mc.getIdRapport(), this.mc.getCollectivite().key, this.mc.getBudget().key));
+ } else {
+ this.dlgControl.notifyImportFinished(null);
+ }
+ break;
+ }
+ case MainControl.STATUS_HAS_UNIT_CONTROL_ERRORS: {
+ this.importer(this.dm, this.mc.getCollectivite(), this.mc.getBudget(), this.mc.getFichierEnrichi(), false, null);
+ this.importer(this.dmRapport, this.mc.getCollectivite(), this.mc.getBudget(), this.mc.getRapport(), true, new Triplet(this.mc.getIdRapport(), this.mc.getCollectivite().key, this.mc.getBudget().key));
+ break;
+ }
+ case MainControl.STATUS_NOT_SCHEMA_VALID:
+ case MainControl.STATUS_INVALID_ENCODING:
+ case MainControl.STATUS_NOT_XML: {
+ this.importer(this.dmRapport, new Pair("00000000000000", "Collectivite de Contrôle"), new Pair("00", "Budget de Contrôle"), this.mc.getRapport(), true, new Triplet(this.mc.getIdRapport(), "00000000000000", "00"));
+ break;
+ }
+ }
+ }
+
+ private ControlsModel getControlsModel() {
+ ControlsModel ret = null;
+ try {
+ final ControlParser cp = new ControlParser();
+ cp.parse(new File(this.dm.getBaseDirectory(), this.dm.getControlConfigFile()));
+ final ControlsModel c = (ControlsModel) cp.getMarshallable();
+ c.validate();
+ ret = c;
+ } catch (final Exception ex) {
+ logger.debug("Error in getControlsModel()!!!", ex);
+ }
+ return ret;
+ }
}
*/
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.File;
+import java.io.FileInputStream;
import java.io.FileOutputStream;
+import java.math.BigDecimal;
+import java.util.Hashtable;
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 org.w3c.dom.Document;
-
-
-import java.io.File;
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
/**
- *
+ *
* @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();
- }
- }
+ static Controller controller;
+
+ protected static Object controlParameterFromString(final 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
+
+ final String dataType = controller.getParameterDataType(paramId);
+ if (dataType == null) {
+ System.err.println("Unknown parameter :" + paramId);
+ return null;
+ }
+ if ("string".equals(dataType)) {
+ if (paramValue.matches("\\{.*\\}")) {
+
+ final int i1 = paramValue.indexOf("{");
+ final 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(final String propertiesFile) throws Exception {
+ // Read properties file.
+ final Properties properties = new Properties();
+
+ properties.load(new FileInputStream(propertiesFile));
+ final Hashtable<String, Object> ret = new Hashtable<String, Object>();
+ for (final Object obk : properties.keySet()) {
+ final 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(final 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);
+ }
+
+ final String typeDoc = args[0];
+ final String fileToReadPath = args[1];
+ final String dirToGeneratePath = args[2];
+ final String propertiesFilePath = args[3];
+
+ final File fileToRead = new File(fileToReadPath);
+
+ final PropertiesExpansion applicationConfiguration = new PropertiesExpansion(System.getProperties());
+ controller = new Controller(typeDoc, applicationConfiguration);
+ final 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
+ final 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 (final String k : result.keySet()) {
+ final Document doc = result.get(k);
+
+ try {
+ final File fn = new File(dirToGenerate, k + ".xml");
+ final FileOutputStream f = new FileOutputStream(fn);
+
+ final TransformerFactory tf = FactoryProvider.getTransformerFactory();
+ final 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 (final Exception e) {
+ e.printStackTrace();
+ //
+
+ } catch (final Error e) {
+ e.printStackTrace();
+
+ }
+ }
+
+ } catch (final Throwable t) {
+ t.printStackTrace();
+ }
+ }
}
* identifiant du type de document
* @throws Exception
*/
- public Controller(String typeDoc, PropertiesExpansion applicationConfiguration) throws Exception {
- config = Loader.getDocumentsInfos(applicationConfiguration.getProperty(Constants.SYS_PROP_DOC_DEF_DIR));
+ public Controller(final String typeDoc, final PropertiesExpansion applicationConfiguration) throws Exception {
+ this.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, new File(pesConfig.getBaseDirectory(), dcm.getControlTechById("TECH03").getParamTechById("schemaLocation").getValue())) {
+ this.pesConfig = this.config.getDocumentById(typeDoc); // ("PES_Aller");
+ this.rapportConfig = this.config.getDocumentById("DocumentRapport");
+ final DocumentModel dm2 = this.pesConfig;
+ final ControlsModel cm = this.getControlsModel();
+ final DocumentControlModel dcm = cm.getDocumentById(this.pesConfig.getId());
+ this.mc = new MainControl(this.pesConfig, this.pesConfig.getNamespaces(), dcm, new File(this.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, cpl) {
+ public AbstractControlContentHandler getControlContentHandler(final String documentModelId, final DocumentControlModel docCtrlMod, final Hashtable<String, Object> parameters, final String file, final ControlProgressListener cpl) {
+ final AbstractControlContentHandler cch = new AbstractControlContentHandler(this.getDocumentModelId(), dm2.getNamespaces(), dcm, parameters, file, cpl) {
@Override
- public Pair getCollectivite(String documentModelId, String fileName) throws ToolException {
+ public Pair getCollectivite(final String documentModelId, final String fileName) throws ToolException {
return new Pair("xxxxxxxxxxx", "Collectivité d'analyse");
}
@Override
- public Pair getBudget(String documentModelId, Pair collectivite, String fileName) throws ToolException, UnauthorizedException {
+ public Pair getBudget(final String documentModelId, final Pair collectivite, final String fileName) throws ToolException, UnauthorizedException {
return new Pair("00", "Budget principal");
}
};
return cch;
}
};
-
- if (pesConfig.getTextToXmlTransformer() != null) {
- mc.setTextToXmlTransformer(pesConfig.getTextToXmlTransformer());
+
+ if (this.pesConfig.getTextToXmlTransformer() != null) {
+ this.mc.setTextToXmlTransformer(this.pesConfig.getTextToXmlTransformer());
}
}
* des valeurs sous la forme <tt>"{val1, val2, val3, ...}"</tt>
* @return true/false (succes/echec)
*/
- public boolean checkParameters(Hashtable<String, Object> hashParams) {
+ public boolean checkParameters(final Hashtable<String, Object> hashParams) {
boolean ret = true;
- DocumentControlModel dcm = mc.getDocumentControl();
- for (ParamModel param : dcm.getParams()) {
+ final DocumentControlModel dcm = this.mc.getDocumentControl();
+ for (final ParamModel param : dcm.getParams()) {
- Object val = hashParams.get(param.getId());
+ final Object val = hashParams.get(param.getId());
if (val == null) {
System.err.println("ERROR: Mandatory parameter " + param.getId() + " Not found ");
ret = false;
*/
public void listMandatoryParameters() {
- DocumentControlModel dcm = mc.getDocumentControl();
+ final DocumentControlModel dcm = this.mc.getDocumentControl();
System.err.println("Mandatory parameters are:");
- for (ParamModel param : dcm.getParams()) {
+ for (final 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);
+ public String getParameterDataType(final String paramId) {
+ final DocumentControlModel dcm = this.mc.getDocumentControl();
+ final ParamModel param = dcm.getParamById(paramId);
if (param != null) {
return param.getDatatype();
} else {
* @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 {
+ public Hashtable<String, Document> controle(final File fileToRead, final Hashtable<String, Object> parameters) throws Exception {
// XemeliosUser localUser = new LocalUser();
- Hashtable<String, Document> domDocuments = new Hashtable<String, Document>();
- if (!checkParameters(parameters)) {
- listMandatoryParameters();
+ final Hashtable<String, Document> domDocuments = new Hashtable<String, Document>();
+ if (!this.checkParameters(parameters)) {
+ this.listMandatoryParameters();
return domDocuments;// qui est vide
}
- File rapport = File.createTempFile("rapport", "xml");
+ final 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());
+ final File tmpEnrichi = File.createTempFile("pesv2-enrichi", "xml");
+ this.mc.setControlProgressListener(this);
+ this.mc.setParameters(parameters);
+ this.mc.setFileToControl(fileToRead);
+ this.mc.setFichierEnrichiLocation(tmpEnrichi.getAbsolutePath());
+ this.mc.setRapportLocation(rapport.getAbsolutePath());
// use any utility to run control
- mc.run();
+ this.mc.run();
- if (mc.getControlStatus() != MainControl.STATUS_NOT_CONTROLLED) {
- if (mc.getControlStatus() > MainControl.STATUS_NOT_SCHEMA_VALID) {
+ if (this.mc.getControlStatus() != MainControl.STATUS_NOT_CONTROLLED) {
+ if (this.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();
+ final TransformerFactory tFactory = FactoryProvider.getTransformerFactory();
+ final Transformer tr = tFactory.newTransformer(new StreamSource(new File(this.pesConfig.getBaseDirectory(), this.pesConfig.getGlobalImportXsltFile())));
+ final 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();
+ if (this.rapportConfig.getGlobalImportXsltFile() != null && this.rapportConfig.getGlobalImportXsltFile().length() > 0) {
+ final TransformerFactory tFactory = FactoryProvider.getTransformerFactory();
+ final Transformer tr = tFactory.newTransformer(new StreamSource(new File(this.rapportConfig.getBaseDirectory(), this.rapportConfig.getGlobalImportXsltFile())));
+ final 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);
+ final DocumentBuilderFactory dFactory = FactoryProvider.getDocumentBuilderFactory();
+ final Document drapport = dFactory.newDocumentBuilder().parse(rapport);
domDocuments.put("Rapport", drapport);
rapport.delete();
}
}
@Override
- public void notifyImportFinished(MainControl.Triplet triplet) {
+ public void notifyImportFinished(final MainControl.Triplet triplet) {
}
@Override
- public void notifyImportInterrupted(boolean hide) {
+ public void notifyImportInterrupted(final boolean hide) {
}
@Override
@Override
public String getDisplayName() {
- return getId();
+ return this.getId();
}
@Override
- public boolean hasRole(String arg0) {
+ public boolean hasRole(final String arg0) {
return true;
}
@Override
- public boolean hasDocument(String arg0) {
+ public boolean hasDocument(final String arg0) {
return true;
}
@Override
- public boolean hasCollectivite(String arg0, DocumentModel dm) {
+ public boolean hasCollectivite(final String arg0, final 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();
+ final ControlParser cp = new ControlParser();
+ cp.parse(new File(this.pesConfig.getBaseDirectory(), this.pesConfig.getControlConfigFile()));
+ final ControlsModel c = (ControlsModel) cp.getMarshallable();
c.validate();
ret = c;
- } catch (Exception ex) {
+ } catch (final Exception ex) {
logger.debug("Error in getControlsModel()!!!", ex);
}
return ret;
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.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseListener;
+import java.awt.image.ImageObserver;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
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.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.swing.ScaleChangeListener;
import org.xhtmlrenderer.swing.SelectionHighlighter;
+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.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.utils.Base64;
+import fr.gouv.finances.dgfip.utils.Dest;
+import fr.gouv.finances.dgfip.utils.IoUtils;
+import fr.gouv.finances.dgfip.utils.NavigationContext;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
+import fr.gouv.finances.dgfip.utils.xml.NamespaceContextImpl;
+import fr.gouv.finances.dgfip.utils.xml.transform.AbstractURIResolver;
+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.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.ui.ImageResources;
+import fr.gouv.finances.dgfip.xemelios.utils.AbstractUriTransformer;
+import fr.gouv.finances.dgfip.xemelios.utils.FileUtils;
+import fr.gouv.finances.dgfip.xemelios.utils.XmlUtils;
+
/**
- *
+ *
* @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;
+ 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 final PropertiesExpansion applicationConfiguration;
+
+ /** Creates a new instance of EditorHtmlViewer */
+ public EditorHtmlViewer(final Hashtable<String, File> documents, final DocumentsModel documentsModel, final String uri, final XemeliosUser user, final PropertiesExpansion applicationConfiguration) {
+ super(EditorHtmlViewer.DEFAULT_TITLE);
+ this.applicationConfiguration = applicationConfiguration;
+ this.documents = documents;
+ this.documentsModel = documentsModel;
+ this.userAgent = new LocalUserAgent(this, this, this.documentsModel, this.documents, applicationConfiguration, user);
+ this.xhtmlRenderer = new XemeliosXhtmlPanel(this.userAgent, this) {
+ @Override
+ public void setDocument(final File file) throws Exception {
+ super.setDocument(file);
+ this.setScalePolicy(ScalableXHTMLPanel.SCALE_POLICY_NONE);
+ }
+
+ @Override
+ public void setDocument(final Document doc, final String url) {
+ super.setDocument(doc, url);
+ this.setScalePolicy(ScalableXHTMLPanel.SCALE_POLICY_NONE);
+ }
+
+ @Override
+ public void setDocument(final InputStream stream, final String url) throws Exception {
+ super.setDocument(stream, url);
+ this.setScalePolicy(ScalableXHTMLPanel.SCALE_POLICY_NONE);
+ }
+ };
+ this.initializeComponents(uri);
+ this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+ }
+
+ public class LocalUserAgent extends XemeliosUserAgent {
+ private DocumentBuilder db = null;
+ private DocumentsModel documentsModel = null;
+ private Hashtable<String, File> documents = null;
+
+ public LocalUserAgent(final Component parent, final UpdatableToolbar tb, final DocumentsModel docs, final Hashtable<String, File> documents, final PropertiesExpansion applicationProperties, final XemeliosUser user) {
+ // super(null,parent,tb,user);
+ super(parent, applicationProperties, user);
+ this.setToolbar(tb);
+ this.documentsModel = docs;
+ this.documents = documents;
+ final DocumentBuilderFactory dbf = FactoryProvider.getDocumentBuilderFactory();
+ dbf.setNamespaceAware(true);
+ try {
+ this.db = dbf.newDocumentBuilder();
+ } catch (final Throwable t) {
+ // we ignore it, suppose Dom is correctly configured if editors can build xml files...
+ }
+ }
+
+ @Override
+ public Dest calculateQuery(final String query) {
+ AbstractUriTransformer uriTransformer = null;
+ NavigationContext ctx = null;
+ if (this.nc == null) {
+ ctx = new NavigationContext();
+ } else {
+ ctx = this.nc.clone();
+ }
+ final Hashtable<String, Object> params = new Hashtable<String, Object>();
+ params.put(HtmlViewer.PARAM_DESTINATION, HtmlViewer.VALUE_DESTINATION_INTERNAL);
+ String servlet = null;
+ String sTmp = query;
+ final int start = query.indexOf('?');
+ if (start >= 0) {
+ servlet = query.substring(query.indexOf("/") + 1, start);
+ sTmp = query.substring(start + 1);
+ }
+ if ("query".equals(servlet)) {
+ final StringTokenizer st = new StringTokenizer(sTmp, "&");
+ while (st.hasMoreTokens()) {
+ final String data = st.nextToken();
+ final int pos = data.indexOf('=');
+ if (pos > 0) {
+ final String paramName = data.substring(0, pos);
+ String paramValue = null;
+ try {
+ paramValue = URLDecoder.decode(data.substring(pos + 1), "UTF-8");
+ } catch (final Throwable t) {
+ }
+ if ("docId".equals(paramName)) {
+ ctx.setDocId(paramValue);
+ String className = null;
+ try {
+ className = Loader.getDocumentsInfos(null).getDocumentById(paramValue).getGlobalUriTransformer();
+ } catch (final Exception ex) {
+ ex.printStackTrace();
+ }
+ if (className != null) {
+ try {
+ final Class clazz = Class.forName(className);
+ final Object o = clazz.newInstance();
+ if (o instanceof AbstractUriTransformer) {
+ uriTransformer = (AbstractUriTransformer) o;
+ }
+ } catch (final 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")) {
+ final int virg = paramValue.indexOf(',');
+ final String pName = paramValue.substring(1, virg);
+ final String pValue = paramValue.substring(virg + 1, paramValue.length() - 1);
+ params.put(pName, pValue);
+ }
+ }
+ if (uriTransformer != null) {
+ uriTransformer.transformUriParam(paramName, paramValue, params);
+ }
+ }
+ }
+ return this.generateDestContext(ctx, params, HtmlViewer.INTERNAL_DESTINATION);
+ } else if ("resource".equals(servlet)) {
+ Dest ret = null;
+ try {
+ final File resourceDir = new File(EditorHtmlViewer.this.applicationConfiguration.getProperty("xemelios.resources.location"));
+ final File res = new File(resourceDir, sTmp);
+ ret = new Dest(res.toURI().toURL(), false);
+ } catch (final Throwable t) {
+ }
+ return ret;
+ } else if ("attachment".equals(servlet)) {
+ final DocumentModel dm = this.documentsModel.getDocumentById(ctx.getDocId());
+ if (dm.getId().equals("pes-aller")) {
+ final File fDoc = this.documents.get(ctx.getDocId());
+ if (fDoc == null) {
+ JOptionPane.showMessageDialog(EditorHtmlViewer.this, "Aucun " + dm.getTitre() + " disponible.", "Erreur", JOptionPane.ERROR_MESSAGE);
+ }
+ try {
+ final String[] args = sTmp.split("&");
+ String idUnique = null;
+ for (final String s : args) {
+ if (s.startsWith("pjId")) {
+ idUnique = s.substring(5);
+ break;
+ }
+ }
+ final Document doc = this.db.parse(fDoc);
+ final XPathFactory xpf = XPathFactory.newInstance();
+ final XPath xp = xpf.newXPath();
+ final NamespaceContextImpl ns = new NamespaceContextImpl();
+ ns.addMapping("n", "http://www.minefi.gouv.fr/cp/helios/pes_v2/Rev0/aller");
+ xp.setNamespaceContext(ns);
+ final 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(" ", "_");
+ final Element contenu = (Element) xp.evaluate("//n:PJ[n:IdUnique/@V='" + idUnique + "']/n:Contenu", pj, XPathConstants.NODE);
+ if (contenu != null) {
+ final File tmp = new File(FileUtils.getTempDir(), nomFichier);
+ if (tmp.exists()) {
+ tmp.delete();
+ }
+ final Element pesFacture = (Element) xp.evaluate("n:PESFacture", contenu, XPathConstants.NODE);
+ if (pesFacture != null) {
+ final TransformerFactory tFactory = FactoryProvider.getTransformerFactory();
+ final Transformer t = tFactory.newTransformer();
+ t.transform(new DOMSource(pesFacture), new StreamResult(tmp));
+ } else {
+ // c'est un fichier
+ final String text = xp.evaluate("//n:PJ[n:IdUnique/@V='" + idUnique + "']/n:Contenu/n:Fichier/text()", contenu);
+ final byte[] buffer = Base64.decode(text);
+ final GZIPInputStream gz = new GZIPInputStream(new ByteArrayInputStream(buffer));
+ final FileOutputStream fos = new FileOutputStream(tmp);
+ final 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 (final Exception ex) {
+ JOptionPane.showMessageDialog(EditorHtmlViewer.this, ex.getMessage(), ex.getClass().getName(), JOptionPane.ERROR_MESSAGE);
+ ex.printStackTrace();
+ }
+ }
+ // return null;
+ }
+ return null;
+ }
+
+ @Override
+ public Dest generateDestContext(final NavigationContext ctx, final Hashtable<String, Object> params, final boolean toExternalDest) {
+ // boolean noException = false;
+ Dest ret = null;
+ try {
+ final DocumentModel dm = this.documentsModel.getDocumentById(ctx.getDocId());
+ if (dm == null) {
+ throw new LocalException("doc " + ctx.getDocId() + " inconnu");
+ }
+ final EtatModel em = dm.getEtatById(ctx.getEtatId());
+ if (em == null) {
+ throw new LocalException("etat " + ctx.getEtatId() + " inconnu");
+ }
+ final ElementModel element = (ctx.getElementId() != null ? em.getElementById(ctx.getElementId()) : em.getBrowsableElement());
+ final File fDoc = this.documents.get(dm.getId());
+ if (fDoc == null) {
+ throw new LocalException("Aucun " + dm.getTitre() + " disponible.");
+ }
+ final Document doc = this.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
+ final InputStream is = IoUtils.getInputStream(f.getPath());
+ // Hashtable<String,Object> parameters = new Hashtable<String,Object>();
+ // parameters.putAll(params);
+ final TransformerFactory tFactory = FactoryProvider.getTransformerFactory();
+ final AbstractURIResolver uriResolver = dm.createUriResolver();
+ AbstractURIResolver.initializationHelper(uriResolver, doc, tFactory.getURIResolver(), f.getParentFile().toURI().toURL().toExternalForm());
+
+ tFactory.setURIResolver(uriResolver);
+
+ final 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 (final 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", this.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());
+ final ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ t.transform(new DOMSource(doc), new StreamResult(baos));
+ final ByteArrayInputStream htmlStream = new ByteArrayInputStream(baos.toByteArray());
+ final File tmp = File.createTempFile("xemelios-data-", ".html", FileUtils.getTempDir());
+ final BufferedInputStream bis = new BufferedInputStream(htmlStream);
+ final BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmp));
+ final 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();
+ final URL url = tmp.toURI().toURL();
+ this.nc = ctx;
+ ret = new Dest(url, toExternalDest);
+ } catch (final LocalException lEx) {
+ JOptionPane.showMessageDialog(this.getViewer(), lEx.getMessage(), "Erreur de paramétrage", JOptionPane.ERROR_MESSAGE);
+ } catch (final Exception ex) {
+ Component comp2 = this.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(final ScaleChangeEvent evt) {
+ if (evt.getComponent() == this.xhtmlRenderer) {
+ final double scale = evt.getScale();
+ int ix = -1;
+ for (int i = 0; i < this.availableScales.length; i++) {
+ final HtmlViewer.ScaleFactor sf = this.availableScales[i];
+ if (sf.getFactor() == scale) {
+ ix = i;
+ break;
+ }
+ }
+ final ItemListener[] iListeners = this.cbxZoom.getItemListeners();
+ for (final ItemListener il : iListeners) {
+ this.cbxZoom.removeItemListener(il);
+ }
+ if (ix == -1) {
+ final int scalePolicy = this.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;
+ }
+ }
+ this.cbxZoom.setSelectedIndex(ix);
+ for (final ItemListener il : iListeners) {
+ this.cbxZoom.addItemListener(il);
+ }
+ }
+ }
+
+ protected void initializeComponents(final String uri) {
+ final HtmlViewer.ScaleFactor[] scales = HtmlViewer.initializeScales();
+ this.availableScales = scales;
+ final IhmFactory iF = IhmFactory.newInstance();
+ this.xhtmlRenderer.addScaleChangeListener(this);
+ final MouseListener[] lls = this.xhtmlRenderer.getMouseListeners();
+ // for (int i = 0; i < lls.length; i++) {
+ // MouseListener ll = lls[i];
+ // if ( ll instanceof LinkListener ) {
+ // xhtmlRenderer.addMouseMotionListener((MouseMotionListener)ll);
+ // }
+ // }
+ this.highlighter = new SelectionHighlighter();
+ this.highlighter.install(this.xhtmlRenderer);
+ this.xhtmlRenderer.addMouseListener(this.highlighter);
+
+ FSScrollPane scroller;
+ this.getContentPane().setLayout(new BorderLayout());
+ final JToolBar tb = new JToolBar();
+ tb.add(this.pbPrevious = new JButton(IhmFactory.getIconFromResource(ImageResources.BRW_PREVIOUS)));
+ tb.add(this.pbNext = new JButton(IhmFactory.getIconFromResource(ImageResources.BRW_NEXT)));
+ tb.add(this.pbPrint = new JButton(IhmFactory.getIconFromResource(ImageResources.PRINT)));
+ final Action copyAction = new AbstractAction(null, IhmFactory.getIconFromResource(ImageResources.EDIT_COPY)) {
- 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 actionPerformed(final ActionEvent e) {
+ try {
+ final DocumentFragment df = EditorHtmlViewer.this.highlighter.getSelectionRange().extractContents();
+ final StringSelection ss = new StringSelection(XmlUtils.getStringRepresentation(df));
+ Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, ss);
+ } catch (final Exception ex) {
+ }
+ }
+ };
+ tb.add(this.pbCopy = new JButton(copyAction));
+ this.pbCopy.setToolTipText("Copier");
- @Override
- public void setDocument(Document doc, String url) {
- super.setDocument(doc, url);
- setScalePolicy(SCALE_POLICY_NONE);
- }
+ final Action selectAllAction = new AbstractAction(null, IhmFactory.getIconFromResource(ImageResources.EDIT_SELECT_ALL)) {
- @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;
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ EditorHtmlViewer.this.highlighter.selectAll();
+ }
- 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;
- }
-
- }
+ };
+ final JButton pbSelectAll = new JButton(selectAllAction);
+ pbSelectAll.setToolTipText("Tout sélectionner");
+ tb.add(pbSelectAll);
- @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)) {
+ this.getRootPane().registerKeyboardAction(copyAction, "copy", KeyStroke.getKeyStroke("ctrl C"), JComponent.WHEN_IN_FOCUSED_WINDOW);
+ this.getRootPane().registerKeyboardAction(selectAllAction, "selectAll", KeyStroke.getKeyStroke("ctrl A"), JComponent.WHEN_IN_FOCUSED_WINDOW);
+ tb.addSeparator();
+ tb.add(iF.newLabel("URL ", "normal"));
+ tb.add(this.dfUrl = new JTextField());
+ this.dfUrl.setEditable(false);
+ final Dimension dim = this.dfUrl.getMinimumSize();
+ this.dfUrl.setMinimumSize(new Dimension(100, (int) dim.getHeight()));
+ tb.addSeparator();
+ tb.add(iF.newLabel("Zoom ", "normal"));
+ this.cbxZoom = new JComboBox(scales);
+ this.cbxZoom.addItemListener(new ItemListener() {
+ @Override
+ public void itemStateChanged(final ItemEvent e) {
+ if (e.getStateChange() == ItemEvent.SELECTED) {
+ final HtmlViewer.ScaleFactor factor = (HtmlViewer.ScaleFactor) e.getItem();
+ if (factor.getFactor() == HtmlViewer.ScaleFactor.PAGE_WIDTH) {
+ EditorHtmlViewer.this.xhtmlRenderer.setScalePolicy(ScalableXHTMLPanel.SCALE_POLICY_FIT_WIDTH);
+ EditorHtmlViewer.this.xhtmlRenderer.doLayout();
+ } else if (factor.getFactor() == HtmlViewer.ScaleFactor.PAGE_HEIGHT) {
+ EditorHtmlViewer.this.xhtmlRenderer.setScalePolicy(ScalableXHTMLPanel.SCALE_POLICY_FIT_HEIGHT);
+ EditorHtmlViewer.this.xhtmlRenderer.doLayout();
+ } else if (factor.getFactor() == HtmlViewer.ScaleFactor.PAGE_WHOLE) {
+ EditorHtmlViewer.this.xhtmlRenderer.setScalePolicy(ScalableXHTMLPanel.SCALE_POLICY_FIT_WHOLE);
+ EditorHtmlViewer.this.xhtmlRenderer.doLayout();
+ } else {
+ EditorHtmlViewer.this.xhtmlRenderer.setScale(factor.getFactor());
+ }
+ }
+ }
+ });
+ this.cbxZoom.setSelectedIndex(2);
+ tb.add(this.cbxZoom);
+ this.getContentPane().add(tb, BorderLayout.PAGE_START);
+ this.getContentPane().add(scroller = new FSScrollPane(this.xhtmlRenderer), BorderLayout.CENTER);
+ scroller.setMinimumSize(new Dimension(ImageObserver.WIDTH, ImageObserver.HEIGHT));
+ scroller.setPreferredSize(new Dimension(ImageObserver.WIDTH, ImageObserver.HEIGHT));
+ scroller.setIgnoreRepaint(false);
+ this.pbPrint.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ EditorHtmlViewer.this.printToPDF();
+ }
+ });
+ this.pbPrint.setToolTipText("Imprimer");
+ this.pbPrevious.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ EditorHtmlViewer.this.goBack();
+ }
+ });
+ this.pbNext.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ EditorHtmlViewer.this.goForward();
+ }
+ });
+ this.pbPrevious.setEnabled(false);
+ this.pbNext.setEnabled(false);
+ if (uri != null) {
+ try {
+ final String eForm = this.userAgent.resolveURI(uri);
+ if (eForm != null) {
+ this.dfUrl.setText(eForm);
+ this.xhtmlRenderer.setDocument(eForm);
+ }
+ } catch (final Throwable t) {
+ t.printStackTrace();
+ System.exit(1);
+ }
+ }
+ this.pack();
+ this.setSize(700, 600);
+ }
- @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");
+ protected void printToPDF() {
+ try {
+ final File tmp = File.createTempFile("xemelios-data-", ".pdf", FileUtils.getTempDir());
+ final OutputStream os = new FileOutputStream(tmp);
+ final ITextRenderer renderer = new ITextRenderer();
+ // G. DON contribution
+ String fileName = this.dfUrl.getText();
+ final int posDiez = fileName.indexOf("#");
+ if (posDiez != -1) {
+ fileName = fileName.substring(0, posDiez);
+ }
+ final 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 (final Exception ex) {
+ ex.printStackTrace();
+ }
+ }
- final Action selectAllAction = new AbstractAction(null,IhmFactory.getIconFromResource(ImageResources.EDIT_SELECT_ALL)) {
+ protected void goBack() {
+ if (this.userAgent.hasBack()) {
+ this.xhtmlRenderer.setDocument(this.userAgent.getBack());
+ } else {
+ this.updateToolbarButtons();
+ }
+ }
- @Override
- public void actionPerformed(ActionEvent e) {
- highlighter.selectAll();
- }
+ protected void goForward() {
+ if (this.userAgent.hasForward()) {
+ this.xhtmlRenderer.setDocument(this.userAgent.getForward());
+ } else {
+ this.updateToolbarButtons();
+ }
+ }
- };
- JButton pbSelectAll = new JButton(selectAllAction);
- pbSelectAll.setToolTipText("Tout sélectionner");
- tb.add(pbSelectAll);
+ @Override
+ public void updateToolbarButtons() {
+ this.pbPrevious.setEnabled(this.userAgent.hasBack());
+ this.pbNext.setEnabled(this.userAgent.hasForward());
+ }
- 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);
- }
+ @Override
+ public void setBaseUrl(final String url) {
+ this.dfUrl.setText(url);
+ }
}
*/
package fr.gouv.finances.cp.xemelios.controls.editors;
+import java.io.File;
+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;
+
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.auth.UnauthorizedException;
+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.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.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;
- }
+ private static final Logger logger = Logger.getLogger(StandaloneController.class);
+
+ private static final int MODE_CTRL = 1;
+ private DocumentModel pesConfig = null;
+
+ /** Creates a new instance of StandaloneController */
+ public StandaloneController(final int mode) throws Exception {
+ final XemeliosUser localUser = new LocalUser();
+ final DocumentsModel config = Loader.getDocumentsInfos(System.getProperty(Constants.SYS_PROP_DOC_DEF_DIR));
+
+ this.pesConfig = config.getDocumentById("PES_Aller");
+ final DocumentModel rapportConfig = config.getDocumentById("rapportapport");
+ final Hashtable<String, File> documents = new Hashtable<String, File>();
+ final StringBuffer uri = new StringBuffer();
+
+ final File fichierEnrichi = new File("/home/chm/tmp/pesv2-enrichi.xml");
+ final 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");
+ final 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 = this.pesConfig;
+ final ControlsModel cm = this.getControlsModel();
+ final DocumentControlModel dcm = cm.getDocumentById(this.pesConfig.getId());
+
+ final MainControl mc = new MainControl(this.pesConfig, this.pesConfig.getNamespaces(), dcm,
+ // pesConfig.getTitre(),
+ new File(this.pesConfig.getBaseDirectory(), dcm.getControlTechById("TECH03").getParamTechById("schemaLocation").getValue())) {
+
+ @Override
+ public AbstractControlContentHandler getControlContentHandler(final String documentModelId, final DocumentControlModel docCtrlMod, final Hashtable<String, Object> parameters, final String file, final ControlProgressListener cpl) {
+ final AbstractControlContentHandler cch = new AbstractControlContentHandler(this.getDocumentModelId(), dm2.getNamespaces(), dcm, parameters, file, null) {
+
+ @Override
+ public Pair getCollectivite(final String documentModelId, final String fileName) throws ToolException {
+ return new Pair("xxxxxxxxxxx", "Collectivité d'analyse");
+ }
+
+ @Override
+ public Pair getBudget(final String documentModelId, final Pair collectivite, final 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 (this.pesConfig.getTextToXmlTransformer() != null) {
+ mc.setTextToXmlTransformer(this.pesConfig.getTextToXmlTransformer());
+ }
+
+ final File tmpEnrichi = new File(FileUtils.getTempDir(), "tmp-pesv2-enrichi.xml");
+
+ mc.setParameters(this.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
+ final TransformerFactory tFactory = FactoryProvider.getTransformerFactory();
+ final Transformer tr = tFactory.newTransformer(new StreamSource(new File(this.pesConfig.getBaseDirectory(), this.pesConfig.getGlobalImportXsltFile())));
+ final 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) {
+ final TransformerFactory tFactory = FactoryProvider.getTransformerFactory();
+ final Transformer tr = tFactory.newTransformer(new StreamSource(new File(rapportConfig.getBaseDirectory(), rapportConfig.getGlobalImportXsltFile())));
+ final 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 {
+ final TransformerFactory tFactory = FactoryProvider.getTransformerFactory();
+ final Transformer tr = tFactory.newTransformer(new StreamSource(new File(this.pesConfig.getBaseDirectory(), this.pesConfig.getGlobalImportXsltFile())));
+ final StreamResult result = new StreamResult(fichierEnrichi);
+ tr.transform(new StreamSource(fileToRead), result);
+ result.getOutputStream().flush();
+ result.getOutputStream().close();
+ // DEBUG PURPOSES
+ final 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");
+ }
+ final 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
+ final 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(final MainControl.Triplet triplet) {
+ }
+
+ @Override
+ public void notifyImportInterrupted(final boolean hide) {
+ }
+
+ @Override
+ public void stopWaiting() {
+ }
+
+ @Override
+ public void notifyTechniqueValidationFailed() {
+ }
+
+ public static void main(final String[] args) {
+ try {
+ new StandaloneController(MODE_CTRL);
+ } catch (final 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 this.getId();
+ }
+
+ @Override
+ public boolean hasRole(final String arg0) {
+ return true;
+ }
+
+ @Override
+ public boolean hasDocument(final String arg0) {
+ return true;
+ }
+
+ @Override
+ public boolean hasCollectivite(final String arg0, final DocumentModel dm) {
+ return true;
+ }
+ }
+
+ private ControlsModel getControlsModel() {
+ ControlsModel ret = null;
+ try {
+ final ControlParser cp = new ControlParser();
+ cp.parse(new File(this.pesConfig.getBaseDirectory(), this.pesConfig.getControlConfigFile()));
+ final ControlsModel c = (ControlsModel) cp.getMarshallable();
+ c.validate();
+ ret = c;
+ } catch (final Exception ex) {
+ logger.debug("Error in getControlsModel()!!!", ex);
+ }
+ return ret;
+ }
public String getVersionComposent() {
return null;
import javax.swing.SwingUtilities;
/**
- *
- * @author chm
+ *
+ * @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) {}
- }
-
+ private long maxProgress, currentProgress;
+
+ /** Creates new form DlgPatchProgress */
+ public DlgPatchProgress() {
+ super((JFrame) null, false);
+ this.initComponents();
+ this.setLocationRelativeTo(null);
+ }
+
+ @Override
+ public void startProgress(final String message) {
+ this.message.setText(message);
+ this.startProgress();
+ this.pack();
+ }
+
+ @Override
+ public void startProgress() {
+ this.currentProgress = 0L;
+ }
+
+ @Override
+ public void setMaxProgress(final long maxProgress) {
+ this.maxProgress = maxProgress;
+ }
+
+ @Override
+ public void pushProgress() {
+ this.currentProgress++;
+ this.displayProgress();
+ }
+
+ @Override
+ public void endProgress() {
+ this.currentProgress = this.maxProgress;
+ this.displayProgress();
+ }
+
+ private void displayProgress() {
+ final int progressValue = (int) ((float) this.currentProgress / (float) this.maxProgress * 100f);
+ final Runnable p = new Runnable() {
+ @Override
+ public void run() {
+ DlgPatchProgress.this.progress.setValue(progressValue);
+ DlgPatchProgress.this.progress.paintImmediately(0, 0, DlgPatchProgress.this.progress.getWidth(), DlgPatchProgress.this.progress.getHeight());
+ }
+ };
+ if (SwingUtilities.isEventDispatchThread()) {
+ p.run();
+ } else {
+ try {
+ SwingUtilities.invokeAndWait(p);
+ } catch (final 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() {
+ this.message = new javax.swing.JLabel();
+ this.progress = new javax.swing.JProgressBar();
+
+ this.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
+ this.setTitle("Mise \u00e0 jour de la base de donn\u00e9es");
+ this.setAlwaysOnTop(true);
+ this.setResizable(false);
+
+ this.progress.setStringPainted(true);
+
+ final org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this.getContentPane());
+ this.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, this.progress, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 364, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.LEADING, this.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(this.message, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 9, Short.MAX_VALUE).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(this.progress, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE).addContainerGap()));
+ this.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 this.currentProgress;
+ }
+
+ @Override
+ public void setProgress(final long progress) {
+ this.currentProgress = progress;
+ this.displayProgress();
+ }
+
+ @Override
+ public void setMessage(final String message) {
+ this.message.setText(message);
+ final 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 (final Throwable t) {
+ }
+ }
+ }
+
}
public class CheckThreadViolationRepaintManager extends RepaintManager {
- // it is recommended to pass the complete check
- private boolean completeCheck = true;
+ // it is recommended to pass the complete check
+ private boolean completeCheck = true;
- public boolean isCompleteCheck() {
- return completeCheck;
- }
+ public boolean isCompleteCheck() {
+ return this.completeCheck;
+ }
- public void setCompleteCheck(boolean completeCheck) {
- this.completeCheck = completeCheck;
- }
+ public void setCompleteCheck(final boolean completeCheck) {
+ this.completeCheck = completeCheck;
+ }
- @Override
- public synchronized void addInvalidComponent(JComponent component) {
- checkThreadViolations(component);
- super.addInvalidComponent(component);
- }
+ @Override
+ public synchronized void addInvalidComponent(final JComponent component) {
+ this.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);
- }
+ @Override
+ public void addDirtyRegion(final JComponent component, final int x, final int y, final int w, final int h) {
+ this.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();
- }
- }
+ private void checkThreadViolations(final JComponent c) {
+ if (!SwingUtilities.isEventDispatchThread() && (this.completeCheck || c.isShowing())) {
+ final Exception exception = new Exception();
+ boolean repaint = false;
+ boolean fromSwing = false;
+ final StackTraceElement[] stackTrace = exception.getStackTrace();
+ for (final 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();
+ }
+ }
}
*/
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.io.FileWriter;
+import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
+import java.util.Enumeration;
+import java.util.Hashtable;
+import java.util.Vector;
+
+import jxl.write.WriteException;
+
import org.apache.log4j.Logger;
+import fr.gouv.finances.dgfip.utils.Amount;
import fr.gouv.finances.dgfip.utils.StringUtilities;
-
+import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
+import fr.gouv.finances.dgfip.xemelios.export.ExportElementModel;
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;
- }
- };
+ 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 final Hashtable<String, Vector<CsvSheet>> sheets = new Hashtable<String, Vector<CsvSheet>>();
+ private final Exporter caller;
+ // private HtmlSheet mainSheet;
+ private String workbookPrefix = null;
+ private final SimpleDateFormat df;
+
+ public CsvExporter(final Exporter caller) {
+ this.caller = caller;
+ this.df = new SimpleDateFormat(caller.getApplicationConfiguration().getProperty("xemelios.date.format", "dd/MM/yyyy"));
+ }
+
+ // Fonctions appellees par Exporter.java
+ /**
+ * Initialisation
+ */
+ @Override
+ 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
+ //
+ final FileWriter xl = new FileWriter(this.caller.fDest);
+ xl.close();
+
+ this.workbookPrefix = StringUtilities.removeFileNameSuffix(this.caller.fDest.getPath());
+
+ }
+
+ void recopieFichier(final String src, final String dst, final 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 (final Exception e) {
+ e.printStackTrace(); // n'importe quelle exception
+ } finally { // finalement on ferme
+ if (in != null) {
+ try {
+ in.close();
+ } catch (final IOException e) {
+ }
+ }
+ if (out != null) {
+ try {
+ out.close();
+ } catch (final IOException e) {
+ }
+ }
+ }
+ }
+
+ /**
+ * Crée un <tt>CsvSheet</tt> et ajoute la liste des entetes de colonne
+ *
+ * @param eem
+ * @throws Exception
+ */
+ @Override
+ void buildSheet(final ExportElementModel eem) throws Exception {
+ Vector<CsvSheet> v = this.sheets.get(eem.getId());
+ if (v == null) {
+ v = new Vector<CsvSheet>();
+ }
+ this.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);
+ }
+ }
+
+ final String fileName = this.workbookPrefix + "_" + libelle; // + ".csv";
+
+ final CsvSheet sheet = new CsvSheet();
+ sheet.open(fileName);
+
+ v.add(sheet);
+
+ for (final ExportElementModel e : eem.getEnfants()) {
+ this.buildSheet(e);
+ }
+ this.caller.firstSheetId = eem.getId();
+ }
+
+ /**
+ * Apporte des finitions
+ */
+ @Override
+ void finish() throws Exception {
+ // pour l'instant rien
+ }
+
+ /**
+ * Fermeture et nettoyage
+ */
+ @Override
+ void close() {
+ final Enumeration elems = this.sheets.keys();
+ while (elems.hasMoreElements()) {
+ final String k = (String) elems.nextElement();
+ final Vector<CsvSheet> v = this.sheets.get(k);
+ for (final CsvSheet s : v) {
+
+ s.close();
+ }
+
+ }
+ // mainSheet.close();
+ }
+
+ /**
+ * Verifie l'existence d'unr feuille dans le classeur
+ *
+ * @param sheetId
+ * le nom de la feuille
+ */
+ @Override
+ boolean sheetExists(final String sheetId) {
+ final Vector<CsvSheet> v = this.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(final String sheetId) {
+ // suppose qu'on a appele sheetExists(sheetId)
+ final CsvSheet ws = this.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(final String sheetId, final Object o, final int line, final int col, final boolean bypassLineRenum) throws Exception {
+
+ int newline = 0;
+ if (bypassLineRenum) {
+ newline = line;
+ } else {
+ final int _ligne = this.caller.getLastLine(sheetId);
+ if (_ligne >= (MAX_ROWS_PER_SHEET * this.sheets.get(sheetId).size())) {
+ this.splitSheet(sheetId);
+ }
+
+ // renumérotation de la ligne
+ newline = _ligne;
+ newline = _ligne % (MAX_ROWS_PER_SHEET) + 2;
+ }
+
+ final CsvSheet sheet = this.getLastSheet(sheetId);
+ final String s = this.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(final String sheetId, final int col1, final int row1, final int col2, final int row2) {
+ /*
+ * forget it CsvSheet _ws = getLastSheet(sheetId);
+ *
+ * try { _ws.mergeCells(col1, row1, col2, row2); } catch(Exception e) {}
+ */
+ }
+
+ @Override
+ void flushLine(final String sheetId) {
+ final CsvSheet _ws = this.getLastSheet(sheetId);
+ _ws.flushLine();
+ }
+
+ // Fonctions a usage interne mises en protected on sait jamais
+ /**
+ * Formatage de l'objet a ecrire
+ */
+ protected String formatted(final Object o, final 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 = this.df.format(o);
+ } else if (o instanceof Amount) {
+ final 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(final 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(final String sheetId) {
+ final Vector<CsvSheet> v = this.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(final String id) {
+ CsvSheet ret = null;
+ final ElementModel e = this.caller.getEMFromId(id);
+ if (e.getSimpleParent() != null) {
+ final String pName = e.getSimpleParent().getElement();
+ ret = this.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(final String id) {
+ final Vector<CsvSheet> v = this.sheets.get(id);
+ final CsvSheet wsRef = v.get(0);
+ final CsvSheet otherRef = this.getLastSheet(id);
+
+ wsRef.close();
+
+ final CsvSheet ws = new CsvSheet();
+
+ final 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
+
+ final String sb = (nf.format(v.size()));
+ final String fname = wsRef.getName() + "_" + sb;
+ ws.open(fname);
+
+ this.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(final String libelle, final boolean addPrefix) {
+ String fileName;
+ if (addPrefix) {
+ fileName = this.workbookPrefix + "_" + libelle + ".csv";
+ } else {
+ fileName = libelle + ".csv";
+ }
+
+ final 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(final String fname) {
+ try {
+ final FileWriter out = new FileWriter(fname + ".csv");
+ this.writer = new CSVWriter(out);
+ } catch (final IOException e) {
+ logger.error("HtmlSheet.open(" + fname + ")", e);
+ }
+ // Version initial tableau surdimensionnnes hum=
+ this.name = fname;
+ this.titles = new String[100];
+ this.names = new String[100];
+ this.entries = new String[100];
+ this.maxTitle = 0;
+ this.maxName = 0;
+ this.maxEntry = 0;
+ this.rowCount = 0;
+ this.titlesFlushed = false;
+ this.namesFlushed = false;
+ }
+
+ void close() {
+ if (this.writer != null) {
+ try {
+ this.writer.close();
+
+ } catch (final IOException e) {
+ logger.error("HtmlSheet.close()", e);
+ }
+ this.writer = null;
+ }
+ }
+
+ String getName() {
+ return this.name;
+ }
+
+ int getRows() {
+ return this.rowCount;
+ }
+
+ void addTitle(final String s, final int col) {
+ if (!this.titlesFlushed) {
+ if (col >= this.titles.length || this.maxTitle >= this.titles.length) {
+ // cas ou il faut redimensionner
+ final int oldlength = this.titles.length;
+ final int newlength = oldlength + oldlength / 2;
+ final String[] tm = new String[newlength];
+ for (int i = 0; i < oldlength; ++i) {
+ tm[i] = this.titles[i];
+ }
+ this.titles = tm;
+ }
+ while (this.maxTitle + 1 < col) {
+ this.maxTitle++;
+ this.titles[this.maxTitle] = CsvExporter.this.formatted("", 0); // pour simuler la presentation en Excel pur
+
+ }
+ this.titles[col] = s;
+ if (col > this.maxTitle) {
+ this.maxTitle = col;
+ }
+
+ }
+ }
+
+ void addName(final String s, final int col) {
+ if (!this.namesFlushed) {
+ if (col >= this.names.length || this.maxName >= this.names.length) {
+ // cas ou il faut redimensionner
+ final int oldlength = this.names.length;
+ final int newlength = oldlength + oldlength / 2;
+ final String[] tm = new String[newlength];
+ for (int i = 0; i < oldlength; ++i) {
+ tm[i] = this.names[i];
+ }
+ this.names = tm;
+ }
+ while (this.maxName + 1 < col) {
+ this.maxName++;
+ this.names[this.maxName] = CsvExporter.this.formatted("", 1);
+ }
+ this.names[col] = s;
+ if (col > this.maxName) {
+ this.maxName = col;
+ }
+
+ }
+ }
+
+ void addEntry(final String s, final int col) {
+ if (col >= this.entries.length || this.maxEntry >= this.entries.length) {
+ // cas ou il faut redimensionner
+ final int oldlength = this.entries.length;
+ final int newlength = oldlength + oldlength / 2;
+ final String[] tm = new String[newlength];
+ for (int i = 0; i < oldlength; ++i) {
+ tm[i] = this.entries[i];
+ }
+ this.entries = tm;
+ }
+
+ while (this.maxEntry + 1 < col) {
+ this.maxEntry++;
+ this.entries[this.maxEntry] = CsvExporter.this.formatted("", 999);
+ }
+ this.entries[col] = s;
+ if (col > this.maxEntry) {
+ this.maxEntry = col;
+ }
+ }
+
+ void mergeCells(final int col1, final int row1, final int col2, final 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() {
+ this.writer.writeNext(this.titles, this.maxTitle);
+ this.titlesFlushed = true;
+ ++this.rowCount;
+ }
+
+ void flushNames() {
+ this.writer.writeNext(this.names, this.maxName);
+ this.namesFlushed = true;
+ ++this.rowCount;
+ }
+
+ void flushLine() {
+ if (!this.titlesFlushed) {
+ this.flushTitles();
+ }
+ if (!this.namesFlushed) {
+ this.flushNames();
+ }
+
+ this.writer.writeNext(this.entries, this.maxEntry);
+ this.maxEntry = 0;
+ ++this.rowCount;
+ }
+ };
}
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);
+ public ExportUndertaker() {
+ };
+
+ public ExportUndertaker(final 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);
}
*/
package fr.gouv.finances.cp.xemelios.export;
-import fr.gouv.finances.cp.utils.PropertiesExpansion;
import java.io.File;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.util.Enumeration;
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.cp.utils.PropertiesExpansion;
+import fr.gouv.finances.cp.xemelios.ui.export.DlgSearchConfig;
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.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.data.DataLayerManager;
-
-import fr.gouv.finances.dgfip.xemelios.utils.HashSwap;
-
-import fr.gouv.finances.dgfip.xemelios.utils.LongueurMax;
+import fr.gouv.finances.dgfip.xemelios.data.DataResultSet;
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;
+import fr.gouv.finances.dgfip.xemelios.utils.HashSwap;
+import fr.gouv.finances.dgfip.xemelios.utils.LongueurMax;
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
- try {
- if("mysql".equals(DataLayerManager.getImplementation().getLayerName())) {
- drs.getListeResultatModel().setTriDefaut(null);
- drs.getListeResultatModel().setOrdre(null);
- }
- } catch(Throwable ignorable) {}
- }
-
- @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();");
- int ligne = 2;
-
- 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);
- }
- }
-
- /*
- * 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();
-
- boolean finished = isCancelled();
- while(!finished){
- while (drs.hasNext() && !isCancelled()) {
- DataHandler dh = drs.next();
- logger.debug("exporting "+dh.getDocumentId());
- exportEM(drs.getListeResultatModel().getParent(), dh, drs.getListeResultatModel().getParent().getId(), ligne);
- ligne++;
- }
-
- if(!isCancelled() && drs.hasNextPage()){
- drs.nextPage();
- }else{
- finished = true;
- }
- }
-
- if (!isCancelled()) {
- undertaker.finish();
- }
- } catch (Exception e) {
- logger.error("Exporter Error catched", e);
- } finally {
- undertaker.close();
- }
- logger.debug("endOf doExport() : " + (ligne - 2) + " rows");
- }
-
- /**
- * 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;
- }
+ public class ExportedElementTag {
+
+ @LongueurMax(value = 1)
+ public int dummy;
+
+ public ExportedElementTag(final int i) {
+ this.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 final 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 final 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 final Hashtable<String, Integer> lignesExporteesForElement = new Hashtable<String, Integer>();
+
+ protected ExportUndertaker getUndertaker() {
+ String undertakerClassName = this.applicationConfiguration.getProperty(Constants.SYS_PROP_XEMELIOS_EXPORTER_CLASS);
+ if (undertakerClassName == null) {
+ undertakerClassName = "fr.gouv.finances.cp.xemelios.export.FullXlsExporter";
+ }
+
+ try {
+ final Class undertakerClass = Class.forName(undertakerClassName);
+ final Class[] exporterArgsClass = new Class[] { Exporter.class };
+ final Object[] exporterArgs = new Object[] { this };
+ final Constructor constructor = undertakerClass.getConstructor(exporterArgsClass);
+ final ExportUndertaker ud = (ExportUndertaker) constructor.newInstance(exporterArgs);
+ return ud;
+ } catch (final ClassNotFoundException e) {
+ logger.error("", e);
+ return null;
+ } catch (final NoSuchMethodException e) {
+ logger.error("", e);
+ return null;
+ } catch (final InstantiationException e) {
+ logger.error("", e);
+ return null;
+ } catch (final IllegalAccessException e) {
+ logger.error("", e);
+ return null;
+ } catch (final IllegalArgumentException e) {
+ logger.error("", e);
+ return null;
+ } catch (final InvocationTargetException e) {
+ logger.error("", e);
+ return null;
+ }
+ }
+
+ private void addLine(final String el) {
+ Integer l = this.lignesExporteesForElement.get(el);
+ if (l == null) {
+ l = new Integer(0);
+ }
+ l = new Integer(l.intValue() + 1);
+ this.lignesExporteesForElement.put(el, l);
+
+ this.undertaker.flushLine(el);
+ }
+
+ int getLastLine(final String el) {
+ Integer l = this.lignesExporteesForElement.get(el);
+ if (l == null) {
+ l = new Integer(0);
+ }
+ return l.intValue();
+ }
+
+ public Exporter(final File f, final DataResultSet drs, final DocumentModel dm, final String etatId, final ElementModel em, final ConfigModel cf, final 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
+ try {
+ if ("mysql".equals(DataLayerManager.getImplementation().getLayerName())) {
+ drs.getListeResultatModel().setTriDefaut(null);
+ drs.getListeResultatModel().setOrdre(null);
+ }
+ } catch (final Throwable ignorable) {
+ }
+ }
+
+ @Override
+ protected Object doInBackground() throws Exception {
+ this.doExport();
+ if (!this.isCancelled()) {
+ ((DlgSearchConfig) this.getParentFrame()).showXLS();
+ } else {
+ ((DlgSearchConfig) this.getParentFrame()).getGlassPane().setVisible(false);
+ }
+ return null;
+ }
+
+ @Override
+ protected void done() {
+ super.done();
+ this.cleanAfterRun();
+ }
+
+ public PropertiesExpansion getApplicationConfiguration() {
+ return this.applicationConfiguration;
+ }
+
+ public void cleanAfterRun() {
+ // nettoyage de la mémoire
+ this.timeEndGenerate = System.currentTimeMillis();
+ this.gapGenerate = this.timeEndGenerate - this.timeStartGenerate;
+ // quelle est la memoire utilisee par exported elements
+ System.gc();
+ final Enumeration cles = this.exportedElements.keys();
+ while (cles.hasMoreElements()) {
+ final String k = (String) cles.nextElement();
+ final HashSwap<ExportedElementTag> val = this.exportedElements.get(k);
+ try {
+ val.destruct();
+ } catch (final Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ this.exportedElements.clear();
+ this.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();");
+ int ligne = 2;
+
+ try {
+ this.undertaker = this.getUndertaker();
+ this.timeStartGenerate = System.currentTimeMillis();
+ this.undertaker.initialize();
+
+ /**
+ * Création des feuilles du classeur
+ */
+ for (final ExportElementModel eem : this.cf.getExportModel().getEnfants()) {
+ if (this.shouldEEMBeExported(eem)) {
+ this.undertaker.buildSheet(eem);
+ }
+ }
+
+ /*
+ * 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
+ */
+ final ListeResultatModel lrm = this.drs.getListeResultatModel();
+ final 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
+ final String tridefault = lrmClone.getTriDefaut();
+ lrmClone.removeAllChamps();
+ this.addAllExportableChamps(lrmClone, this.drs.getListeResultatModel().getParent(), tridefault);
+ this.drs.setListeResultatModel(lrmClone);
+ this.drs.firstPage();
+
+ boolean finished = this.isCancelled();
+ while (!finished) {
+ while (this.drs.hasNext() && !this.isCancelled()) {
+ final DataHandler dh = this.drs.next();
+ logger.debug("exporting " + dh.getDocumentId());
+ this.exportEM(this.drs.getListeResultatModel().getParent(), dh, this.drs.getListeResultatModel().getParent().getId(), ligne);
+ ligne++;
+ }
+
+ if (!this.isCancelled() && this.drs.hasNextPage()) {
+ this.drs.nextPage();
+ } else {
+ finished = true;
+ }
+ }
+
+ if (!this.isCancelled()) {
+ this.undertaker.finish();
+ }
+ } catch (final Exception e) {
+ logger.error("Exporter Error catched", e);
+ } finally {
+ this.undertaker.close();
+ }
+ logger.debug("endOf doExport() : " + (ligne - 2) + " rows");
+ }
+
+ /**
+ * 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(final ListeResultatModel l, final ElementModel e, final String tridefault) throws Exception {
+ final Vector<String> tri = new Vector<String>();
+ if (tridefault != null) {
+ for (final String s : tridefault.split(",")) {
+ tri.add(s);
+ }
+ }
+ for (final 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(final ElementModel _em, final DataHandler _dh, final String sheetId, final int _ligne) throws Exception {
+ // La configuration de l'élément concerné
+ ExportElementModel eem = null;
+ for (final ExportElementModel e : this.cf.getExportModel().getEnfants()) {
+ eem = this.getEEMFromId(e, _em.getId());
+ if (eem != null) {
+ break;
+ }
+ }
+ // remplissage des feuilles des parents
+ final Vector<SimpleElement> parents = this.pushParents(_em, "");
+ this.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 (this.undertaker.sheetExists(sheetId)) {
+ for (int i = (parents.size() - 1); i >= 0; i--) {
+ // if (_ligne < 2) {
+ // }
+ col = this.writeCellsOfParent(this.dm.getEtatById(this.etatId).getElementById(parents.get(i).getElement()), parents.get(i).getPseudoCompletePath(), _dh, sheetId, _ligne, col, (_ligne <= 2), false);
+ this.undertaker.mergeCells(sheetId, oldCol, 0, col - 1, 0);
+ oldCol = col;
+ }
+
+ boolean firstCol = true;
+ // parcours des colonnes configurées
+ for (final ExportChampModel ecm : eem.getChamps()) {
+ if (ecm.isSelectionne()) {
+ // première ligne => entete
+ if (_ligne == 2) {
+ if (firstCol) {
+ this.undertaker.writeCell(sheetId, _em.getTitre(), 0, col, true);
+ }
+ this.undertaker.writeCell(sheetId, ecm.getLibelle(), 1, col, true);
+ }
+ final int index = this.getColumnIndex(ecm.getId(), _em);
+ if (index < 0) {
+ throw new Exception("champ " + ecm.getId() + " not found in " + _em.getConfigXPath());
+ }
+ this.undertaker.writeCell(sheetId, _dh.getValueAtColumn(index), _ligne, col, false);
+ col++;
+ firstCol = false;
+ }
+ }
+
+ this.undertaker.mergeCells(sheetId, oldCol, 0, col - 1, 0);
+ // remplissage des feuilles des enfants
+ if (this.hasChildrenToExport(this.em)) {
+ this.exportEnfants(parents, this.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 = this.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");
+ this.exportedElements.put(_em.getId(), h);
+
+ }
+
+ // String vId = getIdentifiant (eem, _dh, _em);
+ final String vId = this.getIdentifiant(_dh, _em);
+ if (!h.containsKey(vId)) {
+ h.put(vId, new ExportedElementTag(1));
+ }
+
+ this.addLine(sheetId);
+ }
+ }
+
+ private void exportEnfants(final Vector<SimpleElement> parents, final ElementModel _em, final DataHandler _dh) throws Exception {
+ if (_em.getEnfant() != null) {
+ for (final String s : _em.getEnfant().getEnfants().keySet()) {
+ final SimpleElement enfantToExport = _em.getEnfant().getEnfants().get(s);
+
+ // la clé de cet élément
+ // La configuration de l'élément concerné
+ ExportElementModel eem = null;
+ for (final ExportElementModel e : this.cf.getExportModel().getEnfants()) {
+ eem = this.getEEMFromId(e, s);
+ if (eem != null) {
+ break;
+ }
+ }
+ ExportElementModel eemP = null;
+ for (final ExportElementModel e : this.cf.getExportModel().getEnfants()) {
+ eemP = this.getEEMFromId(e, _em.getId());
+ if (eemP != null) {
+ break;
+ }
+ }
+
+ // doit-on exporter cet enfant ?
+ if (this.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
+ final Vector<Object> parentsValues = this.getParentsValues(parents, _dh);
+ for (final ExportChampModel ecm : eemP.getChamps()) {
+ if (ecm.isIdentifiant()) {
+ parentsValues.add(_dh.getValueAtColumn(this.getColumnIndex(ecm.getId(), _em)));
+ }
+ }
+
+ this.exportEnfant(parentsValues, enfantToExport.getPseudoCompletePath(), enfantToExport, _dh.getElement(), enfantToExport.getElement(), _dh);
+ }
+ }
+ }
+ }
+
+ private Vector<Object> getParentsValues(final Vector<SimpleElement> parents, final DataHandler _dh) throws Exception {
+ final Vector<Object> ret = new Vector<Object>();
+
+ for (int p = parents.size() - 1; p >= 0; p--) {
+ ret.addAll(this.getParentValues(parents.get(p), _dh));
+ }
+
+ return ret;
+ }
+
+ private Vector<Object> getParentValues(final SimpleElement parent, final DataHandler _dh) throws Exception {
+ final Vector<Object> ret = new Vector<Object>();
+
+ final ElementModel element = this.getEMFromId(parent.getElement());
+
+ XPathFactory xpf;
+ try {
+ xpf = XPathFactory.newInstance(XPathFactory.DEFAULT_OBJECT_MODEL_URI);
+ } catch (final Throwable t) {
+ xpf = XPathFactory.newInstance();
+ }
+ final XPath xp = xpf.newXPath();
+ xp.setNamespaceContext(this.dm.getNamespaces());
+ final Node n = (Node) xp.evaluate(parent.getPseudoCompletePath(), _dh.getElement(), XPathConstants.NODE);
+ for (final ChampModel cm : element.getListeResultat().getListeChamps()) {
+ if (cm.isIdentifiant()) {
+ final DomPath dp = new DomPath(cm.getPath().getPath(), this.dm.getNamespaces());
+ ret.add(dp.getValue(n, false));
+ }
+ }
+
+ return ret;
+
+ }
+
+ private Vector<Object> getParentId(final ElementModel parent, final Object rootElement) throws Exception {
+ final Vector<Object> ret = new Vector<Object>();
+
+ for (final ChampModel cm : parent.getListeResultat().getListeChamps()) {
+ if (cm.isIdentifiant()) {
+ final DomPath dp = new DomPath(cm.getPath().getPath(), this.dm.getNamespaces());
+ ret.add(dp.getValue((Node) rootElement, false));
+ }
+ }
+
+ return ret;
+
+ }
+
+ private void exportEnfant(final Vector<Object> parentsValues, final String pathToEnfant, final SimpleElement enfantToExport, final Object rootElement, final String sheetId, final DataHandler _dh) throws Exception {
+ // int col = 0;
+
+ final int ligne = this.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
+ final Vector<Node> nodes = this.writeCellsOfEnfant(parentsValues, this.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
+ final ElementModel e = this.getEMFromId(enfantToExport.getElement());
+ if (e.getEnfant() != null) {
+ for (final String s : e.getEnfant().getEnfants().keySet()) {
+ final SimpleElement se = e.getEnfant().getEnfants().get(s);
+
+ ExportElementModel eem = null;
+ for (final ExportElementModel m : this.cf.getExportModel().getEnfants()) {
+ eem = this.getEEMFromId(m, se.getElement());
+ if (eem != null) {
+ break;
+ }
+ }
+ if (this.shouldEEMBeExported(eem)) {
+ for (final Node n : nodes) {
+ final Vector<Object> newParentsValues = new Vector<Object>();
+ newParentsValues.addAll(parentsValues);
+ newParentsValues.addAll(this.getParentId(this.getEMFromId(enfantToExport.getElement()), n));
+ this.exportEnfant(newParentsValues, se.getPath(), se, n, se.getElement(), _dh);
+ }
+ } else {
+ break;
+ }
+ }
+ }
+ }
+
+ private void exportParents(final Vector<SimpleElement> parents, final DataHandler _dh) throws Exception {
+ for (int i = 0; i < parents.size(); i++) {
+ final SimpleElement parentToExport = parents.get(i);
+ if (this.undertaker.sheetExists(parentToExport.getElement())) {
+
+ // si ws est null, c'est un parent qu'on ne veux pas exporter
+
+ final int ligne = this.getLastLine(parentToExport.getElement());
+ this.exportParent(parentToExport, parents, i, parentToExport.getElement(), _dh, ligne, true);
+ }
+ }
+ }
+
+ private int exportParent(final SimpleElement parentToExport, final Vector<SimpleElement> parents, final int indInParents, final String sheetId, final DataHandler _dh, final int ligne, final boolean doCheckMAJ) throws Exception {
+ // a-t-on déjà exporté cet élément ?
+ final ElementModel element = this.getEMFromId(parentToExport.getElement());
+ final String parentPath = parentToExport.getPseudoCompletePath();
+ if (doCheckMAJ && this.isExporte(parentToExport.getElement(), this.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 += this.writeCellsOfParent(element, parentToExport.getPseudoCompletePath(), _dh, sheetId, ligne, col, (ligne <= 2), (this.firstSheetId.equals(sheetId)));
+ if (doCheckMAJ) {
+ this.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 += this.exportParent(parents.get(indInParents + 1), parents, (indInParents + 1), sheetId, _dh, ligne, false);
+ if (indInParents == parents.size() - 1) {
+ if (ligne < 2) {
+ }
+ col += this.writeCellsOfParent(element, parentToExport.getPseudoCompletePath(), _dh, sheetId, ligne, col, (ligne <= 2), true);
+ if (doCheckMAJ) {
+ this.majExportes(parentToExport.getElement(), _dh, parentPath, element);
+ }
+ }
+ }
+ return col;
+ }
+
+ private boolean isExporte(final String idColl, final String id) {
+ // Hashtable<String,String> h = exportedElements.get(idColl);
+
+ boolean ret = false;
+ final HashSwap<ExportedElementTag> h = this.exportedElements.get(idColl);
+ if (h == null) {
+ return false;
+ } else {
+ try {
+ if (h.containsKey(id)) {
+ ret = true;
+ }
+ } catch (final Exception e) {
+ e.printStackTrace();
+ }
+ }
+ return ret;
+ }
+
+ private void majExportes(final String id, final DataHandler _dh, final String parentPath, final ElementModel em) throws Exception {
+ // Hashtable<String,String> h = exportedElements.get(id);
+
+ HashSwap<ExportedElementTag> h = this.exportedElements.get(id);
+ if (h == null) {
+ // h = new Hashtable<String,String>();
+ logger.info("new HashSwap..");
+ h = new HashSwap<ExportedElementTag>(ExportedElementTag.class);
+ logger.info("done");
+ this.exportedElements.put(id, h);
+ }
+ final String vId = this.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(final ElementModel _em, final String parentPath) {
+ final Vector<SimpleElement> ret = new Vector<SimpleElement>();
+
+ final SimpleElement parent = _em.getSimpleParent();
+ if (parent != null) {
+ parent.setPseudoCompletePath(parent.getPath() + (!parentPath.equals("") ? "/" + parentPath : ""));
+ ret.add(parent);
+ ret.addAll(this.pushParents(this.dm.getEtatById(this.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(final ElementModel parent, final String parentPath, final DataHandler _dh, final String sheetId, int _ligne, int _col, final boolean firstLine, final boolean completeLine) throws Exception {
+ final int oldCol = _col;
+ XPathFactory xpf;
+ try {
+ xpf = XPathFactory.newInstance(XPathFactory.DEFAULT_OBJECT_MODEL_URI);
+ } catch (final Throwable t) {
+ xpf = XPathFactory.newInstance();
+ }
+ final XPath xp = xpf.newXPath();
+ xp.setNamespaceContext(this.dm.getNamespaces());
+ final Node n = (Node) xp.evaluate(parentPath, _dh.getElement(), XPathConstants.NODE);
+ boolean firstCol = true;
+ for (final ChampModel cm : parent.getListeResultat().getListeChamps()) {
+ if (cm.isIdentifiant()) {
+ final DomPath dp = new DomPath(cm.getPath().getPath(), this.dm.getNamespaces());
+ final 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) {
+ this.undertaker.writeCell(sheetId, parent.getTitre(), 0, _col, true);
+ }
+ this.undertaker.writeCell(sheetId, cm.getLibelle(), 1, _col, true);
+ }
+ if (_ligne < 2) {
+ _ligne += 2;
+ }
+ final Object value = cm.getValueOf(o);
+ this.undertaker.writeCell(sheetId, value, _ligne, _col++, false);
+ firstCol = false;
+ }
+ }
+ if (completeLine) {
+ this.addLine(sheetId);
+ }
+
+ // merge des cellules
+ if (firstLine) {
+ this.undertaker.mergeCells(sheetId, oldCol, 0, _col - 1, 0);
+ }
+
+ return _col;
+ }
+
+ private Vector<Node> writeCellsOfEnfant(final Vector<Object> parentsValues, final ElementModel enfant, final Object rootElement, final String enfantPath, final String sheetId, final int _ligne/*
+ * ,
+ * int
+ * _col
+ */, boolean firstLine) throws Exception {
+ final Vector<Node> ret = new Vector<Node>();
+ XPathFactory xpf;
+ try {
+ xpf = XPathFactory.newInstance(XPathFactory.DEFAULT_OBJECT_MODEL_URI);
+ } catch (final Throwable t) {
+ xpf = XPathFactory.newInstance();
+ }
+ final XPath xp = xpf.newXPath();
+ xp.setNamespaceContext(this.dm.getNamespaces());
+ final Object xpathRet = xp.evaluate(enfantPath, rootElement, XPathConstants.NODESET);
+
+ // La configuration de l'élément concerné
+ ExportElementModel eem = null;
+ for (final ExportElementModel e : this.cf.getExportModel().getEnfants()) {
+ eem = this.getEEMFromId(e, enfant.getId());
+ if (eem != null) {
+ break;
+ }
+ }
+
+ if (firstLine) {
+ final Stack<ExportElementModel> s = new Stack<ExportElementModel>();
+ ExportElementModel tmp = eem;
+ while (true) {
+ final 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;
+ this.undertaker.writeCell(sheetId, ptmp.getLibelle(), 0, colTitre, true);
+
+ for (final ExportChampModel ecm : ptmp.getChamps()) {
+ if (ecm.isIdentifiant()) {
+ this.undertaker.writeCell(sheetId, ecm.getLibelle(), 1, colTitre++, true);
+ }
+ }
+ this.undertaker.mergeCells(sheetId, oldColTitre, 0, (colTitre - 1), 0);
+
+ }
+ }
+
+ boolean firstCol = true;
+ int maligne = _ligne;
+ int macolonne = 0;
+ int maxCol = 0;
+ if (xpathRet instanceof NodeList) {
+ final 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++) {
+ this.undertaker.writeCell(sheetId, parentsValues.get(p), maligne, col++, false);
+ }
+ macolonne = col;
+
+ final Node node = nodeListe.item(n);
+ ret.add(node);
+ for (final ExportChampModel ecm : eem.getChamps()) {
+ if (ecm.isSelectionne()) {
+ final DomPath dp = new DomPath(enfant.getListeResultat().getChamps().get(ecm.getId()).getPath().getPath(), this.dm.getNamespaces());
+ Object o = "";
+ try {
+ o = dp.getValue(node, false);
+ } catch (final 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) {
+ this.undertaker.writeCell(sheetId, enfant.getTitre(), 0, macolonne, true);
+ }
+ this.undertaker.writeCell(sheetId, ecm.getLibelle(), 1, macolonne, true);
+ }
+ try {
+ final Object computed = enfant.getListeResultat().getChamps().get(ecm.getId()).getValueOf(o);
+ this.undertaker.writeCell(sheetId, computed, maligne, macolonne++, false);
+ } catch (final Exception ex) {
+ logger.error("while exporting " + enfant.getId() + "." + ecm.getId());
+ }
+ firstCol = false;
+ }
+ }
+ this.addLine(sheetId);
+
+ maligne++;
+ maxCol = macolonne;
+ macolonne = col;
+ // merge des cellules de l'entête
+ if (firstLine) {
+ firstLine = false;
+ this.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(final DataHandler _dh, final String parentPath, final ElementModel _em) throws Exception {
+ String ret = "";
+
+ XPathFactory xpf;
+ try {
+ xpf = XPathFactory.newInstance(XPathFactory.DEFAULT_OBJECT_MODEL_URI);
+ } catch (final Throwable t) {
+ xpf = XPathFactory.newInstance();
+ }
+ final XPath xp = xpf.newXPath();
+ xp.setNamespaceContext(this.dm.getNamespaces());
+ final Node node = (Node) xp.evaluate(parentPath, _dh.getElement(), XPathConstants.NODE);
+
+ for (final ChampModel cm : _em.getListeResultat().getListeChamps()) {
+ if (cm.isIdentifiant()) {
+ final DomPath dp = new DomPath(cm.getPath().getPath(), this.dm.getNamespaces());
+ final Object o = dp.getValue(node, false);
+ if (o != null) {
+ if (ret.length() > 0) {
+ ret += "-";
+ }
+ ret += String.valueOf(o);
+ }
+ }
+ }
+
+ return ret;
+ }
+
+ private String getIdentifiant(final DataHandler _dh, final ElementModel _em) throws Exception {
+ String ret = "";
+
+ for (final ChampModel cm : _em.getListeResultat().getListeChamps()) {
+ if (cm.isIdentifiant()) {
+ final Object o = _dh.getValueAtColumn(this.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(final ExportElementModel _eem, final String id) {
+ ExportElementModel ret = null;
+ if (_eem.getId().equals(id)) {
+ ret = _eem;
+ } else {
+ for (final ExportElementModel e : _eem.getEnfants()) {
+ ret = this.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(final String id) {
+ return this.dm.getEtatById(this.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(final String id, final ElementModel em) {
+ int ret = -1;
+ int j = 0;
+
+ final Vector<String> tri = new Vector<String>();
+ final String tridefault = em.getListeResultat().getTriDefaut();
+ for (final String s : tridefault.split(",")) {
+ tri.add(s);
+ }
+
+ for (final 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(final ExportElementModel _eem) {
+ if (_eem != null) {
+ for (final 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(final ElementModel _em) {
+ if (_em.getEnfant() == null) {
+ return false;
+ } else {
+ for (final String s : _em.getEnfant().getEnfants().keySet()) {
+ final SimpleElement se = _em.getEnfant().getEnfants().get(s);
+ // La configuration de l'élément concerné
+ ExportElementModel eem = null;
+ for (final ExportElementModel e : this.cf.getExportModel().getEnfants()) {
+ eem = this.getEEMFromId(e, se.getElement());
+ if (eem != null) {
+ break;
+ }
+ }
+ if (this.shouldEEMBeExported(eem)) {
+ return true;
+ }
+ }
+ return false;
+ }
+ }
+
+ public JDialog getParentFrame() {
+ return this.parentFrame;
+ }
+
+ public void setParentFrame(final JDialog parentFrame) {
+ this.parentFrame = parentFrame;
+ }
}
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.WritableHyperlink;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
+
import org.apache.log4j.Logger;
+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;
+
/**
- * 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
+ * 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);
- }
- }
+ /**
+ * 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 final 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 final WritableFont fontEntete1 = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD, false);
+
+ public FullXlsExporter(final Exporter exporter) {
+ super(exporter);
+ this.exporter = exporter;
+ }
+
+ @Override
+ void initialize() throws Exception {
+ this.settings = new WorkbookSettings();
+ this.settings.setUseTemporaryFileDuringWrite(true);
+ this.settings.setTemporaryFileDuringWriteDirectory(new File("."));
+ this.settings.setCellValidationDisabled(true);
+ this.settings.setGCDisabled(false);
+ this.settings.setDrawingsDisabled(true);
+ this.sheetNames = new ArrayList<String>();
+ this.sheets = new Hashtable<String, ArrayList<WorkbookWrapper>>();
+
+ this.baseFile = this.exporter.fDest;
+ this.baseFileName = this.baseFile.getName();
+ this.baseFileName = StringUtilities.removeFileNameSuffix(this.baseFileName);
+
+ this.index = Workbook.createWorkbook(this.baseFile);
+ // index.set
+
+ logger.debug("JXL version=" + Workbook.getVersion());
+ }
+
+ @Override
+ void buildSheet(final ExportElementModel eem) throws Exception {
+ ArrayList<WorkbookWrapper> v = this.sheets.get(eem.getId());
+ if (v == null) {
+ v = new ArrayList<WorkbookWrapper>();
+ }
+ this.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);
+ }
+ }
+
+ final String fileName = this.baseFileName + "-" + sheetName + "-" + (v.size() + 1) + ".xls";
+ final File sheetFile = new File(this.baseFile.getAbsoluteFile().getParentFile(), fileName);
+ final WritableWorkbook sheet = Workbook.createWorkbook(sheetFile, this.settings);
+ sheet.createSheet(sheetName, 0);
+ final WorkbookWrapper ww = new WorkbookWrapper(sheet, sheetFile, eem);
+ v.add(ww);
+
+ for (final ExportElementModel e : eem.getEnfants()) {
+ this.buildSheet(e);
+ }
+ this.exporter.firstSheetId = eem.getId();
+ this.sheetNames.add(eem.getId());
+ }
+
+ @Override
+ void finish() throws Exception {
+ // logger.debug("finish()");
+ }
+
+ @Override
+ void close() {
+ for (final String sheetName : this.sheets.keySet()) {
+ final ArrayList<WorkbookWrapper> books = this.sheets.get(sheetName);
+ for (final WorkbookWrapper ww : books) {
+ try {
+ ww.purge();
+ } catch (final Throwable t) {
+ logger.error("in close() - " + ww.file.getAbsolutePath(), t);
+ }
+ }
+ }
+ // TODO: écrire dans Index
+ final WritableSheet ws = this.index.createSheet("Index", 0);
+ int elementCount = 0;
+ try {
+ final WritableCellFormat wcf = new WritableCellFormat(this.fontEntete1);
+ final CellView cvCol = new CellView();
+ cvCol.setAutosize(true);
+ for (final String key : this.sheetNames) {
+ final ArrayList<WorkbookWrapper> books = this.sheets.get(key);
+ final Label titre = new Label(elementCount, 0, books.get(0).eem.getLibelle(), wcf);
+ ws.addCell(titre);
+ int row = 1;
+ for (final WorkbookWrapper ww : books) {
+ // Label lbl = new Label(elementCount, row, ww.file.getName());
+ final 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);
+ final CellView cvRow = new CellView();
+ cvRow.setSize(18 * 20);
+ ws.setRowView(0, cvRow);
+ elementCount++;
+ }
+ } catch (final Exception ex) {
+ logger.error("writting index:", ex);
+ }
+ try {
+ this.index.write();
+ this.index.close();
+ this.index = null;
+ } catch (final Throwable t) {
+ logger.error("in close() - " + this.baseFile.getAbsolutePath(), t);
+ }
+ }
+
+ @Override
+ boolean sheetExists(final String sheetId) {
+ // logger.debug("sheetExists("+sheetId+")");
+ final ArrayList<WorkbookWrapper> v = this.sheets.get(sheetId);
+ return (v != null);
+ }
+
+ @Override
+ int getLastLineLastSheet(final String sheetId) {
+ final WorkbookWrapper ww = this.getLastWorkbookWrapper(sheetId);
+ final WritableSheet ws = ww.workbook.getSheet(0);
+ return (ws.getRows() < 2 ? 2 : ws.getRows());
+ }
+
+ @Override
+ void mergeCells(final String sheetId, final int col1, final int row1, final int col2, final int row2) {
+ // on ne fait rien !
+ }
+
+ @Override
+ void writeCell(final String sheetId, final Object o, final int line, final int col, final boolean bypassLineRenum) throws Exception {
+ int newline = 0;
+ if (bypassLineRenum) {
+ newline = line;
+ } else {
+ final int _ligne = this.exporter.getLastLine(sheetId);
+ if (_ligne >= (MAX_ROWS_PER_SHEET * this.sheets.get(sheetId).size())) {
+ this.splitSheet(sheetId);
+ }
+
+ // renumérotation de la ligne
+ newline = _ligne;
+ newline = _ligne % (MAX_ROWS_PER_SHEET) + 2;
+ }
+
+ final WorkbookWrapper ww = this.getLastWorkbookWrapper(sheetId);
+ final WritableSheet sheet = ww.workbook.getSheet(0);
+
+ if (o instanceof java.lang.Integer) {
+ final WritableCellFormat integerFormat = ww.intFormats[newline == 0 ? 0 : newline == 1 ? 1 : 2];
+ final jxl.write.Number number = new jxl.write.Number(col, newline, (Integer) o, integerFormat);
+ sheet.addCell(number);
+ } else if (o instanceof java.lang.Float) {
+ final WritableCellFormat floatFormat = ww.floatFormats[newline == 0 ? 0 : newline == 1 ? 1 : 2];
+ final jxl.write.Number number = new jxl.write.Number(col, newline, (Float) o, floatFormat);
+ sheet.addCell(number);
+ } else if (o instanceof java.util.Date) {
+ final WritableCellFormat dateFormat = ww.dateFormats[newline == 0 ? 0 : newline == 1 ? 1 : 2];
+ final jxl.write.DateTime date = new jxl.write.DateTime(col, newline, (Date) o, dateFormat);
+ sheet.addCell(date);
+ } else if (o instanceof Amount) {
+ final WritableCellFormat floatFormat = ww.floatFormats[newline == 0 ? 0 : newline == 1 ? 1 : 2];
+ final jxl.write.Number number = new jxl.write.Number(col, newline, ((Amount) o).doubleValue(), floatFormat);
+ sheet.addCell(number);
+ } else {
+ final WritableCellFormat format = ww.lblFormats[newline == 0 ? 0 : newline == 1 ? 1 : 2];
+ final jxl.write.Label label = new jxl.write.Label(col, newline, (String) o, format);
+ sheet.addCell(label);
+ }
+ }
+
+ @Override
+ void flushLine(final 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(final String sheetId) {
+ final ArrayList<WorkbookWrapper> v = this.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(final String id) throws Exception {
+ final ArrayList<WorkbookWrapper> v = this.sheets.get(id);
+ final WorkbookWrapper ww = v.get(v.size() - 1);
+
+ final WritableSheet wsRef = ww.workbook.getSheet(0);
+ final String sheetName = wsRef.getName();
+ final String fileName = this.baseFileName + "-" + sheetName + "-" + (v.size() + 1) + ".xls";
+ logger.debug("splitting sheet and produces " + fileName);
+ final File sheetFile = new File(this.baseFile.getAbsoluteFile().getParentFile(), fileName);
+ final WritableWorkbook sheet = Workbook.createWorkbook(sheetFile, this.settings);
+ sheet.createSheet(sheetName, 0);
+ final WorkbookWrapper newWw = new WorkbookWrapper(sheet, sheetFile, ww.eem);
+ v.add(newWw);
+ final WritableSheet ws = sheet.createSheet(sheetName, 0);
+ for (int i = 0; i < 2; i++) {
+ for (int j = 0; j < wsRef.getColumns(); j++) {
+ final WritableCell readCell = (WritableCell) wsRef.getCell(j, i);
+ final WritableCell newCell = readCell.copyTo(j, i);
+ final 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 (final Exception ex) {
+ logger.error("closing not-last sheet", ex);
+ }
+ return ws;
+ }
+
+ private class WorkbookWrapper {
+ private WritableWorkbook workbook;
+ private final File file;
+ private final ExportElementModel eem;
+ private WritableCellFormat[] dateFormats = null;
+ private WritableCellFormat[] intFormats = null;
+ private WritableCellFormat[] floatFormats = null;
+ private WritableCellFormat[] lblFormats = null;
+
+ public WorkbookWrapper(final WritableWorkbook workbook, final File file, final ExportElementModel eem) {
+ this.workbook = workbook;
+ this.file = file;
+ this.eem = eem;
+ this.initFormats();
+ }
+
+ public void purge() throws Exception {
+ if (this.workbook != null) {
+ final CellView cv = new CellView();
+ cv.setSize(18 * 20);
+ this.workbook.getSheet(0).setRowView(0, cv);
+ this.workbook.write();
+ this.workbook.close();
+ this.workbook = null;
+ }
+ this.dateFormats = null;
+ this.intFormats = null;
+ this.floatFormats = null;
+ this.lblFormats = null;
+ }
+
+ private void initFormats() {
+ final WritableFont fontEntete1 = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD, false);
+ final WritableFont fontEntete2 = new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD, false);
+ final WritableFont fontAutre = new WritableFont(WritableFont.ARIAL, 10);
+ this.dateFormats = new WritableCellFormat[3];
+ String dateFmt = FullXlsExporter.this.exporter.getApplicationConfiguration().getProperty(Constants.SYS_PROP_DATE_FORMAT);
+ if (dateFmt == null) {
+ dateFmt = "dd/MM/yyyy";
+ }
+ final DateFormat myDateFormat = new DateFormat(dateFmt);
+ this.dateFormats[0] = new WritableCellFormat(fontEntete1, myDateFormat);
+ this.dateFormats[1] = new WritableCellFormat(fontEntete2, myDateFormat);
+ this.dateFormats[2] = new WritableCellFormat(fontAutre, myDateFormat);
+
+ this.intFormats = new WritableCellFormat[3];
+ this.intFormats[0] = new WritableCellFormat(fontEntete1, NumberFormats.INTEGER);
+ this.intFormats[1] = new WritableCellFormat(fontEntete2, NumberFormats.INTEGER);
+ this.intFormats[2] = new WritableCellFormat(fontAutre, NumberFormats.INTEGER);
+
+ this.floatFormats = new WritableCellFormat[3];
+ this.floatFormats[0] = new WritableCellFormat(fontEntete1, NumberFormats.FLOAT);
+ this.floatFormats[1] = new WritableCellFormat(fontEntete2, NumberFormats.FLOAT);
+ this.floatFormats[2] = new WritableCellFormat(fontAutre, NumberFormats.FLOAT);
+
+ this.lblFormats = new WritableCellFormat[3];
+ this.lblFormats[0] = new WritableCellFormat(fontEntete1);
+ this.lblFormats[1] = new WritableCellFormat(fontEntete2);
+ this.lblFormats[2] = new WritableCellFormat(fontAutre);
+ }
+ }
}
*/
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.io.FileWriter;
+import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
+import java.util.Enumeration;
+import java.util.Hashtable;
+import java.util.Vector;
+
+import jxl.write.WriteException;
+
import org.apache.log4j.Logger;
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+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 fr.gouv.finances.dgfip.xemelios.utils.HtmlTableWriter;
+
/**
* 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;
- }
- }
+ 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 final Hashtable<String, Vector<HtmlSheet>> sheets = new Hashtable<String, Vector<HtmlSheet>>();
+ private final Exporter caller;
+ private String workbookPrefix = null;
+ protected SimpleDateFormat sdf;
+ DecimalFormat df = null;
+ private final PropertiesExpansion applicationProperties;
+
+ public HtmlTableExporter(final Exporter caller, final PropertiesExpansion applicationProperties) {
+ this.caller = caller;
+ this.applicationProperties = applicationProperties;
+ String dateFormat = applicationProperties.getProperty("xemelios.date.format");
+ if (dateFormat == null) {
+ dateFormat = "dd/MM/yyyy";
+ }
+ this.sdf = new SimpleDateFormat(dateFormat);
+ this.df = new DecimalFormat("0.00");
+ this.df.getDecimalFormatSymbols().setDecimalSeparator(',');
+ this.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
+ final String dirRessources = this.applicationProperties.getProperty(Constants.SYS_PROP_RESOURCES_LOCATION);
+ this.recopieFichier(dirRessources + this.getModelFileName(), this.caller.fDest.getPath(), true);
+ this.workbookPrefix = StringUtilities.removeFileNameSuffix(this.caller.fDest.getPath());
+ }
+
+ void recopieFichier(final String src, final String dst, final 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 (final Exception e) {
+ e.printStackTrace(); // n'importe quelle exception
+ } finally { // finalement on ferme
+ if (in != null) {
+ try {
+ in.close();
+ } catch (final IOException e) {
+ }
+ }
+ if (out != null) {
+ try {
+ out.close();
+ } catch (final IOException e) {
+ }
+ }
+ }
+ }
+
+ /**
+ * Obsolete
+ */
+ void addRefInMainSheet(final String libelle, final boolean addPrefix) {
+ String fileName;
+ if (addPrefix) {
+ fileName = this.workbookPrefix + "_" + libelle + ".xls";
+ } else {
+ fileName = libelle + ".xls";
+ }
+
+ final 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(final ExportElementModel eem) throws Exception {
+ logger.debug("buildSheet(" + eem + ")");
+ Vector<HtmlSheet> v = this.sheets.get(eem.getId());
+ if (v == null) {
+ v = new Vector<HtmlSheet>();
+ this.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);
+ final HtmlSheet sheet = new HtmlSheet(this.applicationProperties);
+ sheet.open(this.workbookPrefix + "_" + fileName);
+
+ this.addRefInMainSheet(this.workbookPrefix + "_" + fileName, true);
+ v.add(sheet);
+
+ for (final ExportElementModel e : eem.getEnfants()) {
+ this.buildSheet(e);
+ }
+ this.caller.firstSheetId = eem.getId();
+ }
+
+ /**
+ * Apporte des finitions
+ */
+ @Override
+ void finish() throws Exception {
+ // pour l'instant rien
+ }
+
+ /**
+ * Fermeture et nettoyage
+ */
+ @Override
+ void close() {
+ final Enumeration elems = this.sheets.keys();
+ while (elems.hasMoreElements()) {
+ final String k = (String) elems.nextElement();
+ final Vector<HtmlSheet> v = this.sheets.get(k);
+ for (final HtmlSheet s : v) {
+
+ s.close();
+ }
+
+ }
+ }
+
+ /**
+ * Verifie l'existence d'unr feuille dans le classeur
+ *
+ * @param sheetId
+ * le nom de la feuille
+ */
+ @Override
+ boolean sheetExists(final String sheetId) {
+ final Vector<HtmlSheet> v = this.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(final String sheetId) {
+ // suppose qu'on a appele sheetExists(sheetId)
+ final HtmlSheet ws = this.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(final String sheetId, final Object o, final int line, final int col, final boolean bypassLineRenum) throws Exception {
+
+ int newline = 0;
+ if (bypassLineRenum) {
+ newline = line;
+ } else {
+ final int _ligne = this.caller.getLastLine(sheetId);
+ if (_ligne >= (MAX_ROWS_PER_SHEET * this.sheets.get(sheetId).size())) {
+ this.splitSheet(sheetId);
+ }
+
+ // renumérotation de la ligne
+ newline = _ligne;
+ newline = _ligne % (MAX_ROWS_PER_SHEET) + 2;
+ }
+
+ final HtmlSheet sheet = this.getLastSheet(sheetId);
+ final String s = this.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(final String sheetId, final int col1, final int row1, final int col2, final int row2) {
+ final HtmlSheet _ws = this.getLastSheet(sheetId);
+ _ws.mergeCells(col1, row1, col2, row2);
+ }
+
+ @Override
+ void flushLine(final String sheetId) {
+ final HtmlSheet _ws = this.getLastSheet(sheetId);
+ _ws.flushLine();
+ }
+
+ // Fonctions a usage interne mises en protected on sait jamais
+ /**
+ * Formatage de l'objet a ecrire
+ */
+ protected String formatted(final Object o, final 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 = this.df.format(o);
+ styleId = HtmlTableWriter.FLOAT_CELLFORMAT;
+ } else if (o instanceof java.util.Date) {
+ rawStr = this.sdf.format(o);
+ styleId = HtmlTableWriter.DATE_CELLFORMAT;
+ } else if (o instanceof Amount) {
+ final Double d = new Double(((Amount) o).doubleValue());
+ // changement du point en virgule
+ rawStr = this.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(final 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(final String sheetId) {
+ final Vector<HtmlSheet> v = this.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(final String id) {
+ HtmlSheet ret = null;
+ final ElementModel e = this.caller.getEMFromId(id);
+ if (e.getSimpleParent() != null) {
+ final String pName = e.getSimpleParent().getElement();
+ ret = this.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(final String id) {
+ final Vector<HtmlSheet> v = this.sheets.get(id);
+ final HtmlSheet wsRef = v.get(0);
+ final HtmlSheet otherRef = this.getLastSheet(id);
+ wsRef.close();
+ final HtmlSheet ws = new HtmlSheet(this.applicationProperties);
+ final 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
+ final String sb = (nf.format(v.size()));
+ String fname = wsRef.getName() + "_" + sb;
+ if (fname.length() >= 31) {
+ fname = fname.substring(fname.length() - 30);
+ }
+ ws.open(fname);
+ this.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 final PropertiesExpansion applicationProperties;
+
+ public HtmlSheet(final PropertiesExpansion applicationProperties) {
+ this.applicationProperties = applicationProperties;
+ }
+
+ void open(final String fname) {
+ try {
+ final FileWriter out = new FileWriter(fname + ".xls");
+ this.writer = new HtmlTableWriter(out, fname, this.applicationProperties);
+ } catch (final IOException e) {
+ logger.error("HtmlSheet.open(" + fname + ")", e);
+ }
+ // Version initial tableau surdimensionnnes hum=
+ this.name = fname;
+ this.titles = new String[100];
+ this.names = new String[100];
+ this.entries = new String[100];
+ this.maxTitle = 0;
+ this.maxName = 0;
+ this.maxEntry = 0;
+ this.rowCount = 0;
+ this.titlesFlushed = false;
+ this.namesFlushed = false;
+ }
+
+ void close() {
+ if (this.writer != null) {
+ try {
+ this.writer.close();
+
+ } catch (final IOException e) {
+ logger.error("HtmlSheet.close()", e);
+ }
+ this.writer = null;
+ }
+ }
+
+ String getName() {
+ return this.name;
+ }
+
+ int getRows() {
+ return this.rowCount;
+ }
+
+ void addTitle(final String s, final int col) {
+ if (!this.titlesFlushed) {
+ if (col >= this.titles.length || this.maxTitle >= this.titles.length) {
+ // cas ou il faut redimensionner
+ final int oldlength = this.titles.length;
+ final int newlength = oldlength + oldlength / 2;
+ final String[] tm = new String[newlength];
+ for (int i = 0; i < oldlength; ++i) {
+ tm[i] = this.titles[i];
+ }
+ this.titles = tm;
+ }
+ while (this.maxTitle + 1 < col) {
+ this.maxTitle++;
+ this.titles[this.maxTitle] = HtmlTableExporter.this.formatted("", 0); // pour simuler la presentation en Excel pur
+
+ }
+ this.titles[col] = s;
+ if (col > this.maxTitle) {
+ this.maxTitle = col;
+ }
+
+ }
+ }
+
+ void addName(final String s, final int col) {
+ if (!this.namesFlushed) {
+ if (col >= this.names.length || this.maxName >= this.names.length) {
+ // cas ou il faut redimensionner
+ final int oldlength = this.names.length;
+ final int newlength = oldlength + oldlength / 2;
+ final String[] tm = new String[newlength];
+ for (int i = 0; i < oldlength; ++i) {
+ tm[i] = this.names[i];
+ }
+ this.names = tm;
+ }
+ while (this.maxName + 1 < col) {
+ this.maxName++;
+ this.names[this.maxName] = HtmlTableExporter.this.formatted("", 1);
+ }
+ this.names[col] = s;
+ if (col > this.maxName) {
+ this.maxName = col;
+ }
+
+ }
+ }
+
+ void addEntry(final String s, final int col) {
+ if (col >= this.entries.length || this.maxEntry >= this.entries.length) {
+ // cas ou il faut redimensionner
+ final int oldlength = this.entries.length;
+ final int newlength = oldlength + oldlength / 2;
+ final String[] tm = new String[newlength];
+ for (int i = 0; i < oldlength; ++i) {
+ tm[i] = this.entries[i];
+ }
+ this.entries = tm;
+ }
+ while (this.maxEntry + 1 < col) {
+ this.maxEntry++;
+ this.entries[this.maxEntry] = HtmlTableExporter.this.formatted("", 999);
+ }
+ this.entries[col] = s;
+ if (col > this.maxEntry) {
+ this.maxEntry = col;
+ }
+ }
+
+ void mergeCells(final int col1, final int row1, final int col2, final int row2) {
+ }
+
+ void flushTitles() {
+ this.writer.writeNext(this.titles, this.maxTitle);
+ this.titlesFlushed = true;
+ ++this.rowCount;
+ }
+
+ void flushNames() {
+ this.writer.writeNext(this.names, this.maxName);
+ this.namesFlushed = true;
+ ++this.rowCount;
+ }
+
+ void flushLine() {
+ if (!this.titlesFlushed) {
+ this.flushTitles();
+ }
+ if (!this.namesFlushed) {
+ this.flushNames();
+ }
+
+ this.writer.writeNext(this.entries, this.maxEntry);
+ this.maxEntry = 0;
+ ++this.rowCount;
+ }
+ }
}
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
-
package fr.gouv.finances.cp.xemelios.export;
+import java.text.DecimalFormat;
+import java.text.DecimalFormatSymbols;
+
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);
- }
+ private static DecimalFormat decF = new DecimalFormat("0.00");
+ static {
+ final DecimalFormatSymbols dfs = decF.getDecimalFormatSymbols();
+ dfs.setDecimalSeparator(',');
+ decF.setDecimalFormatSymbols(dfs);
+ decF.setGroupingUsed(false);
+ }
+
+ public HtmlTableExporterXls97SR1(final Exporter exporter, final PropertiesExpansion applicationProperties) {
+ super(exporter, applicationProperties);
+ }
+
+ @Override
+ protected String getModelFileName() {
+ return "/modeleExportXemelios-97SR1.xls";
+ }
- public HtmlTableExporterXls97SR1(Exporter exporter, PropertiesExpansion applicationProperties) {
- super(exporter, applicationProperties);
- }
+ /**
+ * Formatage de l'objet a ecrire
+ */
+ @Override
+ protected String formatted(final Object o, final Integer line) {
- @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 = this.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;
+ }
- // 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);
+ }
- // mettre en gras les titres
- if (line == 0) {
- level = 1;
- }
- if (line == 1) {
- level = 2;
- }
- return HtmlTableWriter.buildCell(rawStr, styleId, level);
- }
-
}
import java.util.Hashtable;
import java.util.Vector;
-
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.CellFormat;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
+import org.apache.log4j.Logger;
+
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
- }
+ 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 final Hashtable<String, Vector<WritableSheet>> sheets = new Hashtable<String, Vector<WritableSheet>>();
+ private final Exporter caller;
+ private WritableWorkbook workbook = null;
+
+ WritableCellFormat[] dateFormats = null;
+ WritableCellFormat[] intFormats = null;
+ WritableCellFormat[] floatFormats = null;
+ WritableCellFormat[] lblFormats = null;
+
+ public JxlExporter(final Exporter caller) {
+ this.caller = caller;
+ this.dateFormats = new WritableCellFormat[3];
+ final DateFormat myDateFormat = new DateFormat(caller.getApplicationConfiguration().getProperty(Constants.SYS_PROP_DATE_FORMAT));
+ this.dateFormats[0] = new WritableCellFormat(this.fontEntete1, myDateFormat);
+ this.dateFormats[1] = new WritableCellFormat(this.fontEntete2, myDateFormat);
+ this.dateFormats[2] = new WritableCellFormat(this.fontAutre, myDateFormat);
+
+ this.intFormats = new WritableCellFormat[3];
+ this.intFormats[0] = new WritableCellFormat(this.fontEntete1, NumberFormats.INTEGER);
+ this.intFormats[1] = new WritableCellFormat(this.fontEntete2, NumberFormats.INTEGER);
+ this.intFormats[2] = new WritableCellFormat(this.fontAutre, NumberFormats.INTEGER);
+
+ this.floatFormats = new WritableCellFormat[3];
+ this.floatFormats[0] = new WritableCellFormat(this.fontEntete1, NumberFormats.FLOAT);
+ this.floatFormats[1] = new WritableCellFormat(this.fontEntete2, NumberFormats.FLOAT);
+ this.floatFormats[2] = new WritableCellFormat(this.fontAutre, NumberFormats.FLOAT);
+
+ this.lblFormats = new WritableCellFormat[3];
+ this.lblFormats[0] = new WritableCellFormat(this.fontEntete1);
+ this.lblFormats[1] = new WritableCellFormat(this.fontEntete2);
+ this.lblFormats[2] = new WritableCellFormat(this.fontAutre);
+
+ }
+
+ // Fonctions appellees par Exporter.java
+ /**
+ * Initialisation
+ */
+ @Override
+ void initialize() throws Exception {
+
+ /**
+ * Création du workbook sur le fichier fDest
+ */
+ final WorkbookSettings ws = new WorkbookSettings();
+ ws.setUseTemporaryFileDuringWrite(true);
+ ws.setTemporaryFileDuringWriteDirectory(new File("."));
+ ws.setCellValidationDisabled(true);
+ ws.setGCDisabled(false);
+ this.workbook = Workbook.createWorkbook(this.caller.fDest, ws);
+ }
+
+ /**
+ * Crée un <tt>WritableSheet</tt> et ajoute la liste des entetes de colonne
+ *
+ * @param eem
+ * @throws Exception
+ */
+ @Override
+ void buildSheet(final ExportElementModel eem) throws Exception {
+
+ Vector<WritableSheet> v = this.sheets.get(eem.getId());
+ if (v == null) {
+ v = new Vector<WritableSheet>();
+ }
+ this.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(this.workbook.createSheet(sheetName, this.workbook.getNumberOfSheets()));
+
+ for (final ExportElementModel e : eem.getEnfants()) {
+ this.buildSheet(e);
+ }
+ this.caller.firstSheetId = eem.getId();
+ }
+
+ /**
+ * Apporte des finitions
+ */
+ @Override
+ void finish() throws Exception {
+ // recopie des entêtes dans les nouvelles feuilles créées
+ this.enteteNewSheets();
+ }
+
+ /**
+ * Fermeture et nettoyage
+ */
+ @Override
+ void close() {
+ if (this.workbook != null) {
+ try {
+ this.workbook.write();
+ this.workbook.close();
+ this.workbook = null;
+ } catch (final Throwable t) {
+ }
+ }
+ }
+
+ /**
+ * Verifie l'existence d'unr feuille dans le classeur
+ *
+ * @param sheetId
+ * le nom de la feuille
+ */
+ @Override
+ boolean sheetExists(final String sheetId) {
+ final Vector<WritableSheet> v = this.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(final String sheetId) {
+ // suppose qu'on a appele sheetExists(sheetId)
+ final WritableSheet ws = this.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(final String sheetId, final Object o, final int line, final int col, final boolean bypassLineRenum) throws Exception {
+ int newline = 0;
+ if (bypassLineRenum) {
+ newline = line;
+ } else {
+ final int _ligne = this.caller.getLastLine(sheetId);
+ if (_ligne >= (MAX_ROWS_PER_SHEET * this.sheets.get(sheetId).size())) {
+ this.splitSheet(sheetId);
+ }
+
+ // renumérotation de la ligne
+ newline = _ligne;
+ newline = _ligne % (MAX_ROWS_PER_SHEET) + 2;
+ }
+
+ final WritableSheet sheet = this.getLastSheet(sheetId);
+
+ if (o instanceof java.lang.Integer) {
+ final WritableCellFormat integerFormat = this.intFormats[newline == 0 ? 0 : newline == 1 ? 1 : 2];
+ final jxl.write.Number number = new jxl.write.Number(col, newline, (Integer) o, integerFormat);
+ sheet.addCell(number);
+ } else if (o instanceof java.lang.Float) {
+ final WritableCellFormat floatFormat = this.floatFormats[newline == 0 ? 0 : newline == 1 ? 1 : 2];
+ final jxl.write.Number number = new jxl.write.Number(col, newline, (Float) o, floatFormat);
+ sheet.addCell(number);
+ } else if (o instanceof java.util.Date) {
+ final WritableCellFormat dateFormat = this.dateFormats[newline == 0 ? 0 : newline == 1 ? 1 : 2];
+ final jxl.write.DateTime date = new jxl.write.DateTime(col, newline, (Date) o, dateFormat);
+ sheet.addCell(date);
+ } else if (o instanceof Amount) {
+ final WritableCellFormat floatFormat = this.floatFormats[newline == 0 ? 0 : newline == 1 ? 1 : 2];
+ final 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");
+ // }
+ final WritableCellFormat format = this.lblFormats[newline == 0 ? 0 : newline == 1 ? 1 : 2];
+ final 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(final String sheetId, final int col1, final int row1, final int col2, final int row2) {
+ final WritableSheet _ws = this.getLastSheet(sheetId);
+
+ try {
+ // _ws.mergeCells(col1, row1, col2, row2);
+ } catch (final 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(final String id) {
+ final String[] names = this.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(final String sheetId) {
+ final Vector<WritableSheet> v = this.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(final String id) {
+ WritableSheet ret = null;
+ final ElementModel e = this.caller.getEMFromId(id);
+ if (e.getSimpleParent() != null) {
+ final String pName = e.getSimpleParent().getElement();
+ ret = this.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(final String id) {
+ final Vector<WritableSheet> v = this.sheets.get(id);
+ final WritableSheet wsRef = v.get(0);
+
+ final WritableSheet ws = this.workbook.createSheet(wsRef.getName() + "_" + (v.size()), this.afterSheet(v.get(v.size() - 1).getName()));
+ v.add(ws);
+ return this.workbook.getSheet(this.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 (final Vector<WritableSheet> v : this.sheets.values()) {
+ if (v.size() > 1) {
+ final WritableSheet wsRef = v.get(0);
+ for (int iv = 1; iv < v.size(); iv++) {
+ final WritableSheet ws = v.get(iv);
+ for (int i = 0; i < 2; i++) {
+ for (int j = 0; j < wsRef.getColumns(); j++) {
+ final WritableCell readCell = (WritableCell) wsRef.getCell(j, i);
+ final WritableCell newCell = readCell.copyTo(j, i);
+ final CellFormat readFormat = readCell.getCellFormat();
+ if (readFormat != null) {
+ final WritableCellFormat newFormat = new WritableCellFormat(readFormat);
+ newCell.setCellFormat(newFormat);
+ }
+ ws.addCell(newCell);
+ }
+ }
+
+ }
+ }
+ }
+ }
+
+ @Override
+ void flushLine(final String el) {
+ // NOP
+ }
}
*/
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.util.ArrayList;
import java.util.Hashtable;
import java.util.Vector;
+
import org.apache.log4j.Logger;
+import fr.gouv.finances.dgfip.utils.StringUtilities;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import fr.gouv.finances.dgfip.xemelios.export.ExportElementModel;
+
/**
- *
+ *
* @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;
- }
- }
+ private static DecimalFormat df = new DecimalFormat("#0.00");
+ static {
+ final 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 final Exporter exporter;
+ private String filenamePrefix;
+
+ public SylkExporter(final Exporter exporter) {
+ super(exporter);
+ this.exporter = exporter;
+ sdf = new SimpleDateFormat(exporter.getApplicationConfiguration().getProperty(Constants.SYS_PROP_DATE_FORMAT, "yyyy-MM-dd"));
+ }
+
+ @Override
+ void buildSheet(final ExportElementModel eem) throws Exception {
+ Vector<SylkTable> tables = this.sheets.get(eem.getId());
+ if (tables == null) {
+ tables = new Vector<SylkTable>();
+ this.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);
+ }
+ }
+ final String filename = this.filenamePrefix + "_" + libelle;
+
+ final SylkTable sheet = new SylkTable(filename);
+ tables.add(sheet);
+
+ this.addRefInMainSheet(filename, false);
+
+ for (final ExportElementModel fils : eem.getEnfants()) {
+ this.buildSheet(fils);
+ }
+
+ this.exporter.firstSheetId = eem.getId();
+ }
+
+ protected void addRefInMainSheet(final String filename, final boolean addPrefix) {
+ final String ref = filename + ".slk";
+ // TODO
+ }
+
+ @Override
+ void flushLine(final String el) {
+ }
+
+ protected void splitSheet(final String sheetId) throws IOException {
+ final Vector<SylkTable> v = this.sheets.get(sheetId);
+ final SylkTable wsRef = v.get(0);
+ final SylkTable otherRef = this.getLastSheet(sheetId);
+
+ // wsRef.close();
+ final Cell[] titleLine = otherRef.getTitleLine();
+ final Cell[] headerLine = otherRef.getHeaderLine();
+
+ otherRef.flush();
+
+ final 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
+
+ final String sb = (nf.format(v.size()));
+
+ final String fname = wsRef.getFileName() + "_" + sb;
+
+ final SylkTable newSheet = new SylkTable(fname, titleLine, headerLine);
+
+ this.addRefInMainSheet(fname, false);
+
+ v.add(newSheet);
+ // return newSheet;
+ }
+
+ @Override
+ void writeCell(final String sheetId, final Object o, final int line, final int col, final boolean bypassLineRenum) throws Exception {
+ int newline = 0;
+ if (bypassLineRenum) {
+ newline = line;
+ } else {
+ final int _ligne = this.exporter.getLastLine(sheetId);
+ if (_ligne >= (MAX_ROWS_PER_SHEET * this.sheets.get(sheetId).size())) {
+ this.splitSheet(sheetId);
+ }
+
+ // renumérotation de la ligne
+ newline = _ligne;
+ newline = _ligne % (MAX_ROWS_PER_SHEET) + 2;
+ }
+
+ final SylkTable sheet = this.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(final String sheetId) {
+ final Vector<SylkTable> v = this.sheets.get(sheetId);
+ if (v != null) {
+ return v.lastElement();
+ } else {
+ return null;
+ }
+ }
+
+ @Override
+ void mergeCells(final String sheetId, final int col1, final int row1, final int col2, final int row2) {
+ logger.debug("mergeCells(" + sheetId + "," + col1 + "," + row1 + "," + col2 + "," + row2 + ")");
+ }
+
+ @Override
+ int getLastLineLastSheet(final String sheetId) {
+ final SylkTable ws = this.getLastSheet(sheetId);
+ final int ret = ws.getRows() < 2 ? 2 : ws.getRows();
+ logger.debug("getLastLineLastSheet(" + sheetId + ") -> " + ret);
+ return ret;
+ }
+
+ @Override
+ boolean sheetExists(final String sheetId) {
+ logger.debug("sheetExists(" + sheetId + ")");
+ final boolean bRet = this.sheets.containsKey(sheetId);
+ return bRet;
+ }
+
+ @Override
+ void close() {
+ logger.debug("close()");
+ }
+
+ @Override
+ void finish() throws Exception {
+ logger.debug("finish()");
+ for (final String key : this.sheets.keySet()) {
+ final Vector<SylkTable> v = this.sheets.get(key);
+ for (int i = 0; i < v.size(); i++) {
+ v.get(i).flush();
+ }
+ v.clear();
+ }
+ this.sheets.clear();
+ }
+
+ @Override
+ void initialize() throws Exception {
+ logger.debug("initialize()");
+ final String dirRessources = this.exporter.getApplicationConfiguration().getProperty(Constants.SYS_PROP_RESOURCES_LOCATION);
+ this.recopieFichier(dirRessources + "/modeleExportXemelios-97.xls", this.exporter.fDest.getPath());
+
+ this.sheets = new Hashtable<String, Vector<SylkTable>>();
+ this.filenamePrefix = StringUtilities.removeFileNameSuffix(this.exporter.fDest.getPath());
+ }
+
+ /**
+ * Copie le fichier src vers dest
+ *
+ * @param src
+ * @param dst
+ */
+ private void recopieFichier(final String src, final 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 (final Exception e) {
+ e.printStackTrace(); // n'importe quelle exception
+ } finally { // finalement on ferme
+ if (in != null) {
+ try {
+ in.close();
+ } catch (final IOException e) {
+ }
+ }
+ if (out != null) {
+ try {
+ out.close();
+ } catch (final 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 final String filename;
+ private final ArrayList<Cell[]> rowArray;
+ private boolean written = false;
+
+ public SylkTable(final String filename) {
+ super();
+ this.filename = filename;
+ this.rowArray = new ArrayList<Cell[]>();
+ }
+
+ public SylkTable(final String filename, final Cell[] titleLine, final Cell[] headerLine) {
+ this(filename);
+ this.rowArray.add(titleLine);
+ this.rowArray.add(headerLine);
+ }
+
+ public void addTitle(final int col, final int row, final Object data) {
+ this.ensureCapacity(row);
+ final Cell[] line = this.rowArray.get(row);
+ line[col] = new Cell(data);
+ line[col].setStyle(Cell.CELL_FMT_TITLE);
+ }
+
+ public void addHeader(final int col, final int row, final Object data) {
+ this.ensureCapacity(row);
+ final Cell[] line = this.rowArray.get(row);
+ line[col] = new Cell(data);
+ line[col].setStyle(Cell.CELL_FMT_HEADER);
+ }
+
+ public void addValue(final int col, final int row, final Object data) {
+ this.ensureCapacity(row);
+ final Cell[] line = this.rowArray.get(row);
+ line[col] = new Cell(data);
+ }
+
+ public String getFileName() {
+ return this.filename;
+ }
+
+ public int getRows() {
+ return this.rowArray.size();
+ }
+
+ private void ensureCapacity(final int row) {
+ while (this.rowArray.size() < (row + 1)) {
+ this.rowArray.add(new Cell[256]);
+ }
+ }
+
+ private void writeTable(final Writer w) throws IOException {
+ if (this.written) {
+ return;
+ }
+ w.write(SYLK_HEADER);
+ for (int y = 0; y < this.rowArray.size(); y++) {
+ final Cell[] line = this.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");
+ this.written = true;
+ }
+
+ public void flush() throws IOException {
+ if (this.rowArray.isEmpty()) {
+ return;
+ }
+ logger.debug("writting " + this.getFileName() + ".slk");
+ final File f = new File(this.getFileName() + ".slk");
+ final FileWriter fw = new FileWriter(f);
+ this.writeTable(fw);
+ fw.flush();
+ fw.close();
+ // empty the data
+ this.clear();
+ }
+
+ private void clear() {
+ for (final Cell[] line : this.rowArray) {
+ for (int i = 0; i < line.length; i++) {
+ line[i] = null;
+ }
+ }
+ this.rowArray.clear();
+ }
+
+ public Cell[] getTitleLine() {
+ return this.rowArray.get(0);
+ }
+
+ public Cell[] getHeaderLine() {
+ return this.rowArray.get(1);
+ }
+ }
+
+ private class Cell {
+ public static final int CELL_VALUE = 0;
+ public static final int CELL_FMT_TITLE = 1;
+ public static final int CELL_FMT_HEADER = 2;
+ public static final int ALIGN_RIGHT = 1;
+ public static final int ALIGN_CENTER = 2;
+ public static final int ALIGN_LEFT = 3;
+ private final int datatype;
+ private int format;
+ private int style;
+ private final Object value;
+
+ public Cell(final Object o) {
+ super();
+ this.value = o;
+ this.datatype = CELL_VALUE;
+ if (o instanceof Number) {
+ this.format = ALIGN_RIGHT;
+ } else if (this.value instanceof java.util.Date) {
+ this.format = ALIGN_CENTER;
+ } else {
+ this.format = ALIGN_LEFT;
+ }
+ }
+
+ public void setStyle(final int style) {
+ this.style = style;
+ }
+
+ public String getSylkRepresentation(final int i, final int j) {
+ final StringBuilder sb = new StringBuilder();
+ if (this.value != null) {
+ if (this.datatype == CELL_VALUE) {
+ sb.append("C;Y").append(i + 1).append(";X").append(j + 1).append(";K").append(this.getFormattedValue()).append("\n");
+ } else {
+ sb.append("C;Y").append(i + 1).append(";X").append(j + 1).append(";E").append(this.getFormattedValue()).append("\n");
+ }
+
+ sb.append("F;P0;Y").append(i + 1).append(";X").append(j + 1);
+ if (this.format == ALIGN_RIGHT) {
+ sb.append(";FG0R");
+ } else if (this.format == ALIGN_CENTER) {
+ sb.append(";FG0C");
+ } else if (this.format == ALIGN_LEFT) {
+ sb.append(";FG0L");
+ }
+
+ if (this.style == CELL_FMT_TITLE) {
+ sb.append(";SLM0"); // sb.append(";SDLTM15");
+ } else if (this.style == CELL_FMT_HEADER) {
+ sb.append(";SDLM10");
+ } else {
+ sb.append(";SLM0");
+ }
+
+ sb.append("\n");
+ }
+ return sb.toString();
+ }
+
+ public String getFormattedValue() {
+ String ret = "";
+ if (this.value instanceof Integer || this.value instanceof Long || this.value instanceof Short) {
+ ret = this.value.toString();
+ } else if (this.value instanceof Number) {
+ // ret = "\""+df.format(value)+"\"";
+ ret = df.format(this.value);
+ } else if (this.value instanceof java.util.Date) {
+ ret = "\"" + sdf.format((java.util.Date) this.value) + "\"";
+ } else {
+ ret = "\"" + ((String) this.value).replaceAll(";", ";;") + "\"";
+ }
+ return ret;
+ }
+ }
}
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
+import javax.swing.WindowConstants;
import org.apache.log4j.Logger;
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.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.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.importers.ImportServiceProvider;
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;
- }
-
- @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 synchronized void run() {
- 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();
- 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();
- }
-
- protected void initComponents() {
- 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;
- }
+ 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(final MainWindow owner, final EtatImporteur ei, final int nbfiles) {
+ super();
+ this.owner = owner;
+ // this.pg=new ProgressDlg(owner,nbfiles,ei);
+ this.ei = ei;
+ }
+
+ @Override
+ public Pair getBudget(final DocumentModel dm, final Pair collectivite, final String fileName, final Pair budget) throws ToolException {
+ Pair ret = null;
+ if (ret == null) {
+ final TreeSet<Pair> existing = new TreeSet<Pair>();
+ try {
+ existing.addAll(DataLayerManager.getImplementation().getBudgets(dm, collectivite, this.owner.getConnectedUser()));
+ } catch (final UnauthorizedException ex) {
+ throw new ToolException(ex, ToolException.ERROR_UNAUTHORIZED);
+ } catch (final DataConfigurationException e) {
+ // logger.error("in getBudget", e);
+ } catch (final DataAccessException e) {
+ // logger.error("in getBudget", e);
+ }
+ final Vector<Pair> budgetsDm = dm.getDefaultBudgets();
+ existing.addAll(budgetsDm);
+ final QueryBudget qb = new QueryBudget(fileName, existing, collectivite.libelle, budget);
+ if (SwingUtilities.isEventDispatchThread()) {
+ qb.run();
+ } else {
+ try {
+ SwingUtilities.invokeAndWait(qb);
+ } catch (final Throwable t) {
+ }
+ }
+ ret = qb.getRet();
+ if (ret == null) {
+ throw new ToolException("Action interrompue", ToolException.ERROR_INTERRUPTED);
+ }
+ }
+ return ret;
+ }
+
+ @Override
+ public Pair getCollectivite(final DocumentModel dm, final String fileName, final Pair collectivite) throws ToolException {
+ Pair ret = null;
+ if (ret == null) {
+ final QueryCollectivite qc = new QueryCollectivite(dm, fileName, collectivite);
+ if (SwingUtilities.isEventDispatchThread()) {
+ qc.run();
+ } else {
+ try {
+ SwingUtilities.invokeAndWait(qc);
+ } catch (final Throwable t) {
+ }
+ }
+ ret = qc.getRet();
+ if (ret == null) {
+ throw new ToolException("Import interrompu", ToolException.ERROR_INTERRUPTED);
+ }
+ }
+ return ret;
+ }
+
+ @Override
+ public boolean getOverwrite(final String docName) throws Exception {
+ if (this.alwaysOverwrite) {
+ return true;
+ }
+ if (this.lastReponse == 0 || this.lastReponse == 1) {
+ return (this.lastReponse == 0);
+ }
+ final QueryOverwrite qo = new QueryOverwrite(docName);
+ int ret = -2;
+ if (SwingUtilities.isEventDispatchThread()) {
+ qo.run();
+ } else {
+ try {
+ SwingUtilities.invokeAndWait(qo);
+ } catch (final Throwable t) {
+ }
+ }
+ ret = qo.getRet();
+ if (ret == JOptionPane.CLOSED_OPTION || ret == 2) {
+ throw new Exception("Annuler");
+ }
+ this.lastReponse = ret;
+ return ret == 0;
+ }
+
+ @Override
+ public void setEtatImporter(final EtatImporteur ei) {
+ this.ei = ei;
+ }
+
+ @Override
+ public Pair getCollectivite() {
+ return this.ei.getCollectivite();
+ }
+
+ @Override
+ public Pair getBudget() {
+ return this.ei.getBudget();
+ }
+
+ public void terminate() {
+ this.pg.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
+ this.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(final int orient) {
+ super(orient);
+ }
+
+ public PaintableProgress(final int min, final int max) {
+ super(min, max);
+ }
+
+ public PaintableProgress(final int orient, final int min, final int max) {
+ super(orient, min, max);
+ }
+
+ public PaintableProgress(final BoundedRangeModel newModel) {
+ super(newModel);
+ }
+
+ @Override
+ public void paintImmediatly() {
+ final Runnable code = new Runnable() {
+
+ @Override
+ public void run() {
+ PaintableProgress.this.paintImmediately(0, 0, PaintableProgress.this.getWidth(), PaintableProgress.this.getHeight());
+ }
+ };
+ if (SwingUtilities.isEventDispatchThread()) {
+ code.run();
+ } else {
+ try {
+ SwingUtilities.invokeAndWait(code);
+ } catch (final Exception ex) {
+ logger.error("tu sais ou", ex);
+ }
+ }
+ }
+ }
+
+ @Override
+ public void displayProgress(final int nbFiles) {
+ final Runnable code = new Runnable() {
+
+ @Override
+ public synchronized void run() {
+ if (ImportServiceSwingProvider.this.pg == null) {
+ ImportServiceSwingProvider.this.pg = new ProgressDlg(ImportServiceSwingProvider.this.owner, nbFiles, ImportServiceSwingProvider.this.ei);
+ }
+ if (ImportServiceSwingProvider.this.ei != null) {
+ ImportServiceSwingProvider.this.ei.addPropertyChangeListener(new PropertyChangeListener() {
+ @Override
+ public void propertyChange(final PropertyChangeEvent evt) {
+ final String propName = evt.getPropertyName();
+ if ("FILE_NAME".equals(propName)) {
+ ImportServiceSwingProvider.this.pg.setCurrentFile((String) evt.getNewValue());
+ } else if ("progress".equals(propName)) {
+ final Integer progress = (Integer) evt.getNewValue();
+ ImportServiceSwingProvider.this.pg.pushCurrentProgress(progress.intValue());
+ } else if ("terminated".equals(propName)) {
+ ImportServiceSwingProvider.this.terminate();
+ }
+ }
+ });
+ }
+ ImportServiceSwingProvider.this.pg.setVisible(true);
+ }
+ };
+ if (SwingUtilities.isEventDispatchThread()) {
+ code.run();
+ } else {
+ try {
+ SwingUtilities.invokeAndWait(code);
+ } catch (final Throwable t) {
+ }
+ }
+ }
+
+ @Override
+ public void pushCurrentProgress(final int progress) {
+ this.pg.pushCurrentProgress(progress);
+ }
+
+ @Override
+ public void displayMessage(final String msg, final int msgType) {
+ if (this.shouldDisplayFeedback()) {
+ JOptionPane.showMessageDialog(this.owner, msg, "Import", msgType == ImportServiceProvider.MSG_TYPE_INFORMATION ? JOptionPane.INFORMATION_MESSAGE : JOptionPane.ERROR_MESSAGE);
+ }
+ }
+
+ @Override
+ public void displayException(final Throwable t) {
+ new DisplayExceptionDlg(this.owner, t);
+ }
+
+ @Override
+ public void startLongWait() {
+ this.pg.setUnknownEndded(true);
+ }
+
+ @Override
+ public void endLongWait() {
+ this.pg.setUnknownEndded(false);
+ }
+
+ private class QueryCollectivite implements Runnable {
+
+ private Pair ret;
+ private final String fileName;
+ private final DocumentModel dm;
+ Pair collectivite;
+
+ public QueryCollectivite(final DocumentModel dm, final String fileName, final Pair collectivite) {
+ super();
+ this.fileName = fileName;
+ this.dm = dm;
+ this.collectivite = collectivite;
+ }
+
+ @Override
+ public void run() {
+ final DlgGetPair dlg = new DlgGetPair(ImportServiceSwingProvider.this.owner, "Sur quel(le) " + this.dm.getLibelleCollectivite() + " porte ce document :\n" + this.fileName + " ?", null, null, this.collectivite);
+
+ if (dlg.run()) {
+ this.ret = new Pair(dlg.getCode(), dlg.getLibelle());
+ }
+ }
+
+ public Pair getRet() {
+ return this.ret;
+ }
+ }
+
+ private class QueryBudget implements Runnable {
+
+ private final String fileName;
+ private final TreeSet<Pair> existing;
+ private Pair ret;
+ private String collectivite = null;
+ private final Pair budget;
+
+ public QueryBudget(final String fileName, final TreeSet<Pair> existing, final String collectivite, final 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(ImportServiceSwingProvider.this.owner, "Sur quel budget porte ce document :\n" + this.fileName + " ?", this.existing, this.collectivite, this.budget);
+
+ if (dlg.run()) {
+ this.ret = new Pair(dlg.getCode(), dlg.getLibelle());
+ }
+ logger.debug("fin de QueryBudget.run()");
+ }
+
+ public Pair getRet() {
+ logger.debug("QueryBudget.getRet()");
+ return this.ret;
+ }
+ }
+
+ private class QueryOverwrite implements Runnable {
+
+ private final String fileName;
+ private int ret = -2;
+
+ public QueryOverwrite(final String fileName) {
+ super();
+ this.fileName = fileName;
+ }
+
+ @Override
+ public void run() {
+ final String msg = "Ce document existe déjà : " + this.fileName + "; voulez-vous l'écraser ?";
+ final String[] options = { "Oui", "Non", "Annuler" };
+ this.ret = JOptionPane.showOptionDialog(ImportServiceSwingProvider.this.owner, msg, "Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
+ }
+
+ public int getRet() {
+ return this.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 final boolean shouldContinue = true;
+ private EtatImporteur ei = null;
+ private final int nbFilesToImport;
+ private int nbFilesImported = -1;
+ PaintableProgress globalProgress, currentProgress;
+ JTextField currentFileName;
+
+ public ProgressDlg(final JFrame owner, final int nbFilesToImport, final EtatImporteur ei) {
+ super(owner, "Import en cours...");
+ this.nbFilesToImport = nbFilesToImport;
+ this.ei = ei;
+ this.initComponents();
+ }
+
+ protected void initComponents() {
+ final 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");
+ }
+ final CellConstraints cc = new CellConstraints();
+ final PanelBuilder pb = new PanelBuilder(fl);
+
+ pb.add(iF.newLabel("Import global", "normal"), cc.xy(2, 2));
+ this.globalProgress = new PaintableProgress(0, 100);
+ this.globalProgress.setStringPainted(true);
+ this.globalProgress.setMaximum(1000);
+ pb.add(this.globalProgress, cc.xy(2, 4));
+
+ this.currentFileName = new JTextField(30);
+ this.currentFileName.setBackground(this.getBackground());
+ this.currentFileName.setBorder(BorderFactory.createEmptyBorder());
+ this.currentFileName.setEditable(false);
+ this.currentFileName.setText(DEFAULT_TEXT);
+ pb.add(this.currentFileName, cc.xy(2, 6));
+ this.currentProgress = new PaintableProgress(0, 100);
+ this.currentProgress.setStringPainted(true);
+ pb.add(this.currentProgress, cc.xy(2, 8));
+ if (SHOW_CANCEL_BUTTON) {
+ final JButton pbCancel = new JButton("Annuler");
+ pbCancel.addActionListener(new ActionListener() {
+
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ ProgressDlg.this.ei.cancel(true);
+ }
+ });
+ pb.add(pbCancel, cc.xy(2, 10));
+ if (this.ei == null) {
+ pbCancel.setEnabled(false);
+ }
+ }
+
+ this.setContentPane(pb.getPanel());
+ this.setResizable(false);
+ this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
+ this.pack();
+ this.setLocationRelativeTo(this.getOwner());
+ this.setVisible(true);
+ final Graphics g = this.getGraphics();
+ g.setClip(0, 0, this.getWidth(), this.getHeight());
+ this.paint(g);
+ this.setGlassPane(new InfiniteGlassPane());
+ }
+
+ public boolean setCurrentFile(final String fileName) {
+ this.nbFilesImported++;
+ logger.debug("Text import : " + DEFAULT_TEXT + fileName + " (" + (1 + this.nbFilesImported) + "/" + this.nbFilesToImport + ")");
+ this.currentFileName.setText(DEFAULT_TEXT + fileName + " (" + (1 + this.nbFilesImported) + "/" + this.nbFilesToImport + ")");
+ this.currentProgress.setMaximum(100);
+ this.currentProgress.setValue(0);
+ return this.shouldContinue;
+ }
+
+ public boolean pushCurrentProgress(final int value) {
+ // logger.debug("CurrentProgress: "+value);
+ this.currentProgress.setValue(value);
+ // logger.debug(nbFilesToImport+" fichiers à importer.\n"+nbFilesImported+" fichiers importés.");
+ final int progress = (int) (((this.nbFilesImported + this.currentProgress.getPercentComplete()) / this.nbFilesToImport) * 1000);
+ // logger.debug("GetMaximum="+globalProgress.getMaximum()+" | GlobalProgress: "+progress);
+ this.globalProgress.setValue(progress);
+ // paintComponents(g);
+ // paintAll(g);
+ this.repaintImmediatly();
+ return this.shouldContinue;
+ }
+
+ public void repaintImmediatly() {
+ // logger.debug("repaintImmediatly");
+ this.currentProgress.paintImmediatly();
+ this.globalProgress.paintImmediatly();
+ final Graphics g = this.getGraphics();
+ g.setClip(0, 0, this.getWidth(), this.getHeight());
+ if (this.isLightweight()) {
+ this.paint(g);
+ } else {
+ this.update(g);
+ }
+ }
+
+ public void setUnknownEndded(final boolean start) {
+ this.getGlassPane().setVisible(start);
+ }
+ }
+
+ @Override
+ public void setDisplayFeedback(final boolean display) {
+ this.displayFeedback = display;
+ }
+
+ @Override
+ public boolean shouldDisplayFeedback() {
+ return this.displayFeedback;
+ }
+
+ @Override
+ public void setCollectivite(final Pair p) {
+ this.ei.setCollectivite(p);
+ }
+
+ @Override
+ public void setBudget(final Pair p) {
+ this.ei.setBudget(p);
+ }
+
+ @Override
+ public void setAlwaysOverwrite(final boolean b) {
+ this.alwaysOverwrite = b;
+ }
}
*/
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;
+import fr.gouv.finances.dgfip.xemelios.common.config.NamespaceModel;
+
/**
- *
+ *
* @author chm
*/
public class NamespaceHolder {
- private Hashtable<String, String> prefixToUri = null;
- private Hashtable<String, ArrayList<String>> uriToPrefix = null;
+ 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 NamespaceHolder() {
+ super();
+ this.prefixToUri = new Hashtable<String, String>();
+ this.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 addMapping(final String prefix, final String uri) {
+ this.prefixToUri.put(prefix, uri);
+ ArrayList<String> prefixes = this.uriToPrefix.get(uri);
+ if (prefixes == null) {
+ prefixes = new ArrayList<String>();
+ this.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 void removeMapping(final String prefix) {
+ final String uri = this.prefixToUri.remove(prefix);
+ if (uri == null) {
+ return;
+ }
+ final ArrayList<String> prefixes = this.uriToPrefix.get(uri);
+ if (prefixes != null) {
+ prefixes.remove(prefix);
+ }
+ }
- public String getNamespaceURI(String prefix) {
- String ret = prefixToUri.get(prefix);
- return ret;
- }
+ public String getNamespaceURI(final String prefix) {
+ final String ret = this.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 String getPrefix(final 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;
+ }
+ final ArrayList<String> prefixes = this.uriToPrefix.get(namespaceURI);
+ if (prefixes != null) {
+ ret = prefixes.get(0);
+ for (final 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 Iterator getPrefixes(final String namespaceURI) {
+ if (namespaceURI == null) {
+ throw new IllegalArgumentException("namespaceURI must not be null");
+ }
+ final ArrayList<String> prefixes = this.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();
- }
+ public Set<String> getAllPrefixes() {
+ return this.prefixToUri.keySet();
+ }
}
*/
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.FileOutputStream;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
+import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;
import org.apache.log4j.Logger;
+import fr.gouv.finances.cp.utils.StartUrl;
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
+ * 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
+ private static Logger logger = Logger.getLogger(ExportPluginRunner.class);
+
+ private Throwable exceptionDuringProcess = null;
+ private String fileName = null;
+ private final XemeliosUser user;
+ private ExportPlugin plugin;
+
+ public ExportPluginRunner(final 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
+ Long nbExport = new Long(0);
+ try {
+ nbExport = this.plugin.doExport();
+ } catch (final Throwable t) {
+ logger.error("in doExport:", t);
+ this.exceptionDuringProcess = t;
+ }
+ return nbExport;
+ }
+
+ @Override
+ public int getPluginType() {
+ return XemeliosPlugin.TYPE_EXPORT;
+ }
+
+ public ExportPlugin getPlugin() {
+ return this.plugin;
+ }
+
+ public void setPlugin(final ExportPlugin plugin) {
+ this.plugin = plugin;
+ }
+
+ public StringBuffer getBuffer() throws Exception {
+ return (StringBuffer) this.get();
+ }
+
+ @Override
+ public void done() {
+ super.done();
+ this.terminate();
+ }
+
+ public void terminate() {
+ try {
+ if (this.plugin.getOutputStream() != null) {
+ this.plugin.getOutputStream().flush();
+ this.plugin.getOutputStream().close();
+ }
+ } catch (final IOException ioEx) {
+ logger.error("closing outputstream", ioEx);
+ }
+ this.setProgressVisible(false);
+ if (this.exceptionDuringProcess != null) {
+ new DisplayExceptionDlg(SwingUtilities.getWindowAncestor(this.getSearchWindow()), this.exceptionDuringProcess);
+ } else {
+ try {
+ StartUrl.startUrl(this.fileName);
+ } catch (final Exception ex) {
+ }
+ // new File(fileName).toURI().toURL().toExternalForm()
+ }
+ this.getSearchWindow().setSearchEnabled(true);
+ try {
+ logger.debug("finished: " + this.get().toString());
+ } catch (final Throwable t) {
+ logger.fatal("interrupted");
+ }
+ }
+
+ public void startExport() throws Exception {
+ // plugin.setUser(user);
+ this.plugin.setProgressListener(this);
+ this.plugin.computeParameters();
+ File f = this.getFileToExportTo(this.plugin.getDefaultFileExtension());
+
+ if (f != null) {
+ this.fileName = f.toURL().toExternalForm();
+ if (f.getName().indexOf(".") < 0) {
+ f = new File(f.getParent(), f.getName() + "." + this.plugin.getDefaultFileExtension());
+ this.fileName = f.toURL().toExternalForm();
+ }
+ this.plugin.setOutputStream(new FileOutputStream(f));
+ this.execute();
+ } else {
+ this.setProgressVisible(false);
+ this.getSearchWindow().setSearchEnabled(true);
+ this.getSearchWindow().setCursor(Cursor.getDefaultCursor());
+ this.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(final String defaultExtension) throws IOException {
+ File ret = null;
+ FileFilter ff = null;
+ // ff = getFileFilter();
+ if (ff == null) {
+ ff = new MyFileFilter(defaultExtension);
+ }
+ final JFileChooser fc = new JFileChooser();
+ // if(defaultExtension!=null) {
+ fc.addChoosableFileFilter(ff);
+ // }
+ if (fc.showSaveDialog(MainWindow.getInstance()) == JFileChooser.APPROVE_OPTION) {
+ ret = fc.getSelectedFile();
+ if (ret.exists()) {
+ final 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 = this.getFileToExportTo(defaultExtension);
+ break;
+ }
+ case JOptionPane.YES_OPTION: {
+ ret.delete();
+ }
+ }
+ }
+ }
+ return ret;
+ }
+
+ protected String getFileName() {
+ return this.fileName;
+ }
+
+ public static class MyFileFilter extends FileFilter {
+ private String ext;
+
+ public MyFileFilter(final String extension) {
+ super();
+ if (extension != null) {
+ if (extension.startsWith(".")) {
+ this.ext = extension;
+ } else {
+ this.ext = "." + extension;
+ }
+ } else {
+ this.ext = " ";
+ }
+ }
+
+ @Override
+ public boolean accept(final File f) {
+ return f.getName().endsWith(this.ext);
+ }
+
+ @Override
public String getDescription() {
- return "Fichiers "+ext.substring(1);
- }
- }
- public XemeliosUser getUser() { return user; }
+ return "Fichiers " + this.ext.substring(1);
+ }
+ }
+
+ public XemeliosUser getUser() {
+ return this.user;
+ }
}
*/
package fr.gouv.finances.cp.xemelios.plugins;
+import javax.swing.SwingUtilities;
+
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
+ * 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;
+ private ListeResultatModel lrm;
+ private final XemeliosUser user;
+ private SearchPlugin plugin;
+
+ public SearchPluginRunner(final XemeliosUser user) {
+ super();
+ this.user = user;
+ }
+
+ public void setPlugin(final SearchPlugin plugin) {
+ this.plugin = plugin;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jdesktop.swingworker.SwingWorker#doInBackground()
+ */
+ @Override
+ public DataResultSet doInBackground() throws Exception {
+ this.plugin.setParameters(this.getParameters());
+ this.plugin.setElementModel(this.getElementModel());
+ this.plugin.setListeResultatModel(this.lrm);
+ return this.plugin.getResultSet();
+ }
- 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 {
+ this.execute();
+ }
+ @Override
+ public int getPluginType() {
+ return XemeliosPlugin.TYPE_SEARCH;
+ }
- public void startSearch() throws Exception {
- execute();
- }
+ public DataResultSet getResultSet() throws Exception {
+ return (DataResultSet) this.get();
+ }
- @Override
- public int getPluginType() {
- return XemeliosPlugin.TYPE_SEARCH;
- }
+ public void setListeResultat(final ListeResultatModel lrm) {
+ this.lrm = lrm;
+ }
- public DataResultSet getResultSet() throws Exception {
- return (DataResultSet) get();
- }
-
- public void setListeResultat(ListeResultatModel lrm) { this.lrm = lrm; }
- public ListeResultatModel getListeResultat() { return lrm; }
+ public ListeResultatModel getListeResultat() {
+ return this.lrm;
+ }
-
- public XemeliosUser getUser() { return user; }
+ public XemeliosUser getUser() {
+ return this.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();
- }
- }
+ @Override
+ public void done() {
+ try {
+ final DataResultSet rs = (DataResultSet) this.get();
+ final Runnable code = new ResultDisplayerThread(rs, this.getListeResultat(), this.getStart(), this.getElementModel(), this.getSearchWindow());
+ if (SwingUtilities.isEventDispatchThread()) {
+ code.run();
+ } else {
+ try {
+ SwingUtilities.invokeAndWait(code);
+ } catch (final Throwable t) {
+ }
+ }
+ this.firePropertyChange("COMPLETED", Boolean.FALSE, Boolean.TRUE);
+ } catch (final Throwable t) {
+ DisplayExceptionDlg.displayException(SwingUtilities.getWindowAncestor(this.getSearchWindow()), t);
+ } finally {
+ this.setProgressVisible(false);
+ super.done();
+ }
+ }
}
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
+import javax.swing.WindowConstants;
import org.apache.log4j.Logger;
import org.jdesktop.swingworker.SwingWorker;
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.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.utils.Pair;
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
+ * 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.");
- }
- }
+ 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;
+
+ 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(final ElementModel em) {
+ this.elementModel = em;
+ this.etatModel = this.elementModel.getParent();
+ this.documentModel = this.etatModel.getParent();
+ }
+
+ protected final ElementModel getElementModel() {
+ return this.elementModel;
+ }
+
+ protected final EtatModel getEtatModel() {
+ return this.etatModel;
+ }
+
+ protected final DocumentModel getDocumentModel() {
+ return this.documentModel;
+ }
+
+ public void setParameters(final Hashtable<String, String> params) {
+ this.params = params;
+ }
+
+ protected final Hashtable<String, String> getParameters() {
+ return this.params;
+ }
+
+ public void setModel(final PluginModel pm) {
+ this.pm = pm;
+ }
+
+ public void setStart(final long start) {
+ this.start = start;
+ }
+
+ public long getStart() {
+ return this.start;
+ }
+
+ protected final PluginModel getPluginModel() {
+ return this.pm;
+ }
+
+ public void setCollectivite(final Pair collectivite) {
+ this.collectivite = collectivite;
+ }
+
+ public void setBudget(final Pair budget) {
+ this.budget = budget;
+ }
+
+ public Pair getBudget() {
+ return this.budget;
+ }
+
+ public Pair getCollectivite() {
+ return this.collectivite;
+ }
+
+ @Override
+ public void setProgressInfos(final int maxProgress, final String progressMessage) {
+ this.maxProgress = maxProgress;
+ this.progressMessage = progressMessage;
+ }
+
+ @Override
+ public void pushProgress() {
+ if (this.progress != null) {
+ this.progress.pushProgress();
+ }
+ }
+
+ @Override
+ public void setProgressVisible(final boolean show) {
+ if (show) {
+ this.progress = new ProgressDlg(MainWindow.getInstance(), this.maxProgress, this.progressMessage);
+ this.progress.setVisible(true);
+ } else if (this.progress != null) {
+ this.progress.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
+ this.progress.setVisible(false);
+ }
+ }
+
+ @Override
+ public void done() {
+ this.sw.stopWaiter();
+ }
+
+ public void setSearchWindow(final PnlSearch sw) {
+ this.sw = sw;
+ }
+
+ public PnlSearch getSearchWindow() {
+ return this.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 final int maxProgress;
+ private int value = 0;
+ private final String progressMessage;
+
+ public ProgressDlg(final JFrame owner, final int maxProgress, final String progressMessage) {
+ super(owner, DEFAULT_TEXT);
+ this.maxProgress = maxProgress;
+ this.progressMessage = progressMessage;
+ this.initComponents();
+ }
+
+ protected void initComponents() {
+ final IhmFactory iF = IhmFactory.newInstance();
+ FormLayout fl = null;
+ fl = new FormLayout("3dlu,pref,3dlu", "3dlu,pref,1dlu,pref,3dlu");
+ final CellConstraints cc = new CellConstraints();
+ final PanelBuilder pb = new PanelBuilder(fl);
+
+ pb.add(iF.newLabel(this.progressMessage, "normal"), cc.xy(2, 2));
+ this.globalProgress = new PaintableProgress(0, 100);
+ this.globalProgress.setStringPainted(true);
+ this.globalProgress.setMaximum(this.maxProgress);
+ pb.add(this.globalProgress, cc.xy(2, 4));
+
+ this.setContentPane(pb.getPanel());
+ this.setResizable(false);
+ this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
+ this.pack();
+ this.setLocationRelativeTo(this.getOwner());
+ this.setVisible(true);
+ final Graphics g = this.getGraphics();
+ g.setClip(0, 0, this.getWidth(), this.getHeight());
+ this.paint(g);
+ }
+
+ public void repaintImmediatly() {
+ final Runnable code = new Runnable() {
+
+ @Override
+ public void run() {
+ ProgressDlg.this.globalProgress.paintImmediatly();
+ final Graphics g = ProgressDlg.this.getGraphics();
+ g.setClip(0, 0, ProgressDlg.this.getWidth(), ProgressDlg.this.getHeight());
+ if (ProgressDlg.this.isLightweight()) {
+ ProgressDlg.this.paint(g);
+ } else {
+ ProgressDlg.this.update(g);
+ }
+ }
+ };
+ if (SwingUtilities.isEventDispatchThread()) {
+ code.run();
+ } else {
+ try {
+ SwingUtilities.invokeAndWait(code);
+ } catch (final Throwable t) {
+ logger.error("repaintImmediatly", t);
+ }
+ }
+ }
+
+ @Override
+ public void pushProgress() {
+ this.value++;
+ // logger.debug("progress: "+value);
+ this.globalProgress.setValue(this.value);
+ this.repaintImmediatly();
+ // repaint();
+ }
+
+ @Override
+ public void setProgressInfos(final int maxProgress, final String progressMessage) {
+ // throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public void setProgressVisible(final boolean show) {
+ // throw new UnsupportedOperationException("Not supported yet.");
+ }
+ }
}
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.BufferedInputStream;
+import java.io.File;
import java.util.StringTokenizer;
import java.util.Vector;
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;
+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;
+
/**
* A propos de l'appli
+ *
* @author chm
*/
public class AboutBox extends JDialog {
static {
- if(System.getProperty("os.name").toLowerCase().indexOf("win")>=0)
+ 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(final Frame owner) {
+ super(owner, "A propos... de " + Constants.NOM_APP);
+ this.initialize();
+ }
+
+ private void initialize() {
+ this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
+ final JLayeredPane layer = new JLayeredPane();
+ // IhmFactory iF = IhmFactory.newInstance();
+ final ImageIcon image = IhmFactory.getIconFromResource(ImageResources.ABOUT);
+ final BufferedImage bi = new BufferedImage(image.getIconWidth(), image.getIconHeight() + ADDITIONAL_HEIGHT, BufferedImage.TYPE_4BYTE_ABGR);
+ final Graphics2D g = (Graphics2D) bi.getGraphics();
+ g.drawImage(image.getImage(), 0, 0, new ImageObserver() {
+ @Override
+ public boolean imageUpdate(final Image img, final int infoflags, final int x, final int y, final int width, final int height) {
+ return true;
+ }
+ });
+
+ final int top = image.getIconHeight();
+ final int width = image.getIconWidth();
+
+ g.setColor(Color.WHITE);
+ g.fillRect(0, top, width, ADDITIONAL_HEIGHT);
+ g.setColor(Color.BLACK);
+
+ final ImageIcon logo = IhmFactory.getIconFromResource(ImageResources.EDITEUR);
+ final 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);
+ this.ecritLigneCentree(g, this.getVersionText(), 90, width, font, Color.BLACK);
+ this.ecritLigneCentree(g, "Développé par axYus", top + 5, width + moa.getIconWidth() - logo.getIconWidth() - 2, font, Color.BLACK);
+ if (this.getParent() instanceof MainWindow) {
+ final XemeliosUser user = ((MainWindow) this.getParent()).getConnectedUser();
+ this.ecritLigneCentree(g, "Utilisateur: " + user.getDisplayName(), top - 20, width, font, Color.BLACK);
+ }
+ font = g.getFont().deriveFont(Font.ITALIC, 10f);
+ this.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);
+ this.ecritLigneCentree(g, "Direction Générale des Finances Publiques", top + 29, width + moa.getIconWidth() - logo.getIconWidth() - 7, font, Color.BLACK);
+
+ final 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(final MouseEvent evt) {
+ if (evt.getButton() == MouseEvent.BUTTON3 && evt.isControlDown() && evt.getClickCount() == 2) {
+ try {
+ final Class c = Class.forName("fr.gouv.finances.cp.xemelios.ui.ia.Plateau");
+ c.newInstance();
+ } catch (final Throwable t) {
+ }
+ }
+ }
+ });
+ layer.setPreferredSize(new Dimension(width, top + ADDITIONAL_HEIGHT));
+ final JButton pbFermer = new JButton("Fermer");
+ pbFermer.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ AboutBox.this.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));
+
+ final JPanel pane = new JPanel();
+ pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS));
+ pane.add(layer);
+ pane.setOpaque(true);
+ this.setContentPane(pane);
+ this.pack();
+ this.validate();
+ final Dimension sSz = Toolkit.getDefaultToolkit().getScreenSize();
+ final Dimension fSz = this.getSize();
+ this.setLocation((sSz.width - fSz.width) / 2, (sSz.height - fSz.height) / 2);
+ this.setResizable(false);
+ this.setVisible(true);
+ }
+
+ protected String getVersionText() {
+ String ret = "";
+ try {
+ String compFileName = null;
+ if (this.getParent() instanceof MainWindow) {
+ compFileName = ((MainWindow) this.getParent()).getEnvProperties().getProperty(Constants.SYS_PROP_COMPONENTS_FILENAME);
+ } else {
+ compFileName = System.getProperty(Constants.SYS_PROP_COMPONENTS_FILENAME);
+ }
+ if (compFileName != null) {
+ final File f = new File(compFileName);
+ if (f.exists()) {
+ final DocumentBuilderFactory domFactory = FactoryProvider.getDocumentBuilderFactory();
+ domFactory.setNamespaceAware(true);
+ final DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
+ final Document dom = domBuilder.parse(f);
+ final XPathFactory xpf = FactoryProvider.getXPathFactory();
+ final XPath xp = xpf.newXPath();
+ ret = xp.evaluate("/xemelios-components/component[@id='xemelios-core']/@version", new DOMSource(dom));
+ }
+ }
+ } catch (final Exception ex) {
+ ex.printStackTrace();
+ }
+ if (ret.length() == 0) {
+ try {
+ final BufferedInputStream bis = new BufferedInputStream(this.getClass().getClassLoader().getResourceAsStream(ImageResources.VERSION));
+ final byte[] buf = new byte[bis.available()];
+ bis.read(buf);
+ ret = new String(buf);
+ } catch (final Throwable t) {
+ }
+ }
+ return ret;
}
- 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;
+ protected void ecritLigneCentree(final Graphics2D graph, final String text, final int top, final int width, final Font font, final Color c) {
+ final Color oldColor = graph.getColor();
+ final Font oldFont = graph.getFont();
+ graph.setFont(font);
+ graph.setColor(c);
+
+ final FontMetrics fm = graph.getFontMetrics();
+ final StringTokenizer st = new StringTokenizer(text, " -");
+ final 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.");
+ 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) );
+ final int lenLigne = (ligne == null ? fm.stringWidth(mot) : fm.stringWidth(ligne + " " + mot));
if (lenLigne > width) {
- lignes.add (ligne);
+ lignes.add(ligne);
ligne = mot;
} else {
- if(ligne==null) ligne = mot;
- else ligne += " "+mot;
+ if (ligne == null) {
+ ligne = mot;
+ } else {
+ ligne += " " + mot;
+ }
}
}
- if (!"".equals (ligne)) lignes.add(ligne);
+ if (!"".equals(ligne)) {
+ lignes.add(ligne);
+ }
// calcul de l'interligne
- int hauteurLigne = fm.getAscent()+fm.getDescent();
- int interligne = fm.getLeading();
+ final int hauteurLigne = fm.getAscent() + fm.getDescent();
+ final 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);
+ for (int i = 0; i < lignes.size(); i++) {
+ ligne = lignes.get(i);
+ final int len = fm.stringWidth(ligne);
+ final int x = width / 2 - len / 2;
+ final int y = (i + 1) * interligne + fm.getAscent() + (i) * hauteurLigne + top;
+ graph.drawString(ligne, x, y);
}
- graph.setFont(oldFont);
- graph.setColor(oldColor);
- }
+ graph.setFont(oldFont);
+ graph.setColor(oldColor);
+ }
- public static void main(String[] args) {
- new AboutBox(null);
- }
+ public static void main(final String[] args) {
+ new AboutBox(null);
+ }
}
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
+import java.util.ArrayList;
import javax.swing.AbstractAction;
import javax.swing.Action;
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.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 {
*/
private static final long serialVersionUID = 3546362837975971889L;
static {
- if(System.getProperty("os.name").toLowerCase().indexOf("win")>=0)
+ if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
setDefaultLookAndFeelDecorated(true);
+ }
}
- public static final transient String DLG_TITLE="Type de document";
+ 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 final String fileName;
+ private final 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;
+ private final PropertiesExpansion applicationProperties;
+
+ public AskDocumentType(final JFrame owner, final String fileName, final DocumentsModel dm, final PropertiesExpansion applicationProperties) {
+ super(owner, DLG_TITLE, true);
+ this.applicationProperties = applicationProperties;
this.fileName = fileName;
this.documentsType = dm;
- initComposants();
+ this.initComposants();
}
-
+
protected void initComposants() {
- int sepInfo = 2;
- int lineInfo = sepInfo + 2;
- int sepData = lineInfo + 2;
- int cbxLine = sepData + 2;
- int buttonLine = cbxLine + 2;
-
+ final int sepInfo = 2;
+ final int lineInfo = sepInfo + 2;
+ final int sepData = lineInfo + 2;
+ final int cbxLine = sepData + 2;
+ final 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);
-
+
+ final 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
+ final CellConstraints cc = new CellConstraints();
+ final PanelBuilder pb = new PanelBuilder(fl);
+ final 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));
+ final ArrayList<DocumentModel> visibleDocs = new ArrayList<DocumentModel>();
+ for (final DocumentModel documentModel : this.documentsType.getDocuments()) {
+ if (documentModel.isImportable()) {
+ if ("true".equals(documentModel.getDisplayInMenuIf())) {
+ if (this.applicationProperties.getProperty(documentModel.getDisplayInMenuIf()) != null) {
+ visibleDocs.add(documentModel);
+ }
+ } else {
+ visibleDocs.add(documentModel);
+ }
+ }
+ }
+ pb.add(this.cbxTypes = new JComboBox(visibleDocs.toArray()), cc.xy(5, cbxLine));
+
+ final JPanel bPane = new JPanel(new FlowLayout(FlowLayout.CENTER));
+ this.pbCancel = new JButton(this.escapeAction);
+ this.pbOk = new JButton("Ok");
+ bPane.add(this.pbOk);
+ bPane.add(this.pbCancel);
+
+ pb.add(bPane, cc.xyw(2, buttonLine, 4));
+
+ final JComboBox cbxTmp = new JComboBox();
+ this.cbxTypes.setSize(new Dimension(70, (int) cbxTmp.getPreferredSize().getHeight()));
+ this.add(pb.getPanel());
+ // add(pbCancel); add(pbOk);
+
area.setEditable(false);
area.setLineWrap(true);
area.setRows(3);
- area.setBackground(getBackground());
+ area.setBackground(this.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);
+ area.setText("Vous avez choisi d'importer le fichier \n" + this.fileName + "\nDe quel type de document s'agit-il ?");
+
+ this.pbOk.setDefaultCapable(true);
+ this.pbOk.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ AskDocumentType.this.dm = (DocumentModel) AskDocumentType.this.cbxTypes.getSelectedItem();
+ AskDocumentType.this.ret = true;
+ AskDocumentType.this.setVisible(false);
}
});
- getRootPane().setDefaultButton(pbOk);
- pack();
- setLocationRelativeTo(getParent());
+ this.getRootPane().setDefaultButton(this.pbOk);
+ this.pack();
+ this.setLocationRelativeTo(this.getParent());
}
+
public boolean run() {
- setVisible(true);
- return ret;
+ this.setVisible(true);
+ return this.ret;
}
- public DocumentModel getDocumentType() { return dm; }
+
+ public DocumentModel getDocumentType() {
+ return this.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);
- }
+ final KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
+ final JRootPane rp = new JRootPane();
+ this.escapeAction = new AbstractAction("Annuler") {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ AskDocumentType.this.ret = false;
+ AskDocumentType.this.setVisible(false);
+ }
};
- rp.registerKeyboardAction(escapeAction,"TOTOTOTO",ks,JComponent.WHEN_IN_FOCUSED_WINDOW);
- return rp;
+ rp.registerKeyboardAction(this.escapeAction, "TOTOTOTO", ks, JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
}
- /* (non-Javadoc)
+
+ /*
+ * (non-Javadoc)
+ *
* @see java.awt.Component#setVisible(boolean)
*/
@Override
- public void setVisible(boolean b) {
- cbxTypes.grabFocus();
+ public void setVisible(final boolean b) {
+ this.cbxTypes.grabFocus();
super.setVisible(b);
}
}
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.ScrollPaneConstants;
+import javax.swing.WindowConstants;
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);
- }
- }
+ private static JTextArea jta;
+ private static JTextArea lines;
+ private JScrollPane jsp;
+ private URL input;
+
+ public CodeViewer(final URL input) {
+ super(input.getFile());
+ this.input = input;
+ this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
+ this.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() {
+ final int caretPosition = jta.getDocument().getLength();
+ final 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;
+ }
+
+ @Override
+ public void changedUpdate(final DocumentEvent de) {
+ lines.setText(this.getText());
+ }
+
+ @Override
+ public void insertUpdate(final DocumentEvent de) {
+ lines.setText(this.getText());
+ }
+
+ @Override
+ public void removeUpdate(final DocumentEvent de) {
+ lines.setText(this.getText());
+ }
+ });
+
+ this.jsp.getViewport().add(jta);
+ this.jsp.setRowHeaderView(lines);
+ this.jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
+
+ this.add(this.jsp);
+ this.pack();
+ this.setSize(800, 600);
+ this.setVisible(true);
+
+ this.doLoadFile();
+
+ }
+
+ protected void doLoadFile() {
+ try {
+ final InputStream is = this.input.openStream();
+ final StringBuilder sb = new StringBuilder();
+ final 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 (final Exception ex) {
+ JOptionPane.showMessageDialog(this, ex.getMessage(), "Erreur", JOptionPane.ERROR_MESSAGE);
+ }
+ }
}
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
+import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
+import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.event.CaretEvent;
import javax.swing.text.PlainDocument;
import org.apache.log4j.Logger;
+import org.jdesktop.swingx.JXDatePicker;
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.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.utils.Pair;
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.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) {
+ 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 final ElementModel em;
+ private final DocumentModel dm;
+ private final Pair collectivite, budget;
+ private Hashtable<String, InputData> inputs;
+ private ArrayList<InputData> orderedInputs;
+ // private ChampModel optionnalField = null;
+ private final boolean hideRemoveIcon, hideChoice;
+
+ private JComboBox cbxAndOr, cbxTypeCritere;
+ private Container replaceMe;
+ private final PnlSearch parent;
+ private JComponent componentToFocus = null;
+ private JCheckBox chkDisplayOptionnal = null;
+ private CritereModel currentCritereModel = null;
+ private JLabel defaultLabel = null;
+ private JLabel deleteMe = null;
+
+ public CriteriaViewer(final PnlSearch parent, final ElementModel em, final Pair collectivite, final Pair budget, final boolean hideRemoveIcon, final Vector<CritereModel> criteresOp) {
+ super();
+ this.parent = parent;
+ this.hideRemoveIcon = hideRemoveIcon;
+ this.em = em;
+ this.dm = em.getParent().getParent();
+ this.DATE_FORMAT = MainWindow.getInstance().getEnvProperties().getProperty(Constants.SYS_PROP_DATE_FORMAT);
+ this.sdf = new SimpleDateFormat(this.DATE_FORMAT);
+ this.collectivite = collectivite;
+ this.budget = budget;
+ this.hideChoice = false;
+ if (blankImg == null) {
+ final Image img = new BufferedImage(deleteImg.getIconWidth(), deleteImg.getIconHeight(), BufferedImage.TYPE_INT_RGB);
+ final Graphics2D gr = (Graphics2D) img.getGraphics();
+ gr.setBackground(parent.getBackground());
+ gr.clearRect(0, 0, deleteImg.getIconWidth(), deleteImg.getIconWidth());
+ blankImg = new ImageIcon(img);
+ }
+ this.initialize(hideRemoveIcon, false, criteresOp);
+ }
+
+ public CriteriaViewer(final PnlSearch parent, final ElementModel em, final Pair collectivite, final Pair budget, final boolean hideRemoveIcon) {
+ this(parent, em, collectivite, budget, hideRemoveIcon, false);
+ }
+
+ public CriteriaViewer(final PnlSearch parent, final ElementModel em, final Pair collectivite, final Pair budget, final boolean hideRemoveIcon, final boolean hideChoice) {
+ super();
+ this.parent = parent;
+ this.hideRemoveIcon = hideRemoveIcon;
+ this.em = em;
+ this.dm = em.getParent().getParent();
+ this.DATE_FORMAT = MainWindow.getInstance().getEnvProperties().getProperty(Constants.SYS_PROP_DATE_FORMAT);
+ this.sdf = new SimpleDateFormat(this.DATE_FORMAT);
+ this.collectivite = collectivite;
+ this.budget = budget;
+ this.hideChoice = hideChoice;
+ if (blankImg == null) {
+ final Image img = new BufferedImage(deleteImg.getIconWidth(), deleteImg.getIconHeight(), BufferedImage.TYPE_INT_RGB);
+ final Graphics2D gr = (Graphics2D) img.getGraphics();
+ gr.setBackground(parent.getBackground());
+ gr.clearRect(0, 0, deleteImg.getIconWidth(), deleteImg.getIconWidth());
+ blankImg = new ImageIcon(img);
+ }
+ this.initialize(hideRemoveIcon, hideChoice);
+ }
+
+ protected void initialize(final boolean hideRemoveIcon, final boolean hideChoice) {
+ final FormLayout fl = new FormLayout("3dlu,pref,3dlu,25dlu,3dlu,110dlu,3dlu,pref:grow(1.0),3dlu", "0dlu,pref");
+ final PanelBuilder pb = new PanelBuilder(fl, this);
+ final CellConstraints cc = new CellConstraints();
+ if (!hideRemoveIcon) {
+ final AbstractAction act = new AbstractAction() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ CriteriaViewer.this.parent.removeLine(CriteriaViewer.this);
+ }
+ };
+ this.deleteMe = new JFocusableLabel(deleteImg, act);
+ this.deleteMe.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(final MouseEvent evt) {
+ act.actionPerformed(null);
+ }
+ });
+ this.deleteMe.setToolTipText("Supprimer ce critère");
+ pb.add(this.deleteMe, cc.xy(2, 2));
+ final Pair[] data = new Pair[2];
+ data[0] = new Pair(AND_ASSOCIATOR, "ET");
+ data[1] = new Pair(OR_ASSOCIATOR, "OU");
+ pb.add(this.cbxAndOr = new JComboBox(data), cc.xy(4, 2));
+ } else {
+ final JLabel blank = new JLabel(blankImg);
+ blank.setBorder(new EmptyBorder(2, 2, 2, 2));
+ pb.add(blank, cc.xy(2, 2));
+ }
+ if (!hideChoice) {
+ pb.add(this.cbxTypeCritere = new JComboBox(this.em.getAvailableCriteres()), cc.xy(6, 2));
+ this.cbxTypeCritere.addActionListener(this);
+ } else {
+ pb.add(this.defaultLabel = new JLabel("XXXX"), cc.xy(6, 2));
+ }
+ pb.add(this.replaceMe = new JPanel(new FlowLayout()), cc.xy(8, 2));
+ if (!hideChoice && this.cbxTypeCritere.getItemCount() > 0) {
+ this.cbxTypeCritere.setSelectedIndex(0);
+ } else {
+ this.inputs = new Hashtable<String, InputData>();
+ this.orderedInputs = new ArrayList<InputData>();
+ }
+ }
+
+ protected void initialize(final boolean hideRemoveIcon, final boolean hideChoice, final Vector<CritereModel> criteresOp) {
+ final FormLayout fl = new FormLayout("3dlu,pref,3dlu,25dlu,3dlu,110dlu,3dlu,pref:grow(1.0),3dlu", "0dlu,pref");
+ final PanelBuilder pb = new PanelBuilder(fl, this);
+ final CellConstraints cc = new CellConstraints();
+ if (!hideRemoveIcon) {
+ final AbstractAction act = new AbstractAction() {
+
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ CriteriaViewer.this.parent.removeLine(CriteriaViewer.this);
+ }
+
+ };
+ this.deleteMe = new JFocusableLabel(deleteImg, act);
+ this.deleteMe.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(final MouseEvent evt) {
+ act.actionPerformed(null);
+ }
+ });
+ this.deleteMe.setToolTipText("Supprimer ce critère");
+ pb.add(this.deleteMe, cc.xy(2, 2));
+ final Pair[] data = new Pair[2];
+ data[0] = new Pair(AND_ASSOCIATOR, "ET");
+ data[1] = new Pair(OR_ASSOCIATOR, "OU");
+ pb.add(this.cbxAndOr = new JComboBox(data), cc.xy(4, 2));
+ } else {
+ final JLabel blank = new JLabel(blankImg);
+ blank.setBorder(new EmptyBorder(2, 2, 2, 2));
+ pb.add(blank, cc.xy(2, 2));
+ }
+ if (!hideChoice) {
+ pb.add(this.cbxTypeCritere = new JComboBox(criteresOp), cc.xy(6, 2));
+ this.cbxTypeCritere.addActionListener(this);
+ } else {
+ pb.add(this.defaultLabel = new JLabel("XXXX"), cc.xy(6, 2));
+ }
+ pb.add(this.replaceMe = new JPanel(new FlowLayout()), cc.xy(8, 2));
+ if (!hideChoice && this.cbxTypeCritere.getItemCount() > 0) {
+ this.cbxTypeCritere.setSelectedIndex(0);
+ } else {
+ this.inputs = new Hashtable<String, InputData>();
+ this.orderedInputs = new ArrayList<InputData>();
+ }
+ }
+
+ public void focusOnDelete() {
+ this.deleteMe.grabFocus();
+ }
+
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ if (evt.getSource() == this.cbxTypeCritere) {
+ this.inputs = new Hashtable<String, InputData>();
+ this.orderedInputs = new ArrayList<InputData>();
+ final CritereModel cm = (CritereModel) this.cbxTypeCritere.getSelectedItem();
+ this.changeCritereModel(cm.clone());
+ }
+ }
+
+ public void changeCritereModel(final CritereModel newCm) {
+ try {
+ CritereModel cm = null;
+ if (!this.hideChoice) {
+ for (int i = 0; i < this.cbxTypeCritere.getModel().getSize(); i++) {
+ final Object other = this.cbxTypeCritere.getModel().getElementAt(i);
+ if (newCm.equals(other)) {
+ cm = (CritereModel) other;
+ break;
+ }
+ }
+ } else {
+ cm = newCm.clone();
+ }
+ if (cm == null) {
+ return;
+ }
+ if (!this.hideChoice && !this.cbxTypeCritere.getSelectedItem().equals(cm)) {
+ this.cbxTypeCritere.removeActionListener(this);
+ this.cbxTypeCritere.setSelectedItem(cm);
+ this.cbxTypeCritere.addActionListener(this);
+ }
+ this.currentCritereModel = cm.clone();
+ this.replaceMe.removeAll();
+ if (this.hideChoice) {
+ this.defaultLabel.setText(cm.getLibelle());
+ }
+ if (this.currentCritereModel.hasBlank()) {
+ this.replaceMe.add(Box.createHorizontalGlue());
+ }
+ for (final 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()));
+ }
+ final String datatype = im.getDatatype();
+ Pair[] pairs = null;
+ if (datatype != null && !im.hasToRemoveOperator()) {
+ try {
+ pairs = DataLayerManager.getImplementation().getOperators(datatype);
+ } catch (final 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(final ActionEvent e) {
+ final Pair item = (Pair) opers.getSelectedItem();
+ final InputData id = CriteriaViewer.this.inputs.get("VALEUR:" + im.getId());
+ JButton pbHelp = null;
+ if (id != null) {
+ // on cherche si il y a un helpButton
+ for (final 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) {
+ final MTextField mtf = (MTextField) id;
+ mtf.setText("--");
+ mtf.setEnabled(false);
+ if (pbHelp != null) {
+ pbHelp.setEnabled(false);
+ }
+ }
+ }
+ } else {
+ if (id instanceof MTextField) {
+ final MTextField mtf = (MTextField) id;
+ mtf.setText("");
+ mtf.setEnabled(true);
+ if (pbHelp != null) {
+ pbHelp.setEnabled(true);
+ }
+ }
+ }
+ }
+ });
+ final String opValue = MainWindow.getInstance().getCriteriaInputValue(im.getKeyName() + ".OPERATEUR");
+ if (opValue != null) {
+ int opIndex = -1;
+ try {
+ opIndex = Integer.parseInt(opValue);
+ } catch (final 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)
+ final String helpPath = im.getHelpPath();
+ if (helpPath != null) {
+ final JHelpButton pbHelp = new JHelpButton((MTextField) jf, this.em, this.collectivite, this.budget, helpPath);
+ al.add(pbHelp);
+ }
+ // second cas, une recherche dans d'autres documents
+ if (im.getSearchHelper() != null) {
+ final SearchHelperModel shm = im.getSearchHelper();
+ final JHelpButton pbHelp = new JHelpButton((MTextField) jf, this.em, this.collectivite, this.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 (final Component c : al) {
+ this.replaceMe.add(c);
+ if (c.getName() != null) {
+ this.inputs.put(c.getName(), (InputData) c);
+ this.orderedInputs.add((InputData) c);
+ }
+ }
+ } else if (xm instanceof SelectModel) {
+ final SelectModel sm = (SelectModel) xm;
+ Collection<Pair> data = null;
+ final 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 {
+ final Vector<Pair> vRepository = DataLayerManager.getImplementation().getListeCodeLibelleRepository(this.dm, this.collectivite, this.parent.getUser());
+ if (vRepository.size() > 1) {
+ final MComboBox mcb = new MComboBox(vRepository);
+ mcb.setName("ListRepository_" + sm.getId());
+ this.replaceMe.add(mcb);
+ // TODO : Foculistener des éléments de la combobox
+ final MComboBox mcbListeCorresLibelle = this.remplirListe(sm, data, focusListeners);
+ mcb.addItemListener(new MComboBoxItemListener(this, sm, this.collectivite, mcb, mcbListeCorresLibelle));
+
+ } else {
+ this.remplirListe(sm, data, focusListeners);
+ }
+ } catch (final 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 (final OptionModel om : sm.getOptions()) {
+ data.add(new Pair(om.getValue(), om.getLibelle()));
+ }
+ }
+ for (final 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(this.dm, this.collectivite, rpm, this.parent.getUser()));
+ data.addAll(localData);
+ } catch (final 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 (final SpecialKeyEntryModel skem : sm.getSpecialKeys()) {
+ if (!skem.isDepends()) {
+ // si pas de dependance, on peut remplir maintenant
+ try {
+ data.addAll(DataLayerManager.getImplementation().getSpecialKeys1(this.dm, this.collectivite, this.budget, skem.isDistinct(), this.parent.getUser()));
+ } catch (final DataAccessException daEx) {
+ new DisplayExceptionDlg(SwingUtilities.getWindowAncestor(this), daEx);
+ } catch (final DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(SwingUtilities.getWindowAncestor(this), dcEx);
+ }
+ } else {
+ // il faut creer un FocusListener pour reinitialiser la liste a chaque fois
+ final SpecialKeyFocusAdapter fl = new SpecialKeyFocusAdapter(this, skem, sm, this.collectivite, this.budget);
+ focusListeners.add(fl);
+ }
+ }
+ for (final ResourceRefModel rrm : sm.getResources()) {
+ final ResourceModel rm = this.dm.getResource(rrm.getRefId());
+ for (final XmlMarshallable ob : rm.getData()) {
+ if (ob instanceof OptionModel) {
+ final OptionModel om = (OptionModel) ob;
+ data.add(new Pair(om.getValue(), om.getLibelle()));
+ }
+ }
+ }
+ final Vector<Pair> vData = new Vector<Pair>();
+ for (final Pair p : data) {
+ vData.add(p);
+ }
+ // fin de recherche des valeurs a mettre dans la liste
+ final MComboBox cbxData = new MComboBox(vData, sm);
+ cbxData.setName("VALEUR:" + sm.getId());
+ if (!focusListeners.isEmpty()) {
+ for (final FocusListener fl : focusListeners) {
+ cbxData.addFocusListener(fl);
+ }
+ }
+ if (sm.getLibelle() != null) {
+ this.replaceMe.add(getLabel(sm.getLibelle()));
+ }
+ this.replaceMe.add(cbxData);
+ if (sm.getValue() != null) {
+ final Pair p = new Pair(sm.getValue(), "");
+ // les paires se compares uniquement par leurs clefs
+ cbxData.setSelectedItem(p);
+ }
+ this.inputs.put(cbxData.getName(), cbxData);
+ this.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
+ final String idAffichage = cm.getIdAffichage();
+ if (idAffichage != null && idAffichage.length() > 0) {
+ this.chkDisplayOptionnal = new JCheckBox("Afficher le champ");
+ // if(option.isChecked()) chkDisplayOptionnal.setSelected(true);
+ if (cm.isDisplayOptional()) {
+ this.chkDisplayOptionnal.setSelected(true);
+ }
+ this.replaceMe.add(this.chkDisplayOptionnal);
+ } else {
+ this.chkDisplayOptionnal = null;
+ }
+
+ this.parent.repaintCriterias();
+ // on regarde si le critere a des valeurs
+ if (newCm.getValeurs() != null) {
+ for (final PropertyModel pm : newCm.getValeurs()) {
+ final String key = pm.getName();
+ final InputData id = this.inputs.get(key);
+ if (id == null) {
+ if (key.equals("AND_OR") && this.cbxAndOr != null) {
+ final Pair p = new Pair(pm.getValue(), "||".equals(pm.getValue()) ? "OU" : "ET");
+ this.cbxAndOr.setSelectedItem(p);
+ } else {
+ logger.debug("id not found: " + key);
+ }
+ // id.setInputValue(pm.getValue());
+ } else {
+ if (id instanceof MComboBox) {
+ final JComboBox cbx = (JComboBox) id;
+ if (cbx.isShowing()) {
+ cbx.dispatchEvent(new FocusEvent(cbx, FocusEvent.FOCUS_GAINED));
+ }
+ }
+ id.setInputValue(pm.getValue());
+ }
+ }
+ }
+ if (this.replaceMe.getComponentCount() == 0) {
+ // c'est un titre, il faut le faire grandir au max
+ this.removeAll();
+ this.setLayout(new FlowLayout());
+ this.add(new JLabel(cm.getLibelle()));
+ }
+ } catch (final UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(this, ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ }
+ }
+
+ private MComboBox remplirListe(final SelectModel sm, final Collection<Pair> data, final ArrayList<FocusListener> focusListeners) {
+ try {
+ if (sm.getOptions() != null) {
+ for (final OptionModel om : sm.getOptions()) {
+ data.add(new Pair(om.getValue(), om.getLibelle()));
+ }
+ }
+ for (final 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(this.dm, this.collectivite, rpm, this.parent.getUser()));
+ data.addAll(localData);
+ } catch (final 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 (final SpecialKeyEntryModel skem : sm.getSpecialKeys()) {
+ if (!skem.isDepends()) {
+ // si pas de dependance, on peut remplir maintenant
+ try {
+ data.addAll(DataLayerManager.getImplementation().getSpecialKeys1(this.dm, this.collectivite, this.budget, skem.isDistinct(), this.parent.getUser()));
+ } catch (final DataAccessException daEx) {
+ new DisplayExceptionDlg(SwingUtilities.getWindowAncestor(this), daEx);
+ } catch (final DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(SwingUtilities.getWindowAncestor(this), dcEx);
+ }
+ } else {
+ // il faut creer un FocusListener pour reinitialiser la liste a
+ // chaque fois
+ final SpecialKeyFocusAdapter fl = new SpecialKeyFocusAdapter(this, skem, sm, this.collectivite, this.budget);
+ focusListeners.add(fl);
+ }
+ }
+ for (final ResourceRefModel rrm : sm.getResources()) {
+ final ResourceModel rm = this.dm.getResource(rrm.getRefId());
+ for (final XmlMarshallable ob : rm.getData()) {
+ if (ob instanceof OptionModel) {
+ final OptionModel om = (OptionModel) ob;
+ data.add(new Pair(om.getValue(), om.getLibelle()));
+ }
+ }
+ }
+ final Vector<Pair> vData = new Vector<Pair>();
+ for (final Pair p : data) {
+ vData.add(p);
+ }
+ // fin de recherche des valeurs a mettre dans la liste
+ final MComboBox cbxData = new MComboBox(vData, sm);
+ cbxData.setName("VALEUR:" + sm.getId());
+ if (!focusListeners.isEmpty()) {
+ for (final FocusListener fl : focusListeners) {
+ cbxData.addFocusListener(fl);
+ }
+ }
+ if (sm.getLibelle() != null) {
+ this.replaceMe.add(getLabel(sm.getLibelle()));
+ }
+ this.replaceMe.add(cbxData);
+ if (sm.getValue() != null) {
+ final Pair p = new Pair(sm.getValue(), "");
+ // les paires se compares uniquement par leurs clefs
+ cbxData.setSelectedItem(p);
+ }
+ this.inputs.put(cbxData.getName(), cbxData);
+ this.orderedInputs.add(cbxData);
+ return cbxData;
+ } catch (final UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(this, ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ return null;
+ }
+ }
+
+ private MComboBox refreshListe(final SelectModel sm, final Collection<Pair> data, final ArrayList<FocusListener> focusListeners, final Pair repository) {
+ this.inputs.clear();
+ this.orderedInputs.clear();
+ for (final 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(this.dm, this.collectivite, rpm, repository, this.parent.getUser()));
+ data.addAll(localData);
+ } catch (final Exception dbEx) {
+ new DisplayExceptionDlg(SwingUtilities.getWindowAncestor(this), dbEx);
+ }
+ }
+ }
+ final Vector<Pair> vData = new Vector<Pair>();
+ for (final Pair p : data) {
+ vData.add(p);
+ }
+ // fin de recherche des valeurs a mettre dans la liste
+ final MComboBox cbxData = new MComboBox(vData, sm);
+ cbxData.setName("VALEUR:" + sm.getId());
+ if (!focusListeners.isEmpty()) {
+ for (final FocusListener fl : focusListeners) {
+ cbxData.addFocusListener(fl);
+ }
+ }
+ if (sm.getLibelle() != null) {
+ this.replaceMe.add(getLabel(sm.getLibelle()));
+ }
+ this.replaceMe.add(cbxData);
+ if (sm.getValue() != null) {
+ final Pair p = new Pair(sm.getValue(), "");
+ // les paires se compares uniquement par leurs clefs
+ cbxData.setSelectedItem(p);
+ }
+ this.inputs.put(cbxData.getName(), cbxData);
+ this.orderedInputs.add(cbxData);
+ return cbxData;
+ }
+
+ public static Component getLabel(final String lbl) {
+ return iF.newLabel(lbl, "normal");
+ }
+
+ public boolean isOptionalDisplayChecked() {
+ boolean result = false;
+ if (this.chkDisplayOptionnal != null) {
+ result = this.chkDisplayOptionnal.isSelected();
+ }
+ return result;
+ }
+
+ public String getXPathExpr() throws ToolException {
+ String expr = ((CritereModel) this.cbxTypeCritere.getSelectedItem()).getPath().getPath();
+ int ix = expr.indexOf("##");
+ while (ix >= 0) {
+ final String sTmp = expr.substring(ix + 2);
+ final int pos = sTmp.indexOf("##");
+ if (pos < 0) {
+ throw new ToolException("Expression mal formee: " + expr, ToolException.ERROR_MALFORMED_XPATH_EXPR);
+ }
+ final String middle = sTmp.substring(0, pos);
+ final InputData id = this.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) {
+ this.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) {
+ this.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) {
+ final MTextField df = (MTextField) id;
+ if ("numeric".equals(df.getDatatype())) {
+ try {
+ Float.parseFloat(df.getText());
+ } catch (final 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) {
+ final InputModel im = (InputModel) df.getMarshallModel();
+ MainWindow.getInstance().setCriteriaInputValue(im.getKeyName(), df.isEditable() ? id.getInputValue() : null);
+ if (im.getDatatype() != null && !im.hasToRemoveOperator()) {
+ final InputData op = this.inputs.get("OPERATEUR:" + im.getId());
+ if (op instanceof MComboBox) {
+ final MComboBox cbxOp = (MComboBox) op;
+ final 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 {
+ final Hashtable<String, String> ret = new Hashtable<String, String>();
+ for (final Enumeration<InputData> enumer = this.inputs.elements(); enumer.hasMoreElements();) {
+ final InputData id = enumer.nextElement();
+ if (id.getInputValue() == null || id.getInputValue().length() == 0) {
+ this.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) {
+ this.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) {
+ final MTextField df = (MTextField) id;
+ if ("numeric".equals(df.getDatatype())) {
+ try {
+ Float.parseFloat(df.getText());
+ } catch (final NumberFormatException mfEx) {
+ this.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 {
+ this.sdf.parse(df.getText());
+ } catch (final ParseException pEx) {
+ this.componentToFocus = df;
+ throw new ToolException("Le champ désigné par le curseur doit contenir une date au format " + this.DATE_FORMAT, ToolException.ERROR_MISFILLED_CRITERIA);
+ }
+ }
+ }
+ final String name = id.getName();
+ ret.put(name, id.getInputValue());
+ }
+ return ret;
+ }
+
+ public String getAndOrEr() {
+ if (this.hideRemoveIcon) {
+ return "";
+ }
+ return ((Pair) (this.cbxAndOr.getSelectedItem())).key;
+ }
+
+ public void doFocusOnError() {
+ if (this.componentToFocus != null) {
+ this.componentToFocus.grabFocus();
+ }
+ }
+
+ public XmlMarshallable getXmlMarshallable() {
+ this.currentCritereModel.getValeurs().removeAllElements();
+ this.currentCritereModel.removeAllProperties();
+ this.currentCritereModel.setDisplayOptional(this.isOptionalDisplayChecked());
+ if (this.cbxAndOr != null && this.cbxAndOr.getSelectedItem() != null) {
+ try {
+ this.currentCritereModel.addChild(new PropertyModel("AND_OR", ((Pair) this.cbxAndOr.getSelectedItem()).key), PropertyModel.QN);
+ } catch (final SAXException saxEx) {
+ }
+ }
+ for (final InputData id : this.orderedInputs) {
+ try {
+ this.currentCritereModel.addChild(new PropertyModel(id.getName(), id.getInputValue()), PropertyModel.QN);
+ } catch (final SAXException saxEx) {
+ }
+ }
+ return this.currentCritereModel;
+ }
+
+ public CritereModel getModel() {
+ return (CritereModel) this.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 final SelectModel sm;
+ private final Hashtable<String, Pair> innerData;
+
+ public MComboBox(final Vector<Pair> data) {
+ this(data, null);
+ }
+
+ public MComboBox(final Vector<Pair> data, final SelectModel sm) {
+ super(data);
+ this.setEditable(false);
+ this.sm = sm;
+ if (sm != null) {
+ this.addListener();
+ }
+ this.innerData = new Hashtable<String, Pair>();
+ for (final Pair p : data) {
+ this.innerData.put(p.key, p);
+ }
+ }
+
+ public MComboBox(final Pair[] data) {
+ this(data, null);
+ }
+
+ public MComboBox(final Pair[] data, final SelectModel sm) {
+ super(data);
+ this.setEditable(false);
+ this.sm = sm;
+ if (sm != null) {
+ this.addListener();
+ }
+ this.innerData = new Hashtable<String, Pair>();
+ for (final Pair element : data) {
+ this.innerData.put(element.key, element);
+ }
+ }
+
+ private void addListener() {
+ this.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ if (MComboBox.this.getSelectedItem() != null) {
+ MComboBox.this.sm.setValue(((Pair) MComboBox.this.getSelectedItem()).key);
+ }
+ }
+ });
+ }
+
+ @Override
+ public String getInputValue() {
+ final Object item = this.getSelectedItem();
+ if (item == null) {
+ return null;
+ }
+ if (item instanceof Pair) {
+ return ((Pair) item).key;
+ }
+ return item.toString();
+ }
+
+ @Override
+ public void setInputValue(final String data) {
+ if (this.getItemCount() == 0) {
+ this.grabFocus();
+ }
+ Pair p = this.innerData.get(data);
+ if (p == null) {
+ p = new Pair(data, data);
+ this.addItem(p);
+ }
+ if (p != null) {
+ this.setSelectedItem(p);
+ }
+ }
+
+ @Override
+ public XmlMarshallable getMarshallModel() {
+ if (this.sm == null) {
+ return null;
+ }
+ this.sm.setValue(this.getInputValue());
+ return this.sm;
+ }
+
+ @Override
+ public String getXmlFormattedDate() {
+ return "";
+ }
+
+ public void setData(final Vector<Pair> vpair) {
+ this.removeAllItems();
+ for (int i = 0; i < vpair.size(); i++) {
+ this.addItem(vpair.get(i));
+ this.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 final InputModel im;
+
+ public MTextField(final InputModel im) {
+ super();
+ this.im = im;
+ if (im.isUppercase()) {
+ this.setDocument(new UppercaseFilteredField());
+ } else if ("date".equals(im.getDatatype())) {
+ this.setDocument(new DateFilteredField());
+ this.addFocusListener(new FocusListener() {
+ @Override
+ public void focusGained(final FocusEvent e) {
+ }
+
+ @Override
+ public void focusLost(final FocusEvent e) {
+ try {
+ final Date d = CriteriaViewer.this.sdf.parse(MTextField.this.getText());
+ MTextField.this.setText(CriteriaViewer.this.sdf.format(d));
+ } catch (final Throwable t) {
+ }
+ }
+
+ });
+ }
+ if (im != null) {
+ this.addCaretListener(new CaretListener() {
+ @Override
+ public void caretUpdate(final CaretEvent e) {
+ MTextField.this.im.setValue(MTextField.this.getText());
+ }
+ });
+ }
+ }
+
+ @Override
+ public String getXmlFormattedDate() {
+ final SimpleDateFormat sdfxml = new SimpleDateFormat(this.im.getXmlDateFormat());
+ try {
+ final Date d = CriteriaViewer.this.sdf.parse(this.getText());
+ return sdfxml.format(d);
+ } catch (final Throwable t) {
+
+ }
+ return null;
+ }
+
+ public String getDatatype() {
+ return this.im.getDatatype();
+ }
+
+ @Override
+ public String getInputValue() {
+ return this.getText();
+ }
+
+ @Override
+ public void setInputValue(final String data) {
+ this.setText(data);
+ }
+
+ @Override
+ public XmlMarshallable getMarshallModel() {
+ this.im.setValue(this.getInputValue());
+ return this.im;
+ }
+
+ @SuppressWarnings("empty-statement")
+ public Date getDate() {
+ if (this.getDatatype().equals("date")) {
+ try {
+ return CriteriaViewer.this.sdf.parse(this.getText());
+ } catch (final Throwable t) {
+ }
+ }
+ ;
+ return null;
+ }
+ }
+
+ class MDateField extends JXDatePicker implements InputData {
+ private final InputModel im;
+ private Date currentDate;
+
+ public MDateField(final InputModel im) {
+ super();
+ this.im = im;
+ final ActionListener l = new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ if (JXDatePicker.COMMIT_KEY.equals(e.getActionCommand())) {
+ MDateField.this.saveDate(MDateField.this.getDate());
+ }
+ }
+ };
+ this.addActionListener(l);
+ final PropertyChangeListener listener = new PropertyChangeListener() {
+ @Override
+ public void propertyChange(final PropertyChangeEvent e) {
+ if ("date".equals(e.getPropertyName())) {
+ MDateField.this.saveDate(MDateField.this.getDate());
+ }
+ }
+ };
+ this.addPropertyChangeListener(listener);
+ // TreeSet<String> formats = new TreeSet<String>();
+ // formats.add(DATE_FORMAT);
+ // formats.add("dd-MM-yyyy");
+ // formats.add("EEE dd MMM yyyy");
+ this.setFormats(CriteriaViewer.this.DATE_FORMAT, "dd-MM-yyyy", "EEE dd MMM yyyy");
+ }
+
+ private void saveDate(final Date date) {
+ this.currentDate = date;
+ }
+
+ @Override
+ public String getInputValue() {
+ if (this.currentDate != null) {
+ return CriteriaViewer.this.sdf.format(this.getDate());
+ } else {
+ return null;
+ }
+ }
+
+ @Override
+ public void setInputValue(final String data) {
+ try {
+ final Date date = CriteriaViewer.this.sdf.parse(data);
+ this.setDate(date);
+ } catch (final ParseException pEx) {
+ logger.info(data + " is not a valid date to format " + CriteriaViewer.this.DATE_FORMAT);
+ }
+ }
+
+ @Override
+ public XmlMarshallable getMarshallModel() {
+ this.im.setValue(this.getInputValue());
+ return this.im;
+ }
+
+ @Override
+ public String getXmlFormattedDate() {
+ final SimpleDateFormat sdfxml = new SimpleDateFormat(this.im.getXmlDateFormat());
+ try {
+ return sdfxml.format(this.currentDate);
+ } catch (final Throwable t) {
+
+ }
+ return null;
+ }
+
+ }
+
+ private class UppercaseFilteredField extends PlainDocument {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void insertString(final int offset, String str, final 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(final String format) {
+ super();
+ this.format = format;
+ }
+
+ public DateFilteredField() {
+ this(CriteriaViewer.this.DATE_FORMAT);
+ }
+
+ public String getFormat() {
+ return this.format;
+ }
+
+ @Override
+ public void insertString(int offset, final String str, final AttributeSet attr) throws BadLocationException {
+ if (str == null) {
+ logger.debug("str is null");
+ return;
+ }
+ if (this.getFormat() == null || this.getFormat().length() == 0) {
+ logger.debug("format is null");
+ return;
+ }
+ if (offset >= this.getFormat().length()) {
+ logger.debug("length > format");
+ return;
+ }
+ final char aChar = str.charAt(0);
+ final char fChar = this.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 < this.getFormat().length()) {
+ final char bChar = this.getFormat().charAt(offset);
+ final 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(this.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, final int len) throws BadLocationException {
+ if (this.getFormat() == null || this.getFormat().length() == 0) {
+ return;
+ }
+ //
+ //
+ super.remove(offset, len);
+ final char bChar = this.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 final MTextField targetField;
+ private final Pair collectivite, budget;
+ private final ElementModel em;
+ private String path;
+ SearchHelperModel shm;
+
+ JHelpButton(final MTextField targetField, final ElementModel elementModel, final Pair collectivite, final Pair budget, final String path) {
+ super("...");
+ this.targetField = targetField;
+ this.em = elementModel;
+ this.collectivite = collectivite;
+ this.budget = budget;
+ this.path = path;
+ this.__initialize();
+ }
+
+ JHelpButton(final MTextField targetField, final ElementModel elementModel, final Pair collectivite, final Pair budget, final SearchHelperModel shm) {
+ super("...");
+ this.targetField = targetField;
+ this.em = elementModel;
+ this.collectivite = collectivite;
+ this.budget = budget;
+ this.shm = shm;
+ this.__initialize();
+ }
+
+ private void __initialize() {
+ final Dimension fieldSize = this.targetField.getPreferredSize();
+ this.setPreferredSize(new Dimension((int) fieldSize.getHeight(), (int) fieldSize.getHeight()));
+ this.setToolTipText("Liste des éléments");
+ this.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ JHelpButton.this.displayHelpBox();
+ }
+ });
+ }
+
+ protected void displayHelpBox() {
+ if (this.shm == null) {
+ final TreeSet<String> values = new TreeSet<String>();
+ try {
+ this.setCursor(new Cursor(Cursor.WAIT_CURSOR));
+ values.addAll(DataLayerManager.getImplementation().getDistinctValues(this.em, this.collectivite, this.budget, this.path, CriteriaViewer.this.parent.getUser()));
+ Container c = CriteriaViewer.this.parent;
+ while (c != null && !(c instanceof JFrame)) {
+ c = c.getParent();
+ }
+ final JFrame parent = (JFrame) c;
+ final DlgSelectFromList dsfl = new DlgSelectFromList(parent, values);
+ if (dsfl.run()) {
+ this.targetField.setInputValue(dsfl.getSelectedValue());
+ }
+ } catch (final Throwable t) {
+ Container c = CriteriaViewer.this.parent;
+ while (c != null && !(c instanceof JFrame)) {
+ c = c.getParent();
+ }
+ new DisplayExceptionDlg((JFrame) c, t);
+ } finally {
+ this.setCursor(Cursor.getDefaultCursor());
+ }
+ } else {
+ final SearchContext sCtx = CriteriaViewer.this.parent.getSearchContext();
+ final DlgSearchHelper dlg = new DlgSearchHelper(SwingUtilities.getWindowAncestor(this), this.targetField, this.shm, sCtx);
+ dlg.setVisible(true);
+ }
+ }
+ }
+
+ private class SpecialKeyFocusAdapter extends FocusAdapter {
+ private final CriteriaViewer cv;
+ private final SelectModel sm;
+ private final SpecialKeyEntryModel skem;
+ private final DocumentModel dm;
+ private final Pair collectivite, budget;
+
+ public SpecialKeyFocusAdapter(final CriteriaViewer cv, final SpecialKeyEntryModel skem, final SelectModel sm, final Pair collectivite, final Pair budget) {
+ super();
+ this.cv = cv;
+ this.skem = skem;
+ this.sm = sm;
+ this.collectivite = collectivite;
+ this.budget = budget;
+ this.dm = cv.dm;
+ }
+
+ @Override
+ public void focusGained(final FocusEvent evt) {
+ final JComboBox cbx = (JComboBox) evt.getSource();
+ cbx.removeFocusListener(this);
+ cbx.removeAllItems();
+ final Vector<Pair> data = new Vector<Pair>();
+ try {
+ if (this.sm.getOptions() != null) {
+ for (final OptionModel om : this.sm.getOptions()) {
+ data.add(new Pair(om.getValue(), om.getLibelle()));
+ }
+ }
+ for (final ResourceRefModel rrm : this.sm.getResources()) {
+ final ResourceModel rm = this.dm.getResource(rrm.getRefId());
+ for (final XmlMarshallable ob : rm.getData()) {
+ if (ob instanceof OptionModel) {
+ final OptionModel om = (OptionModel) ob;
+ data.add(new Pair(om.getValue(), om.getLibelle()));
+ }
+ }
+ }
+ for (final RecherchePaireModel rpm : this.sm.getRecherches()) {
+ if (rpm.getPath() != null) {
+ // on fait une requete dans le referentiel pour
+ // remplir la liste
+ try {
+ data.addAll(DataLayerManager.getImplementation().queryRepository(this.dm, this.collectivite, rpm, CriteriaViewer.this.parent.getUser()));
+ } catch (final 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 = this.skem.getKey1().getData();
+ String itemName = path.substring(2, path.length() - 2);
+ InputData id = this.cv.inputs.get(itemName);
+ if (id.getInputValue() != null && id.getInputValue().length() > 0) {
+ key1 = id.getInputValue();
+ }
+ final Collection<Pair> tmp = this.sm.getNewRecipient();
+ if (this.skem.getPos() == 2) {
+ // we can search here
+ tmp.addAll(DataLayerManager.getImplementation().getSpecialKeys2(this.dm, this.collectivite, this.budget, new Pair(key1, key1), this.skem.isDistinct(), CriteriaViewer.this.parent.getUser()));
+ } else {
+ path = this.skem.getKey1().getData();
+ itemName = path.substring(2, path.length() - 2);
+ id = this.cv.inputs.get(itemName);
+ if (id.getInputValue() != null && id.getInputValue().length() > 0) {
+ key2 = id.getInputValue();
+ }
+ tmp.addAll(DataLayerManager.getImplementation().getSpecialKeys3(this.dm, this.collectivite, this.budget, new Pair(key1, key1), new Pair(key2, key2), this.skem.isDistinct(), CriteriaViewer.this.parent.getUser()));
+ }
+ data.addAll(tmp);
+ for (final Pair p : data) {
+ cbx.addItem(p);
+ }
+ cbx.setPopupVisible(true);
+ cbx.grabFocus();
+ cbx.addFocusListener(this);
+ } catch (final UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(CriteriaViewer.this, ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (final DataConfigurationException dcEx) {
+ // TODO : attention au probleme de focus en boucle
+ logger.error("dans focusGained", dcEx);
+ } catch (final DataAccessException daEx) {
+ // TODO : attention au probleme de focus en boucle
+ logger.error("dans focusGained", daEx);
+ }
+ }
+ }
+
+ private class MComboBoxItemListener implements ItemListener {
+ private final SelectModel sm;
+ private final DocumentModel dm;
+ private final Pair collectivite;
+ private final MComboBox mcb, mcbListeCorresLib;
+
+ public MComboBoxItemListener(final CriteriaViewer cv, final SelectModel sm, final Pair collectivite, final MComboBox mcbox, final MComboBox mcboxListeCorrsLib) {
+ super();
+ this.sm = sm;
+ this.collectivite = collectivite;
+ this.dm = cv.dm;
+ this.mcb = mcbox;
+ this.mcbListeCorresLib = mcboxListeCorrsLib;
+ }
+
+ @Override
+ public void itemStateChanged(final ItemEvent evt) {
+ try {
+ final Pair repository = (Pair) this.mcb.getSelectedItem();
+ final Vector<Pair> vRepository = (Vector<Pair>) DataLayerManager.getImplementation().queryRepository(this.dm, this.collectivite, this.sm.getRecherches().get(0), repository, CriteriaViewer.this.parent.getUser());
+ this.mcbListeCorresLib.setData(vRepository);
+ } catch (final UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(CriteriaViewer.this, ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (final DataConfigurationException e) {
e.printStackTrace();
- } catch (DataAccessException e) {
+ } catch (final 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);
- }
+ }
+ }
+ }
+
+ private class JFocusableLabel extends JLabel {
+
+ public JFocusableLabel(final Icon icon, final Action act) {
+ super(icon);
+ this.setFocusable(true);
+ this.setBorder(new EmptyBorder(2, 2, 2, 2));
+ this.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "CLICK");
+ this.getActionMap().put("CLICK", act);
+ this.addFocusListener(new FocusAdapter() {
+
+ @Override
+ public void focusGained(final FocusEvent e) {
+ ((JFocusableLabel) e.getComponent()).paintFocus();
+ }
+
+ @Override
+ public void focusLost(final FocusEvent e) {
+ ((JFocusableLabel) e.getComponent()).paintFocus();
+ }
+
+ });
+ this.addMouseListener(new MouseAdapter() {
+
+ @Override
+ public void mousePressed(final MouseEvent e) {
+ JFocusableLabel.this.requestFocus();
+ }
+
+ });
+ }
+
+ @Override
+ protected void paintComponent(final Graphics g) {
+ super.paintComponent(g);
+ this.paintFocus(g);
+ }
+
+ protected void paintFocus(final Graphics g) {
+ if (g == null) {
+ return;
+ }
+ if (this.isFocusOwner()) {
+ g.setColor(UIManager.getColor("Button.focus"));
+ } else {
+ g.setColor(UIManager.getColor("Label.background"));
+ }
+ g.drawRect(0, 0, this.getWidth() - 1, this.getHeight() - 1);
+ }
+
+ protected void paintFocus() {
+ this.paintFocus(this.getGraphics());
+ }
+
+ @Override
+ protected void processFocusEvent(final FocusEvent e) {
+ super.processFocusEvent(e);
+ this.invalidate();
+ }
+
+ }
+
+ public void setInputValue(final String inputId, final String value) {
+ final InputData id = this.inputs.get(inputId);
+ if (id != null) {
+ id.setInputValue(value);
+ }
+ }
+
public CritereModel getCurrentCritereModel() {
- return currentCritereModel;
+ return this.currentCritereModel;
}
+
public boolean isHideRemoveIcon() {
- return hideRemoveIcon;
+ return this.hideRemoveIcon;
}
}
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;
+import fr.gouv.finances.dgfip.xemelios.data.ExportableData;
+
public class DatabaseTreeDataFichier extends AbstractTreeTableModel {
- private JXTable table;
- private String[] columnNames = new String [] { "", "" };
- private ExportableData data = new ExportableData();
+ private final JXTable table;
+ private final String[] columnNames = new String[] { "", "" };
+ private final ExportableData data = new ExportableData();
private boolean selectionMultiple = true;
private int mode;
-
+
public int getMode() {
- return mode;
+ return this.mode;
}
- public void setMode(int mode) {
+
+ public void setMode(final int mode) {
this.mode = mode;
}
+
public boolean isSelectionMultiple() {
- return selectionMultiple;
+ return this.selectionMultiple;
}
- public void setSelectionMultiple(boolean selectionMultiple) {
+
+ public void setSelectionMultiple(final boolean selectionMultiple) {
this.selectionMultiple = selectionMultiple;
}
- public DatabaseTreeDataFichier (JXTable table) {
+
+ public DatabaseTreeDataFichier(final JXTable table) {
super();
this.table = table;
}
- public DatabaseTreeDataFichier (Vector<ExportableData> d, JXTable table) {
+
+ public DatabaseTreeDataFichier(final Vector<ExportableData> d, final JXTable table) {
super();
- this.table=table;
- if (d!=null && d.size()>0) {
- data.setLibelle("Documents");
- data.setChilds(d);
+ this.table = table;
+ if (d != null && d.size() > 0) {
+ this.data.setLibelle("Documents");
+ this.data.setChilds(d);
+ } else {
+ this.data.setLibelle("Aucun fichier ne correspond aux critères de recherche.");
+ }
+ this.data.setSelected(false);
+ }
+
+ @Override
+ public boolean isLeaf(final Object node) {
+ return (((ExportableData) node).getChilds().size() == 0);
+ }
+
+ @Override
+ public Class getColumnClass(final 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(final Object object, final int i) {
+ if (i == 0) {
+ return ((ExportableData) object).getLibelle();
+ } else if (i == 1) {
+ return new Boolean(((ExportableData) object).isSelected());
+ } else {
+ return "";
}
- else {
- data.setLibelle("Aucun fichier ne correspond aux critères de recherche.");
+ }
+
+ @Override
+ public void setValueAt(final Object value, final Object node, final int column) {
+ if (column == 1) {
+ if (this.selectionMultiple) {
+ ((ExportableData) node).setSelected(((Boolean) value).booleanValue());
+ } else if (((Boolean) value).booleanValue()) {
+ this.resetValue(this.data);
+ ((ExportableData) node).setSelected(((Boolean) value).booleanValue());
+ if (this.table != null) {
+ this.table.tableChanged(new TableModelEvent(this.table.getModel()));
+ }
+ }
}
+ }
+
+ private void resetValue(final ExportableData data) {
data.setSelected(false);
+ for (final ExportableData d : data.getChilds()) {
+ this.resetValue(d);
+ }
+ }
+
+ @Override
+ public int getChildCount(final Object parent) {
+ return ((ExportableData) parent).getChilds().size();
+ }
+
+ @Override
+ public Object getChild(final Object parent, final int index) {
+ return ((ExportableData) parent).getChild(index);
}
- @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 {
-// }
+ @Override
+ public boolean isCellEditable(final Object object, final int i) {
+ if (this.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 != this.getRoot() && i == 1) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+ }
+
+ @Override
+ public int getIndexOfChild(final Object parent, final Object child) {
+ int i = 0;
+ for (final 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 this.data;
+ }
+
+ @Override
+ public int getColumnCount() {
+ return this.columnNames.length;
+ }
+
+ @Override
+ public String getColumnName(final int arg0) {
+ return this.columnNames[arg0];
+ }
+
+ // public void addData(Data d) {
+ // datas.add(d);
+ // }
+
+ // public static class Data {
+ // }
public ExportableData getData() {
- return data;
- }
+ return this.data;
+ }
}
*/
package fr.gouv.finances.cp.xemelios.ui;
+import java.awt.Cursor;
+
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
+ *
+ * @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));
- }
+ public static enum DIALOG_TYPE {
+ FILE, DATA, BOTH
+ };
+
+ private DocumentsModel dm;
+ private final XemeliosUser user;
+ private final PropertiesExpansion applicationConfiguration;
+ private final DIALOG_TYPE dialogType;
+
+ public void setBActionLibelle(final String actionLibelle) {
+ this.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(final java.awt.Frame parent, final boolean modal, final DocumentsModel _dm, final boolean selectionMultiple, final DIALOG_TYPE dialogType, final XemeliosUser user, final PropertiesExpansion applicationConfiguration) {
+ super(parent, modal);
+ this.user = user;
+ this.dialogType = dialogType;
+ this.applicationConfiguration = applicationConfiguration;
+ this.setDm(_dm);
+ this.initComponents();
+ this.setLocationRelativeTo(this.getParent());
+ this.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() {
+
+ this.jTabbedPane1 = new javax.swing.JTabbedPane();
+ if (this.dialogType == DIALOG_TYPE.DATA || this.dialogType == DIALOG_TYPE.BOTH) {
+ this.jTabbedPane1.addTab("Par données", new PanelChooseDatabaseDonnees(this, this.dm, this.user, this.applicationConfiguration));
+ }
+ if (this.dialogType == DIALOG_TYPE.FILE || this.dialogType == DIALOG_TYPE.BOTH) {
+ this.jTabbedPane1.addTab("Par fichier", new PanelChooseDatabaseFichier(this, this.dm, false, this.user, this.applicationConfiguration));
+ }
+ this.bFermer = new javax.swing.JButton();
+ this.bAction = new javax.swing.JButton();
+
+ this.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+
+ this.bFermer.setText("Fermer");
+ this.bFermer.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgChooseDocuments.this.bFermerActionPerformed(evt);
+ }
+ });
+
+ this.bAction.setText("Action");
+ this.bAction.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgChooseDocuments.this.bActionActionPerformed(evt);
+ }
+ });
+
+ final org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this.getContentPane());
+ this.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(this.jTabbedPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 636, Short.MAX_VALUE)
+ .add(layout.createSequentialGroup().add(this.bFermer).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.bAction))).addContainerGap()));
+ layout.setVerticalGroup(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(
+ layout.createSequentialGroup().addContainerGap().add(this.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(this.bAction).add(this.bFermer)).addContainerGap()));
+
+ this.pack();
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void bActionActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_bActionActionPerformed
+ this.doAction(evt);
+ }// GEN-LAST:event_bActionActionPerformed
+
+ private void bFermerActionPerformed(final 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 this.dm;
+ }
+
+ public void setDm(final DocumentsModel dm) {
+ this.dm = dm;
+ }
+
+ public javax.swing.JTabbedPane getJTabbedPane1() {
+ return this.jTabbedPane1;
+ }
+
+ public void enableButtons(final boolean enable) {
+ this.bAction.setEnabled(enable);
+ this.bFermer.setEnabled(enable);
+ }
+
+ @Override
+ public void startWait() {
+ this.setCursor(new Cursor(Cursor.WAIT_CURSOR));
+ }
+
+ @Override
+ public void stopWait() {
+ this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
+ }
}
*/
package fr.gouv.finances.cp.xemelios.ui;
-import fr.gouv.finances.cp.utils.PropertiesExpansion;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.lang.reflect.Constructor;
+import java.nio.charset.Charset;
+import java.util.Date;
import java.util.HashMap;
import java.util.StringTokenizer;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
+import nu.xom.Attribute;
+import nu.xom.Element;
+import nu.xom.Nodes;
+
import org.apache.log4j.Logger;
import org.jdesktop.swingworker.SwingWorker;
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
import fr.gouv.finances.dgfip.utils.DateUtils;
import fr.gouv.finances.dgfip.utils.Pair;
import fr.gouv.finances.dgfip.xemelios.importers.NullImportServiceProvider;
import fr.gouv.finances.dgfip.xemelios.importers.archives.ArchiveImporter;
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.lang.reflect.Constructor;
-import java.nio.charset.Charset;
-import java.util.Date;
-import nu.xom.Attribute;
-import nu.xom.Element;
-import nu.xom.Nodes;
@SuppressWarnings("serial")
public class DlgCleanDatabase extends DlgChooseDocuments implements WaitableUI {
- private static Logger logger = Logger.getLogger(DlgCleanDatabase.class);
- private XemeliosUser user;
- private PropertiesExpansion applicationProperties;
-
- public DlgCleanDatabase(java.awt.Frame parent, boolean modal, DocumentsModel _dm, DlgChooseDocuments.DIALOG_TYPE dialogType, XemeliosUser user, PropertiesExpansion applicationProperties) {
- super(parent, modal, _dm, true, dialogType, user, MainWindow.getInstance().getEnvProperties());
- this.user = user;
- this.applicationProperties = applicationProperties;
- 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 {
- nu.xom.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("manifeste2").getNamespaces());
- Nodes documentIds = manifeste.query("//m:document/@type", ArchiveImporter.getNamespaceCtx());
- HashMap<String, DocumentModel> docsModel = new HashMap<String, DocumentModel>();
- for (int i = 0; i < documentIds.size(); i++) {
- String docId = documentIds.get(i).getValue();
- docId = ArchiveImporter.normalizeDocumentType(docId);
- if("PJ".equals(docId)) docId=null;
- if ( docId!=null && !docsModel.containsKey(docId)) {
- try {
- docsModel.put(docId, MainWindow.getInstance().getDocModels().getDocumentById(docId));
- } catch(NullPointerException npe) {
- logger.error("NPE with "+docId);
- throw npe;
- }
- }
- }
- DataLayerManager.getImplementation().removeArchive(docsModel, ((Pair)node.getData()).libelle, user);
-logger.debug("ici, node.getData().libelle = "+((Pair)node.getData()).libelle);
- // Mise à jour du manifeste de l'archive
-// DataLayerManager.getImplementation().updateManifeste(((Pair)node.getData()).libelle, user);
- Nodes documents = manifeste.query("/m:manifeste/m:documents/m:document", ArchiveImporter.getNamespaceCtx());
- for(int i=0;i<documents.size();i++) {
- nu.xom.Element doc = (nu.xom.Element)documents.get(i);
- nu.xom.Element resultImport = ArchiveImporter.getElement(doc.query("m:resultatimport | resultatimport", ArchiveImporter.getNamespaceCtx()));
- if(resultImport!=null) doc.removeChild(resultImport);
- doc.addAttribute(new Attribute("imported","Non"));
- }
- nu.xom.Element evt = new Element("evenement");
- evt.addAttribute(new Attribute("date", DateUtils.formatXsDateTime(new Date())));
- evt.addAttribute(new Attribute("section", "Suppression complète"));
- Element evts = ArchiveImporter.getElement(manifeste.query("/m:manifeste/m:evenements", ArchiveImporter.getNamespaceCtx()));
- evts.insertChild(evt, 0);
- manifeste.getRootElement().addAttribute(new Attribute("imported", "Non"));
- manifeste.getRootElement().addAttribute(new Attribute("added:archive", Constants.ADDED_NS_URI,"Non"));
- Element resultImport = ArchiveImporter.getElement(manifeste.query("/m:manifeste/m:resultatimport", ArchiveImporter.getNamespaceCtx()));
- if(resultImport!=null) resultImport.getParent().removeChild(resultImport);
- Element section = ArchiveImporter.getElement(manifeste.query("/m:manifeste/m:section", ArchiveImporter.getNamespaceCtx()));
- if(section!=null) section.getParent().removeChild(section);
- // le /manifeste/fakes sera créé par l'importeur, il faut le supprimer
- Element fakes = ArchiveImporter.getElement(manifeste.query("/m:manifeste/m:fakes", ArchiveImporter.getNamespaceCtx()));
- if(fakes!=null) fakes.getParent().removeChild(fakes);
-
-
- // Suppression dans le referentiel collectivite
-// XmlUtils.showDomInConsole(manifeste, "Manifeste de la base");
- Nodes actionsOnDelete = manifeste.query("//m:on-delete/m:action", ArchiveImporter.getNamespaceCtx());
- for (int compteurAction = 0; compteurAction < actionsOnDelete.size(); compteurAction++) {
- nu.xom.Element action = (nu.xom.Element) actionsOnDelete.get(compteurAction);
- String className = action.getAttributeValue("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;
-
- Nodes parameters = action.query("m:parameter", ArchiveImporter.getNamespaceCtx());
- for (int i = 0; i < parameters.size(); i++) {
- nu.xom.Element param = (nu.xom.Element) parameters.get(i);
- String paramName = param.getAttributeValue("name");
- String type = param.getAttributeValue("type");
- if ("java.lang.String".equals(type)) {
- String value = param.getAttributeValue("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.getAttributeValue("value");
- if (value == null) {
- value = (String) xp.evaluate("./text()", param, XPathConstants.STRING);
- }
- patcher.setParameter(paramName, Integer.valueOf(value));
- }
- }
- patcher.run();
- }
- doImportManifeste(manifeste, manifeste.getRootElement().getAttributeValue("archive-name"));
- } 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();
- }
- }
- protected void doImportManifeste(nu.xom.Document manif, String archiveName) throws IOException {
- DocumentModel dm = getDm().getDocumentById("manifeste2");
- String idColl = "0000";
- String libColl = "Traçabilité";
- String idBudg = "00";
- String libBudg = "--";
-
- Pair collectivite = new Pair(idColl, libColl);
- Pair budget = new Pair(idBudg, libBudg);
- try {
- DataLayerManager.getImplementation().removeDocument(dm, budget, collectivite, archiveName+".xml", user);
- } catch(Exception ex) {
- logger.error("while dropping previous manifeste", ex);
- }
-
- File outputFile = null;
- try {
- outputFile = new File(FileUtils.getTempDir(), archiveName+".xml");
- Charset cs = Charset.forName("UTF-8");
- OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(outputFile),cs);
- osw.write(manif.toXML());
- osw.flush();
- osw.close();
- Class clazz = Class.forName(dm.getImportClass());
- Constructor cc = clazz.getConstructor(XemeliosUser.class, PropertiesExpansion.class);
- Object obj = cc.newInstance(user, applicationProperties);
- if (!(obj instanceof EtatImporteur)) {
- throw new DataConfigurationException("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;
- ImportServiceProvider importServiceProvider = new NullImportServiceProvider();
- ei.setArchiveName(archiveName);
- ei.setImpSvcProvider(importServiceProvider);
- ei.setOverwriteRule("never");
- ei.setApplicationConfiguration(applicationProperties);
-
- ei.setDocument(dm);
- File[] fichiers = new File[]{outputFile};
- ei.setFilesToImport(fichiers);
-
- importServiceProvider.setCollectivite(collectivite);
- importServiceProvider.setBudget(budget);
- ei.setCollectivite(collectivite);
- ei.setBudget(budget);
- importServiceProvider.setEtatImporter(ei);
-
- ei.run();
- FileInfo fInfo = ei.getFileInfo();
- if(ei.getWarningCount()>0)
- fInfo.setWarningCount(ei.getWarningCount());
- return;
- } catch (Exception ex) {
- logger.error("importer", ex);
- return;
- } finally {
- if (outputFile.exists()) {
- outputFile.delete();
- }
- }
- }
-
- 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);
- }
- }
+ private static Logger logger = Logger.getLogger(DlgCleanDatabase.class);
+ private final XemeliosUser user;
+ private final PropertiesExpansion applicationProperties;
+
+ public DlgCleanDatabase(final java.awt.Frame parent, final boolean modal, final DocumentsModel _dm, final DlgChooseDocuments.DIALOG_TYPE dialogType, final XemeliosUser user, final PropertiesExpansion applicationProperties) {
+ super(parent, modal, _dm, true, dialogType, user, MainWindow.getInstance().getEnvProperties());
+ this.user = user;
+ this.applicationProperties = applicationProperties;
+ this.setTitle("Suppression");
+ this.setBActionLibelle("Supprimer");
+ this.setVisible(true);
+ }
+
+ @Override
+ protected void doAction(final ActionEvent evt) {
+ if (this.getJTabbedPane1().getSelectedComponent() instanceof PanelChooseDatabaseDonnees) {
+ this.purge(((PanelChooseDatabaseDonnees) this.getJTabbedPane1().getSelectedComponent()).getJTree1().getSelectionPath());
+ }
+ if (this.getJTabbedPane1().getSelectedComponent() instanceof PanelChooseDatabaseFichier) {
+ this.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) {
+ final ExportableData datas = ((PanelChooseDatabaseFichier) this.getJTabbedPane1().getSelectedComponent()).getData().getData();
+ for (final ExportableData d : datas.getChilds()) {
+ // logger.debug("avant :\n"+d);
+ this.inspectSelectionOfChilds(d);
+ // logger.debug("après:\n"+d);
+ this.purgeData(d);
+ }
+ }
+ }
+
+ protected boolean inspectSelectionOfChilds(final ExportableData d) {
+ if (d.getChilds().size() == 0) {
+ return d.isSelected();
+ } else {
+ boolean hasAllChildsSelected = true;
+ for (final ExportableData dd : d.getChilds()) {
+ hasAllChildsSelected &= this.inspectSelectionOfChilds(dd);
+ }
+ d.setSelected(d.isSelected() || hasAllChildsSelected);
+ return hasAllChildsSelected;
+ }
+ }
+
+ protected void purgeData(final ExportableData datas) {
+ // Si l'on veux supprimer ce niveau
+ if (datas.isSelected()) {
+ this.doSuppressData(datas);
+ } else {
+ for (final ExportableData d : datas.getChilds()) {
+ this.purgeData(d);
+ }
+ }
+ }
+
+ public void doSuppressData(final ExportableData d) {
+ Runnable process = null;
+ // suppression selon le niveau
+ switch (d.getLevel()) {
+ case ExportableData.LVL_DOC: {
+ final DocumentModel dm = this.getDm().getDocumentById(d.getKey());
+ logger.debug("deleting DOC : " + dm.getId());
+ process = new Runnable() {
+
+ @Override
+ public void run() {
+ try {
+ DlgCleanDatabase.this.getGlassPane().setVisible(true);
+ DataLayerManager.getImplementation().removeDocumentModel(dm, DlgCleanDatabase.this.user);
+ } catch (final UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(DlgCleanDatabase.this.getParent(), ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (final DataAccessException daEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, daEx);
+ } catch (final DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, dcEx);
+ } finally {
+ DlgCleanDatabase.this.getGlassPane().setVisible(false);
+ }
+ }
+ };
+ break;
+ }
+ case ExportableData.LVL_COL: {
+ final StringTokenizer st = new StringTokenizer(d.getKey(), "|");
+ final DocumentModel dm = this.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 {
+ DlgCleanDatabase.this.getGlassPane().setVisible(true);
+ DataLayerManager.getImplementation().removeCollectivite(dm, collectivite, DlgCleanDatabase.this.user);
+ } catch (final UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(DlgCleanDatabase.this.getParent(), ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (final DataAccessException daEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, daEx);
+ } catch (final DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, dcEx);
+ } finally {
+ DlgCleanDatabase.this.getGlassPane().setVisible(false);
+ }
+ }
+ };
+ break;
+ }
+ case ExportableData.LVL_BUD: {
+ final StringTokenizer st = new StringTokenizer(d.getKey(), "|");
+ final DocumentModel dm = this.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 {
+ DlgCleanDatabase.this.getGlassPane().setVisible(true);
+ DataLayerManager.getImplementation().removeBudget(dm, collectivite, budget, DlgCleanDatabase.this.user);
+ } catch (final UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(DlgCleanDatabase.this.getParent(), ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (final DataAccessException daEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, daEx);
+ } catch (final DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, dcEx);
+ } finally {
+ DlgCleanDatabase.this.getGlassPane().setVisible(false);
+ }
+ }
+ };
+ break;
+ }
+ case ExportableData.LVL_FIC: {
+ final StringTokenizer st = new StringTokenizer(d.getKey(), "|");
+ final DocumentModel dm = this.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 {
+ DlgCleanDatabase.this.getGlassPane().setVisible(true);
+ DataLayerManager.getImplementation().removeFichier(dm, fichier, DlgCleanDatabase.this.user);
+ } catch (final UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(DlgCleanDatabase.this.getParent(), ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (final DataAccessException daEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, daEx);
+ } catch (final DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, dcEx);
+ } finally {
+ DlgCleanDatabase.this.getGlassPane().setVisible(false);
+ }
+ }
+ };
+ break;
+ }
+ }
+ if (process != null) {
+ logger.debug("deleting");
+ final 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(final TreePath tp) {
+ if (tp == null) {
+ return;
+ }
+ final 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) {
+ this.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) {
+ this.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(final DatabaseTreeDataDonnee.DataNode dn) {
+ final 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 {
+ DlgCleanDatabase.this.getGlassPane().setVisible(true);
+ DataLayerManager.getImplementation().removeDocumentModel(dm, DlgCleanDatabase.this.user);
+ } catch (final UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(DlgCleanDatabase.this.getParent(), ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (final DataAccessException daEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, daEx);
+ } catch (final DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, dcEx);
+ } finally {
+ DlgCleanDatabase.this.getGlassPane().setVisible(false);
+ }
+ }
+ };
+ break;
+ }
+ case DatabaseTreeDataDonnee.DataNode.TYPE_ARCHIVE: {
+ final DatabaseTreeDataDonnee.DataNode node = dn;
+ process = new Runnable() {
+ @Override
+ public void run() {
+ try {
+ final nu.xom.Document manifeste = DataLayerManager.getImplementation().getManifesteFromArchive(((Pair) node.getData()).libelle, DlgCleanDatabase.this.user);
+ if (manifeste != null) {
+ final XPathFactory xpf = FactoryProvider.getXPathFactory();
+ final XPath xp = xpf.newXPath();
+ xp.setNamespaceContext(MainWindow.getInstance().getDocModels().getDocumentById("manifeste2").getNamespaces());
+ final Nodes documentIds = manifeste.query("//m:document/@type", ArchiveImporter.getNamespaceCtx());
+ final HashMap<String, DocumentModel> docsModel = new HashMap<String, DocumentModel>();
+ for (int i = 0; i < documentIds.size(); i++) {
+ String docId = documentIds.get(i).getValue();
+ docId = ArchiveImporter.normalizeDocumentType(docId);
+ if ("PJ".equals(docId)) {
+ docId = null;
+ }
+ if (docId != null && !docsModel.containsKey(docId)) {
+ try {
+ docsModel.put(docId, MainWindow.getInstance().getDocModels().getDocumentById(docId));
+ } catch (final NullPointerException npe) {
+ logger.error("NPE with " + docId);
+ throw npe;
+ }
+ }
+ }
+ DataLayerManager.getImplementation().removeArchive(docsModel, ((Pair) node.getData()).libelle, DlgCleanDatabase.this.user);
+ logger.debug("ici, node.getData().libelle = " + ((Pair) node.getData()).libelle);
+ // Mise à jour du manifeste de l'archive
+ // DataLayerManager.getImplementation().updateManifeste(((Pair)node.getData()).libelle, user);
+ final Nodes documents = manifeste.query("/m:manifeste/m:documents/m:document", ArchiveImporter.getNamespaceCtx());
+ for (int i = 0; i < documents.size(); i++) {
+ final nu.xom.Element doc = (nu.xom.Element) documents.get(i);
+ final nu.xom.Element resultImport = ArchiveImporter.getElement(doc.query("m:resultatimport | resultatimport", ArchiveImporter.getNamespaceCtx()));
+ if (resultImport != null) {
+ doc.removeChild(resultImport);
+ }
+ doc.addAttribute(new Attribute("imported", "Non"));
+ }
+ final nu.xom.Element evt = new Element("evenement");
+ evt.addAttribute(new Attribute("date", DateUtils.formatXsDateTime(new Date())));
+ evt.addAttribute(new Attribute("section", "Suppression complète"));
+ final Element evts = ArchiveImporter.getElement(manifeste.query("/m:manifeste/m:evenements", ArchiveImporter.getNamespaceCtx()));
+ evts.insertChild(evt, 0);
+ manifeste.getRootElement().addAttribute(new Attribute("imported", "Non"));
+ manifeste.getRootElement().addAttribute(new Attribute("added:archive", Constants.ADDED_NS_URI, "Non"));
+ final Element resultImport = ArchiveImporter.getElement(manifeste.query("/m:manifeste/m:resultatimport", ArchiveImporter.getNamespaceCtx()));
+ if (resultImport != null) {
+ resultImport.getParent().removeChild(resultImport);
+ }
+ final Element section = ArchiveImporter.getElement(manifeste.query("/m:manifeste/m:section", ArchiveImporter.getNamespaceCtx()));
+ if (section != null) {
+ section.getParent().removeChild(section);
+ }
+ // le /manifeste/fakes sera créé par l'importeur, il faut le supprimer
+ final Element fakes = ArchiveImporter.getElement(manifeste.query("/m:manifeste/m:fakes", ArchiveImporter.getNamespaceCtx()));
+ if (fakes != null) {
+ fakes.getParent().removeChild(fakes);
+ }
+
+ // Suppression dans le referentiel collectivite
+ // XmlUtils.showDomInConsole(manifeste, "Manifeste de la base");
+ final Nodes actionsOnDelete = manifeste.query("//m:on-delete/m:action", ArchiveImporter.getNamespaceCtx());
+ for (int compteurAction = 0; compteurAction < actionsOnDelete.size(); compteurAction++) {
+ final nu.xom.Element action = (nu.xom.Element) actionsOnDelete.get(compteurAction);
+ final String className = action.getAttributeValue("class");
+ final Class clazz = Class.forName(className);
+ final Object instance = clazz.newInstance();
+ if (!(instance instanceof AbstractImportPatcherImpl)) {
+ throw new Exception(className + " n'est pas un AbstractImportPatcherImpl");
+ }
+ final AbstractImportPatcherImpl patcher = (AbstractImportPatcherImpl) instance;
+
+ final Nodes parameters = action.query("m:parameter", ArchiveImporter.getNamespaceCtx());
+ for (int i = 0; i < parameters.size(); i++) {
+ final nu.xom.Element param = (nu.xom.Element) parameters.get(i);
+ final String paramName = param.getAttributeValue("name");
+ final String type = param.getAttributeValue("type");
+ if ("java.lang.String".equals(type)) {
+ String value = param.getAttributeValue("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.getAttributeValue("value");
+ if (value == null) {
+ value = (String) xp.evaluate("./text()", param, XPathConstants.STRING);
+ }
+ patcher.setParameter(paramName, Integer.valueOf(value));
+ }
+ }
+ patcher.run();
+ }
+ DlgCleanDatabase.this.doImportManifeste(manifeste, manifeste.getRootElement().getAttributeValue("archive-name"));
+ } else {
+ JOptionPane.showMessageDialog(DlgCleanDatabase.this.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 (final UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(DlgCleanDatabase.this.getParent(), ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (final DataAccessException daEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, daEx);
+ } catch (final DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, dcEx);
+ } catch (final XPathExpressionException e) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, e);
+ } catch (final ClassNotFoundException e) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, e);
+ } catch (final InstantiationException e) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, e);
+ } catch (final IllegalAccessException e) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, e);
+ } catch (final Exception e) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, e);
+ } finally {
+ DlgCleanDatabase.this.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 {
+ DlgCleanDatabase.this.getGlassPane().setVisible(true);
+ DataLayerManager.getImplementation().removeCollectivite(dm, collectivite, DlgCleanDatabase.this.user);
+ } catch (final UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(DlgCleanDatabase.this.getParent(), ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (final DataAccessException daEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, daEx);
+ } catch (final DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, dcEx);
+ } finally {
+ DlgCleanDatabase.this.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 {
+ DlgCleanDatabase.this.getGlassPane().setVisible(true);
+ DataLayerManager.getImplementation().removeBudget(dm, collectivite, budget, DlgCleanDatabase.this.user);
+ } catch (final UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(DlgCleanDatabase.this.getParent(), ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (final DataAccessException daEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, daEx);
+ } catch (final DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, dcEx);
+ } finally {
+ DlgCleanDatabase.this.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 {
+ DlgCleanDatabase.this.getGlassPane().setVisible(true);
+ DataLayerManager.getImplementation().removeSpecialKey1(dm, collectivite, budget, perso1, DlgCleanDatabase.this.user);
+ } catch (final UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(DlgCleanDatabase.this.getParent(), ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (final DataAccessException daEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, daEx);
+ } catch (final DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, dcEx);
+ } finally {
+ DlgCleanDatabase.this.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 {
+ DlgCleanDatabase.this.getGlassPane().setVisible(true);
+ DataLayerManager.getImplementation().removeSpecialKey2(dm, collectivite, budget, perso1, perso2, DlgCleanDatabase.this.user);
+ } catch (final UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(DlgCleanDatabase.this.getParent(), ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (final DataAccessException daEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, daEx);
+ } catch (final DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(DlgCleanDatabase.this, dcEx);
+ } finally {
+ DlgCleanDatabase.this.getGlassPane().setVisible(false);
+ }
+ }
+ };
+ break;
+ }
+ }
+ if (process != null) {
+ logger.debug("deleting");
+ final SwingWorker deleter = new Deleter(process, this);
+ deleter.execute();
+ }
+ }
+
+ protected void doImportManifeste(final nu.xom.Document manif, final String archiveName) throws IOException {
+ final DocumentModel dm = this.getDm().getDocumentById("manifeste2");
+ final String idColl = "0000";
+ final String libColl = "Traçabilité";
+ final String idBudg = "00";
+ final String libBudg = "--";
+
+ final Pair collectivite = new Pair(idColl, libColl);
+ final Pair budget = new Pair(idBudg, libBudg);
+ try {
+ DataLayerManager.getImplementation().removeDocument(dm, budget, collectivite, archiveName + ".xml", this.user);
+ } catch (final Exception ex) {
+ logger.error("while dropping previous manifeste", ex);
+ }
+
+ File outputFile = null;
+ try {
+ outputFile = new File(FileUtils.getTempDir(), archiveName + ".xml");
+ final Charset cs = Charset.forName("UTF-8");
+ final OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(outputFile), cs);
+ osw.write(manif.toXML());
+ osw.flush();
+ osw.close();
+ final Class clazz = Class.forName(dm.getImportClass());
+ final Constructor cc = clazz.getConstructor(XemeliosUser.class, PropertiesExpansion.class);
+ final Object obj = cc.newInstance(this.user, this.applicationProperties);
+ if (!(obj instanceof EtatImporteur)) {
+ throw new DataConfigurationException("Cette classe n'est pas un importeur.\nLe fichier de configuration qui vous a été livré est certainement invalide.\nVeuillez contacter votre fournisseur.");
+ }
+ final EtatImporteur ei = (EtatImporteur) obj;
+ final ImportServiceProvider importServiceProvider = new NullImportServiceProvider();
+ ei.setArchiveName(archiveName);
+ ei.setImpSvcProvider(importServiceProvider);
+ ei.setOverwriteRule("never");
+ ei.setApplicationConfiguration(this.applicationProperties);
+
+ ei.setDocument(dm);
+ final File[] fichiers = new File[] { outputFile };
+ ei.setFilesToImport(fichiers);
+
+ importServiceProvider.setCollectivite(collectivite);
+ importServiceProvider.setBudget(budget);
+ ei.setCollectivite(collectivite);
+ ei.setBudget(budget);
+ importServiceProvider.setEtatImporter(ei);
+
+ ei.run();
+ final FileInfo fInfo = ei.getFileInfo();
+ if (ei.getWarningCount() > 0) {
+ fInfo.setWarningCount(ei.getWarningCount());
+ }
+ return;
+ } catch (final Exception ex) {
+ logger.error("importer", ex);
+ return;
+ } finally {
+ if (outputFile.exists()) {
+ outputFile.delete();
+ }
+ }
+ }
+
+ private class Deleter extends SwingWorker {
+
+ private Runnable process = null;
+ private DlgCleanDatabase dlg = null;
+
+ public Deleter(final Runnable process, final DlgCleanDatabase dlg) {
+ super();
+ this.process = process;
+ this.dlg = dlg;
+ }
+
+ @Override
+ public String doInBackground() {
+ this.dlg.enableButtons(false);
+ this.dlg.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
+ this.process.run();
+ return null;
+ }
+
+ @Override
+ public void done() {
+ try {
+ if (DlgCleanDatabase.this.getJTabbedPane1().getSelectedComponent() instanceof PanelChooseDatabaseDonnees) {
+ ((PanelChooseDatabaseDonnees) this.dlg.getJTabbedPane1().getSelectedComponent()).getJTree1().setModel(new DatabaseTreeDataDonnee(DlgCleanDatabase.this.getDm(), this.dlg, DlgCleanDatabase.this.user, MainWindow.getInstance().getEnvProperties()));
+ }
+ if (DlgCleanDatabase.this.getJTabbedPane1().getSelectedComponent() instanceof PanelChooseDatabaseFichier) {
+ ((PanelChooseDatabaseFichier) this.dlg.getJTabbedPane1().getSelectedComponent()).refresh();
+ }
+ } catch (final UnauthorizedException ex) {
+ //
+ }
+ this.dlg.setCursor(Cursor.getDefaultCursor());
+ this.dlg.enableButtons(true);
+ }
+ }
}
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+import java.util.ArrayList;
import java.util.Enumeration;
+import java.util.Hashtable;
+import javax.swing.AbstractAction;
+import javax.swing.Action;
import javax.swing.DefaultCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
+import javax.swing.JOptionPane;
+import javax.swing.JPopupMenu;
import javax.swing.JRootPane;
import javax.swing.JTable;
import javax.swing.JTextField;
+import javax.swing.KeyStroke;
+import javax.swing.SwingConstants;
+import javax.swing.event.TableModelEvent;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.table.DefaultTableCellRenderer;
import org.apache.log4j.Logger;
import org.jdesktop.swingx.JXTreeTable;
+import org.jdesktop.swingx.treetable.AbstractTreeTableModel;
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.EnvironmentDomain;
import fr.gouv.finances.dgfip.xemelios.common.config.Loader;
import fr.gouv.finances.dgfip.xemelios.common.config.ReferenceModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.VariableModel;
+import fr.gouv.finances.dgfip.xemelios.data.DataConfigurationException;
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
+ *
+ * @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);
- }
-
- }
-
- }
+ private static final String TITLE = "Environnement";
+ private static Logger logger = Logger.getLogger(DlgEditEnvironment.class);
+ private final EnvironmentDomain documents;
+ private final TreeTableModel myModel;
+ private final int domain;
+ private Action action;
+ private final Hashtable<String, ValueToSave> valuesToSave;
+ private final ArrayList<String> valuesToRemove;
+ private DocumentsModel defaultConfiguration;
+ private final XemeliosUser user;
+
+ /** Creates new form DlgEditEnvironment */
+ public DlgEditEnvironment(final java.awt.Frame parent, final EnvironmentDomain documents, final int domain, final XemeliosUser user) {
+ super(parent, true);
+ this.setTitle(TITLE);
+ this.documents = documents;
+ this.domain = domain;
+ this.user = user;
+ this.myModel = this.createModel();
+ this.valuesToSave = new Hashtable<String, ValueToSave>();
+ this.valuesToRemove = new ArrayList<String>();
+ if (EnvironmentDomain.DOMAIN_DOCUMENTS == domain) {
+ try {
+ this.defaultConfiguration = Loader.getConfigurationFromLoadedFiles();
+ } catch (final Exception e) {
+ // on peut ici l'ignorer
+ }
+ }
+ this.initComponents();
+ this.setLocationRelativeTo(this.getParent());
+ this.treeTable.setTreeTableModel(this.myModel);
+ if (EnvironmentDomain.DOMAIN_DOCUMENTS != domain) {
+ this.pbSaveValues.setVisible(false);
+ }
+ this.treeTable.addTreeExpansionListener(new TreeExpansionListener() {
+ @Override
+ public void treeCollapsed(final TreeExpansionEvent event) {
+ }
+
+ @Override
+ public void treeExpanded(final TreeExpansionEvent event) {
+ DlgEditEnvironment.this.treeTable.packAll();
+ }
+ });
+ }
+
+ @Override
+ protected JRootPane createRootPane() {
+ final JRootPane rp = super.createRootPane();
+ this.action = new AbstractAction() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ final DlgCore dlg = new DlgCore(MainWindow.instance);
+ dlg.setVisible(true);
+ DlgEditEnvironment.this.setVisible(false);
+ }
+ };
+ rp.getActionMap().put("SS", this.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() {
+
+ this.jScrollPane1 = new javax.swing.JScrollPane();
+ this.treeTable = new JXTreeTablePropertyEditor(this.defaultConfiguration);
+ this.pbOk = new javax.swing.JButton();
+ this.pbSaveValues = new javax.swing.JButton();
+
+ this.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+
+ this.treeTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_LAST_COLUMN);
+ this.jScrollPane1.setViewportView(this.treeTable);
+
+ this.pbOk.setText("Fermer");
+ this.pbOk.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgEditEnvironment.this.pbOkClick(evt);
+ }
+ });
+
+ this.pbSaveValues.setText("Enregistrer");
+ this.pbSaveValues.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgEditEnvironment.this.pbSaveValuesActionPerformed(evt);
+ }
+ });
+
+ final org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this.getContentPane());
+ this.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, this.jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 356, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup().add(this.pbSaveValues).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.pbOk))).addContainerGap()));
+ layout.setVerticalGroup(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(
+ org.jdesktop.layout.GroupLayout.TRAILING,
+ layout.createSequentialGroup().addContainerGap().add(this.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(this.pbOk).add(this.pbSaveValues)).addContainerGap()));
+
+ this.pack();
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void pbOkClick(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbOkClick
+ if (this.treeTable.isEditing()) {
+ this.treeTable.getCellEditor(this.treeTable.getEditingRow(), this.treeTable.getEditingColumn()).stopCellEditing();
+ }
+ this.setVisible(false);
+ }// GEN-LAST:event_pbOkClick
+
+ private void pbSaveValuesActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbSaveValuesActionPerformed
+ final Hashtable<String, Object> values = new Hashtable<String, Object>();
+ for (final String key : this.valuesToSave.keySet()) {
+ final ValueToSave vts = this.valuesToSave.get(key);
+ values.put(key, vts.value);
+ }
+ try {
+ DataLayerManager.getImplementation().saveRedefinedValues(values, this.valuesToRemove, this.user);
+ } catch (final 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(this.documents, this.domain);
+ }
+
+ private class EnvironmentTreeModel extends AbstractTreeTableModel {
+ private final EnvironmentDomain env;
+ private final int domain;
+
+ public EnvironmentTreeModel(final EnvironmentDomain env, final int domain) {
+ super();
+ this.env = env;
+ this.domain = domain;
+ }
+
+ @Override
+ public boolean isLeaf(final Object node) {
+ if (node instanceof EnvironmentDomain) {
+ final EnvironmentDomain ed = (EnvironmentDomain) node;
+ return !(ed.hasEnvironment(this.domain) || ed.getChildCount(this.domain, MainWindow.getInstance().getEnvProperties()) > 0);
+ }
+ return true;
+ }
+
+ @Override
+ public int getChildCount(final Object parent) {
+ if (parent instanceof EnvironmentDomain) {
+ final EnvironmentDomain ed = (EnvironmentDomain) parent;
+ int ret = 0;
+ if (ed.hasEnvironment(this.domain)) {
+ final Enumeration enumer = ed.getVariables(this.domain);
+ while (enumer.hasMoreElements()) {
+ ret++;
+ enumer.nextElement();
+ }
+ }
+ return ed.getChildCount(this.domain, MainWindow.getInstance().getEnvProperties()) + ret;
+ }
+ return 0;
+ }
+
+ @Override
+ public String getColumnName(final int i) {
+ switch (i) {
+ case 0:
+ return "Propriété";
+ case 1:
+ return "Valeur";
+ }
+ return "";
+ }
+
+ @Override
+ public Class getColumnClass(final int i) {
+ if (i == 1) {
+ return String.class;
+ } else {
+ return super.getColumnClass(i);
+ }
+ }
+
+ @Override
+ public Object getValueAt(final Object object, final int i) {
+ if (i == 0) {
+ return object.toString();
+ } else if (object instanceof VariableModel) {
+ final VariableModel vm = (VariableModel) object;
+ try {
+ if (vm.getReference() != null) {
+ return vm.getReference().getValue(this.env);
+ } else {
+ return "<unset>";
+ }
+ } catch (final DataConfigurationException dcEx) {
+ logger.error(dcEx);
+ return dcEx.getMessage();
+ }
+ } else {
+ return "";
+ }
+ }
+
+ @Override
+ public void setValueAt(final Object value, final Object node, final int column) {
+ if (node instanceof VariableModel) {
+ final VariableModel vm = (VariableModel) node;
+ if (vm.getReference() != null) {
+ try {
+ vm.getReference().setValue(this.env, value);
+ final ReferenceModel rm = vm.getReference();
+ DlgEditEnvironment.this.valuesToSave.put(rm.getName(), new ValueToSave(rm, value));
+ DlgEditEnvironment.this.valuesToRemove.remove(rm.getName());
+ } catch (final DataConfigurationException dcEx) {
+ logger.error(dcEx);
+ }
+ }
+ }
+ }
+
+ @Override
+ public Object getChild(final Object parent, final int index) {
+ if (parent instanceof EnvironmentDomain) {
+ final EnvironmentDomain ed = (EnvironmentDomain) parent;
+ final int childCount = ed.getChildCount(this.domain, MainWindow.getInstance().getEnvProperties());
+ if (index < childCount) {
+ return ed.getChildAt(this.domain, index);
+ } else {
+ final int i2 = index - childCount;
+ final Enumeration<VariableModel> enumer = ed.getVariables(this.domain);
+ int count = 0;
+ while (count < i2 && enumer.hasMoreElements()) {
+ enumer.nextElement();
+ count++;
+ }
+ return enumer.nextElement();
+ }
+ } else {
+ return null;
+ }
+ }
+
+ @Override
+ public boolean isCellEditable(final Object object, final int i) {
+ return (i == 1 && object instanceof VariableModel);
+ }
+
+ @Override
+ public int getIndexOfChild(final Object parent, final Object child) {
+ return 0;
+ }
+
+ @Override
+ public Object getRoot() {
+ return this.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(final EnvironmentDomain domain) {
+ super();
+ this.domain = domain;
+ this.booleanEditor = new MyCellEditor(new JCheckBox()) {
+ @Override
+ public Component getTableCellEditorComponent(final JTable table, final Object value, final boolean isSelected, final int row, final int column) {
+ final Component c = super.getTableCellEditorComponent(table, value, isSelected, row, column);
+ final JCheckBox chk = (JCheckBox) this.editorComponent;
+ chk.setSelected(((Boolean) value).booleanValue());
+ chk.setBackground(c.getBackground());
+ chk.addMouseListener(new MouseListener() {
+ @Override
+ public void mouseClicked(final MouseEvent e) {
+ this.maybeShowPopup(e);
+ }
+
+ @Override
+ public void mousePressed(final MouseEvent e) {
+ this.maybeShowPopup(e);
+ }
+
+ @Override
+ public void mouseReleased(final MouseEvent e) {
+ this.maybeShowPopup(e);
+ }
+
+ private void maybeShowPopup(final MouseEvent e) {
+ if (e.isPopupTrigger()) {
+ final JPopupMenu popup = new JPopupMenu();
+ popup.add(new AbstractAction("Valeur par défaut") {
+ @Override
+ public void actionPerformed(final 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(final MouseEvent e) {
+ }
+
+ @Override
+ public void mouseExited(final MouseEvent e) {
+ }
+ });
+ return chk;
+ }
+ };
+ this.integerEditor = new MyCellEditor(new JTextField()) {
+ @Override
+ public Component getTableCellEditorComponent(final JTable table, final Object value, final boolean isSelected, final int row, final int column) {
+ final JTextField txt = (JTextField) this.editorComponent;
+ final EnvironmentDomain defaultConfiguration = JXTreeTablePropertyEditor.this.getDefaultConfiguration();
+ txt.setHorizontalAlignment(SwingConstants.RIGHT);
+ txt.setText(value.toString());
+ txt.addMouseListener(new MouseListener() {
+ @Override
+ public void mouseClicked(final MouseEvent e) {
+ this.maybeShowPopup(e);
+ }
+
+ @Override
+ public void mousePressed(final MouseEvent e) {
+ this.maybeShowPopup(e);
+ }
+
+ @Override
+ public void mouseReleased(final MouseEvent e) {
+ this.maybeShowPopup(e);
+ }
+
+ private void maybeShowPopup(final MouseEvent e) {
+ if (e.isPopupTrigger()) {
+ final JPopupMenu popup = new JPopupMenu();
+ popup.add(new RestoreDefaultValueAction(defaultConfiguration, JXTreeTablePropertyEditor.this.integerEditor));
+ popup.show(e.getComponent(), e.getX(), e.getY());
+ }
+ }
+
+ @Override
+ public void mouseEntered(final MouseEvent e) {
+ }
+
+ @Override
+ public void mouseExited(final MouseEvent e) {
+ }
+ });
+ return txt;
+ }
+ };
+ this.booleanRenderer = new DefaultTableCellRenderer() {
+ private final JCheckBox chk = new JCheckBox();
+
+ @Override
+ public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) {
+ final JLabel lbl = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
+ this.chk.setSelected(((Boolean) value).booleanValue());
+ this.chk.setBackground(lbl.getBackground());
+ this.chk.setBorder(lbl.getBorder());
+ return this.chk;
+ }
+ };
+ this.integerRenderer = new DefaultTableCellRenderer() {
+ @Override
+ public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) {
+ final JLabel txt = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
+ txt.setHorizontalAlignment(SwingConstants.RIGHT);
+ txt.setText(value.toString());
+ return txt;
+ }
+ };
+ }
+
+ private EnvironmentDomain getDefaultConfiguration() {
+ return this.domain;
+ }
+
+ @Override
+ public TableCellEditor getCellEditor(final int row, final int column) {
+ if (column == 1 && this.getTreeTableModel() instanceof EnvironmentTreeModel) {
+ final EnvironmentTreeModel model = (EnvironmentTreeModel) this.getTreeTableModel();
+ final Object node = this.getPathForRow(row).getLastPathComponent();
+ if (node instanceof VariableModel) {
+ final VariableModel vm = (VariableModel) node;
+ final String type = vm.getType();
+ if ("integer".equals(type)) {
+ this.integerEditor.setVm(vm);
+ this.integerEditor.row = row;
+ return this.integerEditor;
+ } else if ("boolean".equals(type)) {
+ this.booleanEditor.setVm(vm);
+ this.booleanEditor.row = row;
+ return this.booleanEditor;
+ }
+ }
+ return super.getCellEditor(row, column);
+ } else {
+ return super.getCellEditor(row, column);
+ }
+ }
+
+ @Override
+ public TableCellRenderer getCellRenderer(final int row, final int column) {
+ if (column == 1 && this.getTreeTableModel() instanceof EnvironmentTreeModel) {
+ final EnvironmentTreeModel model = (EnvironmentTreeModel) this.getTreeTableModel();
+ final Object node = this.getPathForRow(row).getLastPathComponent();
+ if (node instanceof VariableModel) {
+ final VariableModel vm = (VariableModel) node;
+ final String type = vm.getType();
+ if ("integer".equals(type)) {
+ return this.integerRenderer;
+ } else if ("boolean".equals(type)) {
+ return this.booleanRenderer;
+ }
+ }
+ return super.getCellRenderer(row, column);
+ } else {
+ return super.getCellRenderer(row, column);
+ }
+ }
+ }
+
+ private class ValueToSave {
+ Object value;
+
+ public ValueToSave(final ReferenceModel ref, final Object value) {
+ super();
+ this.value = value;
+ }
+ }
+
+ private static class MyCellEditor extends DefaultCellEditor {
+ private VariableModel vm;
+ private int row;
+
+ public VariableModel getVm() {
+ return this.vm;
+ }
+
+ public int getRow() {
+ return this.row;
+ }
+
+ public void setVm(final VariableModel vm) {
+ this.vm = vm;
+ }
+
+ public MyCellEditor(final JCheckBox chk) {
+ super(chk);
+ }
+
+ public MyCellEditor(final JTextField df) {
+ super(df);
+ }
+ }
+
+ private class RestoreDefaultValueAction extends AbstractAction {
+ private final EnvironmentDomain defaultConfiguration;
+ private final MyCellEditor cellEditor;
+
+ public RestoreDefaultValueAction(final EnvironmentDomain defaultConfiguration, final MyCellEditor cellEditor) {
+ super("Rétablir la valeur par défaut");
+ this.defaultConfiguration = defaultConfiguration;
+ this.cellEditor = cellEditor;
+ }
+
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ Object value = null;
+ String path = this.cellEditor.getVm().getReference().getName();
+ if (path.startsWith("/")) {
+ path = path.substring(1);
+ }
+ logger.debug(path);
+ try {
+ value = this.cellEditor.getVm().getReference().getValue(this.defaultConfiguration);
+ if (value != null) {
+ this.cellEditor.getVm().getReference().setValue(DlgEditEnvironment.this.documents, value);
+ this.cellEditor.cancelCellEditing();
+ DlgEditEnvironment.this.treeTable.tableChanged(new TableModelEvent(DlgEditEnvironment.this.treeTable.getModel(), this.cellEditor.getRow()));
+ DlgEditEnvironment.this.valuesToRemove.add(this.cellEditor.getVm().getReference().getName());
+ DlgEditEnvironment.this.valuesToSave.remove(this.cellEditor.getVm().getReference().getName());
+ }
+ } catch (final Throwable t) {
+ logger.error("actionPreformed", t);
+ }
+
+ }
+
+ }
}
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 org.apache.log4j.Logger;
+import fr.gouv.finances.cp.xemelios.ui.export.DlgSearchConfig;
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.DocumentsModel;
+import fr.gouv.finances.dgfip.xemelios.data.DatabaseTreeDataDonnee;
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;
- }
+ private static Logger logger = Logger.getLogger(DlgExportAll.class);
+ private Action escapeAction;
+ private final XemeliosUser user;
+
+ public DlgExportAll(final java.awt.Frame parent, final boolean modal, final DlgChooseDocuments.DIALOG_TYPE dialogType, final DocumentsModel _dm, final XemeliosUser user) {
+ super(parent, modal, _dm, false, dialogType, user, MainWindow.getInstance().getEnvProperties());
+ this.user = user;
+ this.setTitle("Exporter");
+ this.setBActionLibelle("Exporter");
+ final Object o = this.getJTabbedPane1().getComponent(0);
+ if (o instanceof PanelChooseDatabaseFichier) {
+ ((PanelChooseDatabaseFichier) o).setMode(PanelChooseDatabaseFichier.MODE_EXPORT);
+ }
+ }
+
+ @Override
+ protected void doAction(final ActionEvent evt) {
+ if (this.getJTabbedPane1().getSelectedComponent() instanceof PanelChooseDatabaseDonnees) {
+ this.export(((PanelChooseDatabaseDonnees) this.getJTabbedPane1().getSelectedComponent()).getJTree1().getSelectionPath());
+ }
+ if (this.getJTabbedPane1().getSelectedComponent() instanceof PanelChooseDatabaseFichier) {
+ this.exportFichiers();
+ }
+ }
+
+ /**
+ * EXPORT PAR FICHIER
+ */
+ protected void exportFichiers() {
+ final ExportableData datas = ((PanelChooseDatabaseFichier) this.getJTabbedPane1().getSelectedComponent()).getData().getData();
+ for (final ExportableData d : datas.getChilds()) {
+ this.exportData(d);
+ }
+ }
+
+ protected void exportData(final ExportableData datas) {
+ // Si l'on veux exorter ce niveau
+ if (datas.isSelected()) {
+ this.doExportData(datas);
+ } else {
+ for (final ExportableData d : datas.getChilds()) {
+ this.exportData(d);
+ }
+ }
+ }
+
+ public void doExportData(final 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: {
+ final StringTokenizer st = new StringTokenizer(d.getKey(), "|");
+ dm = this.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: {
+ final StringTokenizer st = new StringTokenizer(d.getKey(), "|");
+ dm = this.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) {
+
+ final DocumentsModel dmsTmp = new DocumentsModel(DocumentsModel.QN);
+ try {
+ dmsTmp.addChild(dm, DocumentModel.QN);
+ } catch (final Throwable t) {
+ }
+
+ final DlgSearchConfig sc = new DlgSearchConfig(MainWindow.getInstance(), dmsTmp, DlgSearchConfig.EXEC_FROM_MENU, this.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(final TreePath tp) {
+ if (tp == null) {
+ return;
+ }
+ final DatabaseTreeDataDonnee.DataNode node = (DatabaseTreeDataDonnee.DataNode) tp.getLastPathComponent();
+ this.export(node);
+ }
+
+ /**
+ * Exporte a partir du noeud specifie
+ *
+ * @param dn
+ * @return <tt>true</tt> s'il faut rafraichir l'arbre
+ */
+ protected void export(final DatabaseTreeDataDonnee.DataNode dn) {
+ DocumentModel dm = null;
+ Pair collectivite = null;
+ Pair budget = null;
+ final String fichier = null;
+ Pair perso1 = null;
+ Pair perso2 = null;
+
+ final 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) {
+
+ final DocumentsModel dmsTmp = new DocumentsModel(DocumentsModel.QN);
+ try {
+ dmsTmp.addChild(dm, DocumentModel.QN);
+ } catch (final Throwable t) {
+ }
+
+ final DlgSearchConfig sc = new DlgSearchConfig(MainWindow.getInstance(), dmsTmp, DlgSearchConfig.EXEC_FROM_MENU, this.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() {
+ final KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
+ final JRootPane rp = new JRootPane();
+ this.escapeAction = new AbstractAction("Fermer") {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ DlgExportAll.this.setVisible(false);
+ }
+ };
+ rp.registerKeyboardAction(this.escapeAction, "TOTOTOTO", ks, JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
+ }
}
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
+import javax.swing.SwingConstants;
import org.apache.log4j.Logger;
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.
+ * 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;
- }
-
-
- }
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 3256721779816151348L;
+ private static final Logger logger = Logger.getLogger((DlgSelectRequest.class));
+ private Action escapeAction;
+ private final 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(final MainWindow parent, final Vector<? extends ListDisplayable> data, final ElementModel elementModel) {
+ super(parent, true);
+ this.data = data;
+ this.parentFrame = parent;
+ this.elementModel = elementModel;
+ this.initComponents();
+ }
+
+ protected void initComponents() {
+ final int sepInfo = 2; // 2
+ final int lineInfo = sepInfo + 2; // 4
+ final int sepData = lineInfo + 2; // 6
+ final int listLine = sepData + 2; // 8
+ final int buttonLine1 = listLine + 2; // 10
+
+ JTextArea area = null;
+
+ final 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
+ final CellConstraints cc = new CellConstraints();
+ final PanelBuilder pb = new PanelBuilder(fl);
+ // IhmFactory iF=IhmFactory.newInstance();
+ // final JTree tree = new JTree(new DatabaseTreeData(dm,wrapper));
+ this.list = new JList(this.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(this.list), cc.xy(3, listLine, "fill, fill"));
+
+ final JButton pbOk = new JButton("Ok");
+
+ final JPanel bPane = new JPanel(new FlowLayout(FlowLayout.CENTER));
+ bPane.add(pbOk);
+ bPane.add(pbCancel = new JButton(this.escapeAction));
+
+ pb.add(bPane, cc.xyw(2, buttonLine1, 2));
+
+ area.setEditable(false);
+ area.setLineWrap(true);
+ area.setRows(3);
+ area.setBackground(this.getBackground());
+ area.setText("Sélectionnez dans la liste ci-dessous\n" + "la recherche que vous souhaitez réafficher.");
+
+ this.list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
+ this.list.setCellRenderer(new MyCellRenderer());
+ this.list.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(final 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()) {
+ final Point clickPos = evt.getPoint();
+ final int index = DlgSelectRequest.this.list.locationToIndex(clickPos);
+ final ListDisplayable ld = (ListDisplayable) DlgSelectRequest.this.list.getModel().getElementAt(index);
+ if (ld.isDeletable()) {
+ final JPopupMenu pm = new JPopupMenu();
+ final JMenuItem mnu = new JMenuItem("Supprimer cette requête");
+ mnu.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ if (JOptionPane.showConfirmDialog(DlgSelectRequest.this, "Voulez-vous vraiment supprimer cette requête :\n" + ld.getDisplayName() + " ?") == JOptionPane.YES_OPTION) {
+ logger.debug("suppression");
+ final RechercheModel rm = (RechercheModel) ld;
+ DlgSelectRequest.this.parentFrame.getSavedRequest(DlgSelectRequest.this.elementModel).delete(rm);
+ DlgSelectRequest.this.data.remove(rm);
+ DlgSelectRequest.this.list.setListData(DlgSelectRequest.this.data);
+ }
+ }
+ });
+ pm.add(mnu);
+ pm.show(DlgSelectRequest.this.list, clickPos.x, clickPos.y);
+ }
+ }
+ }
+ });
+ this.getRootPane().setDefaultButton(pbCancel);
+
+ this.setContentPane(pb.getPanel());
+
+ pbOk.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ if (DlgSelectRequest.this.list.getSelectedValue() != null) {
+ DlgSelectRequest.this.ret = true;
+ DlgSelectRequest.this.setVisible(false);
+ }
+ }
+ });
+
+ this.pack();
+ this.setLocationRelativeTo(this.getParent());
+ }
+
+ public boolean run() {
+ this.setVisible(true);
+ return this.ret;
+ }
+
+ public Object getSelectedItem() {
+ return this.list.getSelectedValue();
+ }
+
+ @Override
+ protected JRootPane createRootPane() {
+ final KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
+ final JRootPane rp = new JRootPane();
+ this.escapeAction = new AbstractAction("Annuler") {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ DlgSelectRequest.this.setVisible(false);
+ }
+ };
+ rp.registerKeyboardAction(this.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(final JList list, final Object value, final int index, final boolean isSelected, final boolean cellHasFocus) {
+ final JLabel ancestor = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
+ final 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, SwingConstants.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;
+ }
+
+ }
}
*/
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.Toolkit;
+import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.util.Set;
import java.util.StringTokenizer;
+import javax.swing.AbstractAction;
+import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComboBox;
+import javax.swing.JComponent;
import javax.swing.JInternalFrame;
import javax.swing.JTextField;
import javax.swing.JToolBar;
+import javax.swing.KeyStroke;
import javax.swing.text.html.FormSubmitEvent;
import org.apache.log4j.Logger;
+import org.w3c.dom.DocumentFragment;
+import org.xhtmlrenderer.context.StyleReference;
+import org.xhtmlrenderer.pdf.ITextOutputDevice;
import org.xhtmlrenderer.pdf.ITextRenderer;
+import org.xhtmlrenderer.pdf.ITextUserAgent;
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 org.xhtmlrenderer.swing.SelectionHighlighter;
+
+import com.lowagie.text.DocumentException;
-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.cp.xemelios.ui.xhtmlviewer.XemeliosUserAgent;
+import fr.gouv.finances.cp.xemelios.ui.xhtmlviewer.XemeliosXhtmlPanel;
+import fr.gouv.finances.dgfip.utils.Dest;
+import fr.gouv.finances.dgfip.utils.NavigationContext;
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;
-
- /**
+ 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 final MainWindow mainWindow;
+ private JButton pbPrint, pbPrevious, pbNext;
+ private XemeliosUserAgent userAgent = null;
+ private JComboBox cbxZoom;
+ private ScaleFactor[] availableScales;
+ 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();
- }
- }
+ public HtmlViewer(final URL documentToDisplay, final String title, final NavigationContext nc, final MainWindow mw) {
+ this(documentToDisplay, title, mw);
+ }
+
+ public HtmlViewer(final URL documentToDisplay, final String title, final MainWindow mw) {
+ super(title, true, true, true, true);
+ this.documentUrl = documentToDisplay;
+ this.mainWindow = mw;
+ this.userAgent = new XemeliosUserAgent(this.mainWindow, this, this, this.mainWindow.getConnectedUser());
+ this.xhtmlRenderer = new XemeliosXhtmlPanel(this.userAgent, this);
+ this.initializeComponents();
+ this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
+ }
+
+ public HtmlViewer(final String uri, final String title, final MainWindow mw) {
+ super(title, true, true, true, true);
+ this.mainWindow = mw;
+ this.userAgent = new XemeliosUserAgent(this.mainWindow, this, this, this.mainWindow.getConnectedUser());
+ this.xhtmlRenderer = new XemeliosXhtmlPanel(this.userAgent, this);
+ this.initializeComponents();
+ this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
+ final Dest dest = this.userAgent.calculateQuery(uri);
+ try {
+ this.browseUrl(dest);
+ } catch (final Throwable t) {
+ logger.error("in HtmlViewer(String,String,MainWindow)", t);
+ }
+ }
+
+ public static ScaleFactor[] initializeScales() {
+ final 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(final ScaleChangeEvent evt) {
+ if (evt.getComponent() == this.xhtmlRenderer) {
+ final double scale = evt.getScale();
+ logger.debug("received scaleChanged with " + scale);
+ int ix = -1;
+ for (int i = 0; i < this.availableScales.length; i++) {
+ final ScaleFactor sf = this.availableScales[i];
+ if (sf.getFactor() == scale) {
+ ix = i;
+ break;
+ }
+ }
+ final ItemListener[] iListeners = this.cbxZoom.getItemListeners();
+ for (final ItemListener il : iListeners) {
+ this.cbxZoom.removeItemListener(il);
+ }
+ if (ix == -1) {
+ // TODO
+ final int scalePolicy = this.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;
+ }
+ }
+ this.cbxZoom.setSelectedIndex(ix);
+ for (final ItemListener il : iListeners) {
+ this.cbxZoom.addItemListener(il);
+ }
+ }
+ }
+
+ protected void initializeComponents() {
+ final ScaleFactor[] scales = initializeScales();
+ this.availableScales = scales;
+ final IhmFactory iF = IhmFactory.newInstance();
+ final MouseListener[] lls = this.xhtmlRenderer.getMouseListeners();
+ for (final MouseListener ll : lls) {
+ if (ll instanceof LinkListener) {
+ this.xhtmlRenderer.addMouseMotionListener((MouseMotionListener) ll);
+ }
+ }
+ if (IS_SELECTION_ENABLED) {
+ this.highlighter = new SelectionHighlighter();
+ this.highlighter.install(this.xhtmlRenderer);
+ this.xhtmlRenderer.addMouseListener(this.highlighter);
+ }
+ FSScrollPane scroller;
+ this.getContentPane().setLayout(new BorderLayout());
+ final JToolBar tb = new JToolBar();
+ tb.add(this.pbPrevious = new JButton(IhmFactory.getIconFromResource(ImageResources.BRW_PREVIOUS)));
+ tb.add(this.pbNext = new JButton(IhmFactory.getIconFromResource(ImageResources.BRW_NEXT)));
+ tb.add(this.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(final ActionEvent e) {
+ final DocumentFragment df = HtmlViewer.this.highlighter.getSelectionRange().extractContents();
+ final StringSelection ss = new StringSelection(XmlUtils.getStringRepresentation(df));
+ Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, ss);
+ }
+ };
+ tb.add(this.pbCopy = new JButton(copyAction));
+ this.pbCopy.setToolTipText("Copier");
+
+ final Action selectAllAction = new AbstractAction(null, IhmFactory.getIconFromResource(ImageResources.EDIT_SELECT_ALL)) {
+
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ HtmlViewer.this.highlighter.selectAll();
+ }
+ };
+ final JButton pbSelectAll = new JButton(selectAllAction);
+ pbSelectAll.setToolTipText("Tout sélectionner");
+ tb.add(pbSelectAll);
+
+ this.getRootPane().registerKeyboardAction(copyAction, "copy", KeyStroke.getKeyStroke("ctrl C"), JComponent.WHEN_IN_FOCUSED_WINDOW);
+ this.getRootPane().registerKeyboardAction(selectAllAction, "selectAll", KeyStroke.getKeyStroke("ctrl A"), JComponent.WHEN_IN_FOCUSED_WINDOW);
+ }
+ tb.addSeparator();
+ tb.add(iF.newLabel("URL ", "normal"));
+ tb.add(this.dfUrl = new JTextField());
+ this.dfUrl.setEditable(false);
+ final Dimension dim = this.dfUrl.getMinimumSize();
+ this.dfUrl.setMinimumSize(new Dimension(100, (int) dim.getHeight()));
+ tb.addSeparator();
+ tb.add(iF.newLabel("Zoom ", "normal"));
+ this.cbxZoom = new JComboBox(scales);
+ // TODO
+ this.cbxZoom.addItemListener(new ItemListener() {
+
+ @Override
+ public void itemStateChanged(final ItemEvent e) {
+ if (e.getStateChange() == ItemEvent.SELECTED) {
+ final ScaleFactor factor = (ScaleFactor) e.getItem();
+ if (factor.getFactor() == ScaleFactor.PAGE_WIDTH) {
+ HtmlViewer.this.xhtmlRenderer.setScalePolicy(ScalableXHTMLPanel.SCALE_POLICY_FIT_WIDTH);
+ HtmlViewer.this.xhtmlRenderer.doLayout();
+ } else if (factor.getFactor() == ScaleFactor.PAGE_HEIGHT) {
+ HtmlViewer.this.xhtmlRenderer.setScalePolicy(ScalableXHTMLPanel.SCALE_POLICY_FIT_HEIGHT);
+ HtmlViewer.this.xhtmlRenderer.doLayout();
+ } else if (factor.getFactor() == ScaleFactor.PAGE_WHOLE) {
+ HtmlViewer.this.xhtmlRenderer.setScalePolicy(ScalableXHTMLPanel.SCALE_POLICY_FIT_WHOLE);
+ HtmlViewer.this.xhtmlRenderer.doLayout();
+ } else {
+ HtmlViewer.this.xhtmlRenderer.setScale(factor.getFactor());
+ }
+ }
+ }
+ });
+ this.cbxZoom.setSelectedIndex(2);
+ tb.add(this.cbxZoom);
+ this.getContentPane().add(tb, BorderLayout.PAGE_START);
+ this.getContentPane().add(scroller = new FSScrollPane(this.xhtmlRenderer), BorderLayout.CENTER);
+ scroller.setPreferredSize(new Dimension(LOCAL_WIDTH, LOCAL_HEIGHT));
+ scroller.setIgnoreRepaint(false);
+ this.pbPrint.addActionListener(new ActionListener() {
+
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ HtmlViewer.this.printToPDF();
+ }
+ });
+ this.pbPrint.setToolTipText("Imprimer");
+ this.pbPrevious.addActionListener(new ActionListener() {
+
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ HtmlViewer.this.goBack();
+ }
+ });
+ this.pbNext.addActionListener(new ActionListener() {
+
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ HtmlViewer.this.goForward();
+ }
+ });
+ this.pbPrevious.setEnabled(false);
+ this.pbNext.setEnabled(false);
+ if (this.documentUrl != null) {
+ try {
+ this.browseUrl(this.documentUrl, INTERNAL_DESTINATION);
+ } catch (final Throwable t) {
+ }
+ }
+ this.pack();
+ }
+
+ protected void printToPDF() {
+ try {
+ final File tmp = File.createTempFile("xemelios-data-", ".pdf", FileUtils.getTempDir());
+ final OutputStream os = new FileOutputStream(tmp);
+ final ITextRenderer renderer = new ITextRenderer();
+ final CustomUserAgentCallback callback = new CustomUserAgentCallback(renderer.getOutputDevice());
+ callback.setSharedContext(renderer.getSharedContext());
+ renderer.getSharedContext().setUserAgentCallback(callback);
+ final StyleReference css = new StyleReference(callback);
+ String url = this.dfUrl.getText();
+ if (url.indexOf("#") > 0) {
+ url = url.substring(0, url.indexOf("#"));
+ }
+ final 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 (final IOException ioEx) {
+ logger.error("while printing to PDF: ", ioEx);
+ } catch (final ToolException tEx) {
+ logger.error("while printing to PDF: ", tEx);
+ } catch (final URISyntaxException uriEx) {
+ logger.error("while printing to PDF: ", uriEx);
+ } catch (final DocumentException docEx) {
+ logger.error("while printing to PDF: ", docEx);
+ }
+ }
+
+ protected void browseUri(final URI uri) throws ToolException {
+ final String query = uri.getQuery();
+ final Dest dest = this.userAgent.calculateQuery(query);
+ this.browseUrl(dest);
+ }
+
+ protected void browseUrl(final Dest dest) throws ToolException {
+ this.browseUrl(dest.url, dest.toExternal);
+ }
+
+ protected void browseUrl(final URL url, final boolean toExternalDestination) throws ToolException {
+ try {
+ if (toExternalDestination) {
+ StartUrl.startUrl(url.toExternalForm());
+ } else {
+ final String eForm = url.toExternalForm();
+ this.dfUrl.setText(eForm);
+ this.xhtmlRenderer.setDocument(eForm);
+ }
+ } catch (final Exception ioEx) {
+ throw new ToolException(ioEx, ToolException.ERROR_INVALID_XHTML);
+ }
+ }
+
+ protected Dest browseFormSubmission(final FormSubmitEvent fse) throws UnsupportedEncodingException {
+ final StringTokenizer st = new StringTokenizer(fse.getData(), "&");
+ final Hashtable<String, String> params = new Hashtable<String, String>();
+ while (st.hasMoreTokens()) {
+ final String token = st.nextToken();
+ final int pos = token.indexOf('=');
+ final String paramName = token.substring(0, pos);
+ final 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) {
+ final Set<String> keys = params.keySet();
+ final Set<String> toRemove = new HashSet<String>();
+ for (final 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 (final String key : params.keySet()) {
+ path = path + key + "=" + params.get(key) + "&";
+ }
+ path = path.substring(0, path.length() - 1);
+ return this.userAgent.calculateQuery(path);
+ }
+
+ /**
+ * Opens designed page in external browser by filtering it through outputter.xsl
+ *
+ * @param page
+ * The page to open
+ */
+ protected void output(final NavigationContext ctx) {
+ final Hashtable<String, Object> params = new Hashtable<String, Object>();
+ params.put(PARAM_DESTINATION, VALUE_DESTINATION_EXTERNAL);
+ final Dest dest = this.userAgent.generateDestContext(ctx, params, EXTERNAL_DESTINATION);
+ try {
+ this.browseUrl(dest.url, EXTERNAL_DESTINATION);
+ } catch (final ToolException tEx) {
+ // on se fout que le xhtml ne soit pas bon, c'est le probleme du browser
+ }
+ }
+
+ protected void goBack() {
+ if (this.userAgent.hasBack()) {
+ this.xhtmlRenderer.setDocument(this.userAgent.getBack());
+ } else {
+ this.updateToolbarButtons();
+ }
+ }
+
+ protected void goForward() {
+ if (this.userAgent.hasForward()) {
+ this.xhtmlRenderer.setDocument(this.userAgent.getForward());
+ } else {
+ this.updateToolbarButtons();
+ }
+ }
+
+ @Override
+ public void updateToolbarButtons() {
+ this.pbPrevious.setEnabled(this.userAgent.hasBack());
+ this.pbNext.setEnabled(this.userAgent.hasForward());
+ }
+
+ @Override
+ public void setBaseUrl(final String url) {
+ this.dfUrl.setText(url);
+ }
+
+ class CustomUserAgentCallback extends ITextUserAgent {
+
+ public CustomUserAgentCallback(final ITextOutputDevice outputDevice) {
+ super(outputDevice);
+ }
+
+ @Override
+ public String resolveURI(final String uri) {
+ if (uri.startsWith("xemelios:")) {
+ String servlet = null;
+ String sTmp = uri;
+ final 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 {
+ final File resourceDir = new File(HtmlViewer.this.mainWindow.getEnvProperties().getProperty("xemelios.resources.location"));
+ final File res = new File(resourceDir, sTmp);
+ ret = res.toURI().toURL().toExternalForm();
+ } catch (final 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 final Double factor;
+ private final String libelle;
+
+ public ScaleFactor(final double factor, final String libelle) {
+ super();
+ this.factor = new Double(factor);
+ this.libelle = libelle;
+ }
+
+ public double getFactor() {
+ return this.factor.doubleValue();
+ }
+
+ public String getLibelle() {
+ return this.libelle;
+ }
+
+ @Override
+ public String toString() {
+ return this.getLibelle();
+ }
+ }
}
*/
package fr.gouv.finances.cp.xemelios.ui;
-import fr.gouv.finances.dgfip.xemelios.common.config.Loader;
-import fr.gouv.finances.dgfip.xemelios.utils.Errors;
-import fr.gouv.finances.dgfip.xemelios.tools.AbstractTool;
import java.awt.BorderLayout;
+import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.DisplayMode;
+import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.event.WindowEvent;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
+import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
+import java.io.OutputStreamWriter;
+import java.io.PrintWriter;
import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.net.UnknownHostException;
+import java.nio.charset.Charset;
+import java.sql.Connection;
+import java.text.SimpleDateFormat;
import java.util.ArrayList;
+import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
-import java.util.Iterator;
import java.util.List;
+import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
+import java.util.jar.JarFile;
+import java.util.jar.Manifest;
+import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
+import javax.swing.Timer;
+import javax.swing.WindowConstants;
import javax.swing.border.EtchedBorder;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileSystemView;
import javax.xml.parsers.DocumentBuilder;
+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.apache.log4j.xml.DOMConfigurator;
import org.jdesktop.swingworker.SwingWorker;
+import org.netbeans.api.wizard.WizardDisplayer;
+import org.netbeans.spi.wizard.Wizard;
import org.netbeans.spi.wizard.WizardException;
+import org.netbeans.spi.wizard.WizardPage;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.xeustechnologies.jcl.JarClassLoader;
-import fr.gouv.finances.dgfip.utils.NavigationContext;
-import fr.gouv.finances.dgfip.utils.Pair;
-import fr.gouv.finances.dgfip.utils.Xslt;
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.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.ui.admin.DlgSystemConfiguration;
import fr.gouv.finances.cp.xemelios.ui.collectivites.DlgSelectNavigationTarget;
import fr.gouv.finances.cp.xemelios.utils.ConfigurationReportBuilder;
import fr.gouv.finances.dgfip.utils.ClassPathUtils;
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.Xslt;
import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
-import fr.gouv.finances.dgfip.utils.xml.transform.CustomURIResolver;
+import fr.gouv.finances.dgfip.utils.xml.transform.AbstractURIResolver;
import fr.gouv.finances.dgfip.xemelios.auth.AuthEngine;
import fr.gouv.finances.dgfip.xemelios.auth.UnauthorizedException;
+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.Loader;
+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.dgfip.xemelios.controls.core.MainControl;
+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.data.impl.pool.Pool;
import fr.gouv.finances.dgfip.xemelios.data.impl.pool.PoolManager;
+import fr.gouv.finances.dgfip.xemelios.importers.EtatImporteur;
import fr.gouv.finances.dgfip.xemelios.importers.archives.ArchiveImporter;
+import fr.gouv.finances.dgfip.xemelios.tools.AbstractTool;
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.Errors;
import fr.gouv.finances.dgfip.xemelios.utils.FileUtils;
import fr.gouv.finances.dgfip.xemelios.utils.XemeliosUtils;
-import java.awt.Color;
-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.lang.reflect.Method;
-import java.net.URL;
-import java.net.URLClassLoader;
-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;
-import org.xeustechnologies.jcl.JarClassLoader;
/**
* Main Xemelios window
private Action actQuitter;
private JDesktopPane desk;
// private JTextField statusField;
- private StartListener startListener;
+ private final StartListener startListener;
private DocumentsModel docModels;
protected File lastInputDirectory = null;
private JMenu searchMenu;
private JMenuItem mnuClean = null;
private JMenuItem mnuExporterFichier = null;
private JMenuItem mnuSupprimer = null;
- private JMenu mnuConfigExports = null;
+ private final JMenu mnuConfigExports = null;
private JLabel backImage;
// private JWaiter waiter;
private PersonnalConfigurationModel config;
public XPathFactory xpf;
private Properties criteriasInputValues;
// private String updateUrl; // componentsModelFileName,
- private PropertiesExpansion applicationProperties;
+ private final PropertiesExpansion applicationProperties;
private PnlUpdaterProgress pup;
// le panel dans lequel on vient mettre tout ce qui doit être à droite
private JPanel indicatorPanel;
*/
public static String fieldSeparator = ";";
- public MainWindow(PropertiesExpansion applicationProperties, String title, StartListener sl, String[] args) {
+ public MainWindow(final PropertiesExpansion applicationProperties, final String title, final StartListener sl, final String[] args) {
super(title);
this.applicationProperties = applicationProperties;
String updateConfig = applicationProperties.getProperty(Constants.SYS_PROP_MAJ_CONFIG);
if (!(Constants.MAJ_PROD.equals(updateConfig))) {
updateConfig = (updateConfig == null ? "DEVELOPPEMENT" : updateConfig);
}
- setTitle(title + " - " + updateConfig);
- if (instance != null) {
+ this.setTitle(title + " - " + updateConfig);
+ if (MainWindow.instance != null) {
throw new RuntimeException("Only one instance of MainWindow can exists");
}
- instance = this;
+ MainWindow.instance = this;
this.startListener = sl;
- startListener.pushProgress();
- xpf = FactoryProvider.getXPathFactory();
+ this.startListener.pushProgress();
+ this.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));
+ this.loadConfig();
+ this.startListener.pushProgress();
+ this.checkUpdateScript();
+ this.startListener.pushProgress();
+ this.initComponents();
+ this.startListener.pushProgress();
+ final Properties homeProperties = this.getHomeProperties();
+ if (this.lastInputDirectory == null && homeProperties.getProperty(Constants.SYS_PROP_LAST_INPUT_DIRECTORY) != null && homeProperties.getProperty(Constants.SYS_PROP_LAST_INPUT_DIRECTORY).length() > 0) {
+ this.lastInputDirectory = new File(homeProperties.getProperty(Constants.SYS_PROP_LAST_INPUT_DIRECTORY));
}
try {
- if (!checkPassword()) {
- startListener.completeProgress();
- runExit();
+ if (!this.checkPassword()) {
+ this.startListener.completeProgress();
+ this.runExit();
}
- } catch (Throwable t) {
+ } catch (final Throwable t) {
new DisplayExceptionDlg(this, t);
- runExit();
+ this.runExit();
}
- initMenus2();
- setMenusAccess();
- startListener.pushProgress();
+ this.initMenus2();
+ this.setMenusAccess();
+ this.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(this.getEnvProperties().getProperty(Constants.SYS_PROP_FIRST_START))) {
+ this.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();
+ this.checkUpdateAvailability();
}
}
- startListener.completeProgress();
+ this.startListener.completeProgress();
if (args.length > 0) {
- starterImport(args);
+ this.starterImport(args);
}
- } catch (DataConfigurationException dcEx) {
+ } catch (final DataConfigurationException dcEx) {
Throwable ex = dcEx;
while (ex.getCause() != null) {
ex = ex.getCause();
}
ex.printStackTrace();
- logger.error("<init>", dcEx);
+ MainWindow.logger.error("<init>", dcEx);
System.exit(1);
}
}
* @throws DataConfigurationException
*/
protected void loadConfig() throws DataConfigurationException {
- if (applicationProperties.getProperty(Constants.SYS_PROP_LOG4J) != null) {
- String log4jConfFile = applicationProperties.getProperty(Constants.SYS_PROP_LOG4J);
+ if (this.applicationProperties.getProperty(Constants.SYS_PROP_LOG4J) != null) {
+ final String log4jConfFile = this.applicationProperties.getProperty(Constants.SYS_PROP_LOG4J);
DOMConfigurator.configure(log4jConfFile);
- logger = Logger.getLogger(this.getClass());
- logger.info("log4J initialise");
+ MainWindow.logger = Logger.getLogger(this.getClass());
+ MainWindow.logger.info("log4J initialise");
}
// 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");
+ this.docModels = this.getDocumentsInfos(this.applicationProperties.getProperty(Constants.SYS_PROP_DOC_DEF_DIR));
+ this.initDataLayer();
+ this.applyPatches();
+ MainWindow.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");
+ MainWindow.logger.debug("we must configure first auth-engine");
Connection con = null;
try {
con = PoolManager.getInstance().getConnection();
- if (XemeliosUtils.isLocalComputerServer(con) || "true".equals(applicationProperties.getProperty(Constants.SYS_PROP_FORCE_DB_UPGRADE))) {
- logger.debug("we are on server");
+ if (XemeliosUtils.isLocalComputerServer(con) || "true".equals(this.applicationProperties.getProperty(Constants.SYS_PROP_FORCE_DB_UPGRADE))) {
+ MainWindow.logger.debug("we are on server");
// on est dans le cas où on démarre pour le première fois sur le serveur
try {
- Class clazz = Class.forName("fr.gouv.finances.dgfip.xemelios.auth.impl.std.db.ui.DlgConfigAuthentication");
- Constructor cc = clazz.getConstructor(java.awt.Frame.class, boolean.class, String.class, PropertiesExpansion.class);
- Object o = cc.newInstance(null, true, null, getEnvProperties());
- Method meth = clazz.getMethod("run");
- Object retVal = meth.invoke(o);
- boolean ret = ((Boolean) retVal).booleanValue();
+ final Class clazz = Class.forName("fr.gouv.finances.dgfip.xemelios.auth.impl.std.db.ui.DlgConfigAuthentication");
+ final Constructor cc = clazz.getConstructor(java.awt.Frame.class, boolean.class, String.class, PropertiesExpansion.class);
+ final Object o = cc.newInstance(null, true, null, this.getEnvProperties());
+ final Method meth = clazz.getMethod("run");
+ final Object retVal = meth.invoke(o);
+ final boolean ret = ((Boolean) retVal).booleanValue();
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);
+ MainWindow.logger.debug("DlgConfigAuthentication.run terminated");
+ } catch (final Throwable t) {
+ MainWindow.logger.error("paramétrage authentification", t);
}
} else {
- logger.debug("we are on client");
+ MainWindow.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");
}
}
}
try {
- AuthEngine.Holder.init(applicationProperties);
- } catch (RuntimeException re) {
+ AuthEngine.Holder.init(this.applicationProperties);
+ } catch (final 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();
+ MainWindow.logger.debug("Loading personnal config");
+ this.loadPersonnalConfig();
}
protected void initComponents() {
- criteriasInputValues = loadCriteriasInputValues();
- IhmFactory iF = IhmFactory.newInstance();
- initActions();
- startListener.pushProgress();
- desk = new JDesktopPane();
- desk.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
- 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);
- Color background = desk.getBackground();
- String updateSource = applicationProperties.getProperty(Constants.SYS_PROP_MAJ_CONFIG);
- if ("PRIVATE".equals(updateSource))
+ this.criteriasInputValues = this.loadCriteriasInputValues();
+ final IhmFactory iF = IhmFactory.newInstance();
+ this.initActions();
+ this.startListener.pushProgress();
+ this.desk = new JDesktopPane();
+ this.desk.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
+ final ImageIcon image = IhmFactory.getIconFromResource(ImageResources.SPLASH); // fond 3
+ this.backImage = new JLabel(image);
+ this.backImage.setBounds(0, 0, image.getIconWidth(), image.getIconHeight());
+ this.desk.add(this.backImage, JLayeredPane.FRAME_CONTENT_LAYER);
+ Color background = this.desk.getBackground();
+ final String updateSource = this.applicationProperties.getProperty(Constants.SYS_PROP_MAJ_CONFIG);
+ if ("PRIVATE".equals(updateSource)) {
background = Color.RED;
- else if ("RECETTE".equals(updateSource))
+ } else if ("RECETTE".equals(updateSource)) {
background = Color.ORANGE;
- desk.setBackground(background);
- initMenus1();
- startListener.pushProgress();
- addWindowListener(new WindowAdapter() {
+ }
+ this.desk.setBackground(background);
+ this.initMenus1();
+ this.startListener.pushProgress();
+ this.addWindowListener(new WindowAdapter() {
@Override
- public void windowClosed(WindowEvent e) {
+ public void windowClosed(final WindowEvent e) {
}
@Override
- public void windowClosing(WindowEvent e) {
- runExit();
- logger.debug("closing");
+ public void windowClosing(final WindowEvent e) {
+ MainWindow.this.runExit();
+ MainWindow.logger.debug("closing");
}
});
- startListener.pushProgress();
- JPanel inner = new JPanel(new BorderLayout());
- JPanel status = new JPanel(new BorderLayout());
- startListener.pushProgress();
+ this.startListener.pushProgress();
+ final JPanel inner = new JPanel(new BorderLayout());
+ final JPanel status = new JPanel(new BorderLayout());
+ this.startListener.pushProgress();
// status.add(statusField = new JTextField(30), BorderLayout.WEST);
- startListener.pushProgress();
+ this.startListener.pushProgress();
// statusField.setEditable(false);
// statusField.setBorder(new EmptyBorder(0, 0, 0, 0));
- startListener.pushProgress();
- indicatorPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
+ this.startListener.pushProgress();
+ this.indicatorPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
// indicatorPanel.add(waiter = new JWaiter());
- status.add(indicatorPanel, BorderLayout.EAST);
+ status.add(this.indicatorPanel, BorderLayout.EAST);
boolean debugUI = false;
- status.add(indicatorPanel, BorderLayout.EAST);
- if ("true".equals(applicationProperties.getProperty(Constants.SYS_PROP_ADMIN_MENU_GC))) {
- indicatorPanel.add(new RamViewer());
+ status.add(this.indicatorPanel, BorderLayout.EAST);
+ if ("true".equals(this.applicationProperties.getProperty(Constants.SYS_PROP_ADMIN_MENU_GC))) {
+ this.indicatorPanel.add(new RamViewer());
debugUI = true;
}
- if ("true".equals(applicationProperties.getProperty(Constants.SYS_PROP_SHOW_POOL_STATUS))) {
- indicatorPanel.add(new PoolStatDisplayer());
+ if ("true".equals(this.applicationProperties.getProperty(Constants.SYS_PROP_SHOW_POOL_STATUS))) {
+ this.indicatorPanel.add(new PoolStatDisplayer());
debugUI = true;
}
- startListener.pushProgress();
- pup = new PnlUpdaterProgress(this);
- pup.setVisible(false);
+ this.startListener.pushProgress();
+ this.pup = new PnlUpdaterProgress(this);
+ this.pup.setVisible(false);
// indicatorPanel.add(pup);
- desk.add(pup, JLayeredPane.PALETTE_LAYER);
- desk.addComponentListener(new ComponentAdapter() {
+ this.desk.add(this.pup, JLayeredPane.PALETTE_LAYER);
+ this.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);
- pup.setLocation((int) (dim.getWidth() - pup.getWidth()), (int) (dim.getHeight() - pup.getHeight()));
+ public void componentResized(final ComponentEvent evt) {
+ final Dimension dim = evt.getComponent().getSize();
+ final Dimension imgSize = MainWindow.this.backImage.getSize();
+ MainWindow.this.backImage.setLocation((int) (dim.getWidth() - imgSize.getWidth()) / 2, (int) (dim.getHeight() - imgSize.getHeight()) / 2);
+ MainWindow.this.pup.setLocation((int) (dim.getWidth() - MainWindow.this.pup.getWidth()), (int) (dim.getHeight() - MainWindow.this.pup.getHeight()));
// pup.setLocation(0,0);
}
});
status.setBorder(new EtchedBorder(EtchedBorder.LOWERED));
- if (debugUI)
+ if (debugUI) {
inner.add(status, BorderLayout.SOUTH);
+ }
// 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();
+ this.startListener.pushProgress();
+ inner.add(this.desk, BorderLayout.CENTER);
+ this.setContentPane(inner);
+ this.startListener.pushProgress();
// dimensionnement de la fenetre
- Properties props = getHomeProperties();
+ final Properties props = this.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();
+ final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
+ final GraphicsConfiguration gc = this.getGraphicsConfiguration();
+ final GraphicsDevice gd = gc.getDevice();
+ final DisplayMode dm = gd.getDisplayMode();
+ final GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
+ final Rectangle rect = ge.getMaximumWindowBounds();
Rectangle lastLocation = null;
- if (props.getProperty(MAIN_WINDOW_POSITION) != null) {
+ if (props.getProperty(MainWindow.MAIN_WINDOW_POSITION) != null) {
// syntax is "(x,y,width,height)"
- String s = props.getProperty(MAIN_WINDOW_POSITION);
+ String s = props.getProperty(MainWindow.MAIN_WINDOW_POSITION);
s = s.substring(1, s.length() - 1);
- String[] sa = s.split(",");
+ final 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]);
+ final int x = Integer.parseInt(sa[0]);
+ final int y = Integer.parseInt(sa[1]);
+ final int width = Integer.parseInt(sa[2]);
+ final 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) {
+ } catch (final Exception ex) {
// on ignre, on initialise pas
}
}
if (lastLocation != null) {
- setBounds(lastLocation);
+ this.setBounds(lastLocation);
} else {
if (rect != null && (rect.getWidth() != dm.getWidth() || rect.getHeight() != dm.getHeight())) {
- setBounds(rect);
+ this.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);
+ this.setLocation((int) ((screenSize.getWidth() - MainWindow.DEFAULT_WIDTH) / 2), (int) ((screenSize.getHeight() - MainWindow.DEFAULT_HEIGHT) / 2));
+ this.pack();
+ this.setSize(new Dimension(MainWindow.DEFAULT_WIDTH, MainWindow.DEFAULT_HEIGHT));
+ this.setExtendedState(Frame.MAXIMIZED_BOTH);
}
}
- startListener.pushProgress();
- setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
- startListener.pushProgress();
- setVisible(true);
- startListener.pushProgress();
+ this.startListener.pushProgress();
+ this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
+ this.startListener.pushProgress();
+ this.setVisible(true);
+ this.startListener.pushProgress();
}
protected void initActions() {
- startListener.pushProgress();
- startListener.pushProgress();
- actQuitter = new AbstractAction("Quitter") {
+ this.startListener.pushProgress();
+ this.startListener.pushProgress();
+ this.actQuitter = new AbstractAction("Quitter") {
private static final long serialVersionUID = 1L;
@Override
- public void actionPerformed(ActionEvent e) {
- runExit();
+ public void actionPerformed(final ActionEvent e) {
+ MainWindow.this.runExit();
}
};
- startListener.pushProgress();
+ this.startListener.pushProgress();
}
private void initMenus1() {
- JMenuBar mBar = new JMenuBar();
- JMenu fileMenu = new JMenu("Fichier");
+ final JMenuBar mBar = new JMenuBar();
+ final JMenu fileMenu = new JMenu("Fichier");
- importerMenu = new JMenu("Importer");
- controlerMenu = new JMenu("Analyser");
- fileMenu.add(importerMenu);
- fileMenu.add(controlerMenu);
+ this.importerMenu = new JMenu("Importer");
+ this.controlerMenu = new JMenu("Analyser");
+ fileMenu.add(this.importerMenu);
+ fileMenu.add(this.controlerMenu);
fileMenu.addSeparator();
- JMenu mnuExports = new JMenu("Exports");
- mnuExporterFichier = new JMenuItem("Exporter des fichiers...");
- mnuExporterFichier.addActionListener(new ActionListener() {
+ final JMenu mnuExports = new JMenu("Exports");
+ this.mnuExporterFichier = new JMenuItem("Exporter des fichiers...");
+ this.mnuExporterFichier.addActionListener(new ActionListener() {
@Override
- public void actionPerformed(ActionEvent e) {
- exporterFichier();
+ public void actionPerformed(final ActionEvent e) {
+ MainWindow.this.exporterFichier();
}
});
- mnuExports.add(mnuExporterFichier);
+ mnuExports.add(this.mnuExporterFichier);
fileMenu.add(mnuExports);
// TODO: une entrée pour supprimer tout
- mnuSupprimer = new JMenuItem("Supprimer...");
- fileMenu.add(mnuSupprimer);
- mnuSupprimer.addActionListener(new ActionListener() {
+ this.mnuSupprimer = new JMenuItem("Supprimer...");
+ fileMenu.add(this.mnuSupprimer);
+ this.mnuSupprimer.addActionListener(new ActionListener() {
@Override
- public void actionPerformed(ActionEvent evt) {
- new DlgCleanDatabase(MainWindow.this, true, docModels, DlgChooseDocuments.DIALOG_TYPE.BOTH, getConnectedUser(), getEnvProperties());
+ public void actionPerformed(final ActionEvent evt) {
+ new DlgCleanDatabase(MainWindow.this, true, MainWindow.this.docModels, DlgChooseDocuments.DIALOG_TYPE.BOTH, MainWindow.this.getConnectedUser(), MainWindow.this.getEnvProperties());
}
});
fileMenu.addSeparator();
boolean reAddSeparator = false;
- if ("true".equals(applicationProperties.getProperty(Constants.SYS_PROP_RESET_CONFIG))) {
- JMenuItem mnuReset = new JMenuItem("Reset config ...");
+ if ("true".equals(this.applicationProperties.getProperty(Constants.SYS_PROP_RESET_CONFIG))) {
+ final JMenuItem mnuReset = new JMenuItem("Reset config ...");
fileMenu.add(mnuReset);
reAddSeparator = true;
mnuReset.addActionListener(new ActionListener() {
@Override
- public void actionPerformed(ActionEvent evt) {
- reloadConfiguration();
+ public void actionPerformed(final ActionEvent evt) {
+ MainWindow.this.reloadConfiguration();
}
});
}
- if ("true".equals(applicationProperties.getProperty(Constants.SYS_PROP_ADMIN_MENU_GC))) {
- mnuClean = new JMenuItem("Garbage collector");
- fileMenu.add(mnuClean);
+ if ("true".equals(this.applicationProperties.getProperty(Constants.SYS_PROP_ADMIN_MENU_GC))) {
+ this.mnuClean = new JMenuItem("Garbage collector");
+ fileMenu.add(this.mnuClean);
reAddSeparator = true;
- mnuClean.addActionListener(new ActionListener() {
+ this.mnuClean.addActionListener(new ActionListener() {
@Override
- public void actionPerformed(ActionEvent evt) {
+ public void actionPerformed(final ActionEvent evt) {
System.gc();
}
});
- mnuClean.setEnabled(false);
+ this.mnuClean.setEnabled(false);
}
- if (reAddSeparator)
+ 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());
+ public void actionPerformed(final ActionEvent evt) {
+ final DlgEditEnvironment dee = new DlgEditEnvironment(MainWindow.this, MainWindow.this.docModels, EnvironmentDomain.DOMAIN_DOCUMENTS, MainWindow.this.getConnectedUser());
dee.setVisible(true);
}
});
fileMenu.addSeparator();
- JMenuItem mnuConfig = new JMenuItem("Configuration...");
+ final JMenuItem mnuConfig = new JMenuItem("Configuration...");
mnuConfig.addActionListener(new ActionListener() {
@Override
- public void actionPerformed(ActionEvent e) {
- DlgSystemConfiguration dlg = new DlgSystemConfiguration(MainWindow.this, true);
+ public void actionPerformed(final ActionEvent e) {
+ final DlgSystemConfiguration dlg = new DlgSystemConfiguration(MainWindow.this, true);
dlg.setVisible(true);
}
});
fileMenu.add(mnuConfig);
- JMenuItem mnuMAJ = new JMenuItem("Mise à jour...");
+ final JMenuItem mnuMAJ = new JMenuItem("Mise à jour...");
mnuMAJ.addActionListener(new ActionListener() {
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(final ActionEvent e) {
// ForceUpdate fu = new ForceUpdate();
// fu.execute();
- UpdateChecker uc = new UpdateChecker();
+ final UpdateChecker uc = new UpdateChecker();
uc.execute();
}
});
fileMenu.addSeparator();
- fileMenu.add(new JMenuItem(actQuitter));
+ fileMenu.add(new JMenuItem(this.actQuitter));
mBar.add(fileMenu);
- searchMenu = new JMenu("Recherche");
- browseMenu = new JMenu("Navigation");
+ this.searchMenu = new JMenu("Recherche");
+ this.browseMenu = new JMenu("Navigation");
- searchMenu.setEnabled(false);
- browseMenu.setEnabled(false);
- mBar.add(searchMenu);
- mBar.add(browseMenu);
+ this.searchMenu.setEnabled(false);
+ this.browseMenu.setEnabled(false);
+ mBar.add(this.searchMenu);
+ mBar.add(this.browseMenu);
- JMenu toolMenu = loadToolMenu();
+ final JMenu toolMenu = this.loadToolMenu();
if (toolMenu != null) {
mBar.add(toolMenu);
}
- windowMenu = new WindowMenu("Fenêtres", desk);
+ this.windowMenu = new WindowMenu("Fenêtres", this.desk);
- mBar.add(windowMenu);
+ mBar.add(this.windowMenu);
mBar.add(Box.createHorizontalGlue());
- JMenu helper = new JMenu("?");
- Action aboutAction = new AbstractAction("A Propos") {
+ final JMenu helper = new JMenu("?");
+ final Action aboutAction = new AbstractAction("A Propos") {
private static final long serialVersionUID = 1L;
@Override
- public void actionPerformed(ActionEvent evt) {
+ public void actionPerformed(final ActionEvent evt) {
new AboutBox(MainWindow.this);
}
};
helper.add(new JMenuItem(aboutAction));
- Action helpAction = new AbstractAction("Aide en ligne") {
+ final Action helpAction = new AbstractAction("Aide en ligne") {
private static final long serialVersionUID = 1L;
@Override
- public void actionPerformed(ActionEvent evt) {
+ public void actionPerformed(final ActionEvent evt) {
try {
- StartUrl.startUrl(applicationProperties.getProperty(Constants.SYS_PROP_HELP_URL));
- } catch (Throwable t) {
+ StartUrl.startUrl(MainWindow.this.applicationProperties.getProperty(Constants.SYS_PROP_HELP_URL));
+ } catch (final Throwable t) {
}
}
};
helper.add(helpAction);
- Action releaseNotesAction = new AbstractAction("Notes de version...") {
+ final 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";
+ public void actionPerformed(final ActionEvent e) {
+ final String url = "http://xemelios.org/updatesV5/release-notes-" + MainWindow.this.getEnvProperties().getProperty(Constants.SYS_PROP_MAJ_CONFIG) + ".html";
try {
StartUrl.startUrl(url);
- } catch (Exception ex) {
- logger.error("while openning release-notes", ex);
+ } catch (final Exception ex) {
+ MainWindow.logger.error("while openning release-notes", ex);
}
}
};
helper.add(releaseNotesAction);
- Action dlInfos = new AbstractAction("Rapport de configuration...") {
+ final Action dlInfos = new AbstractAction("Rapport de configuration...") {
private static final long serialVersionUID = 1L;
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(final ActionEvent e) {
try {
MainWindow.getInstance().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
- ConfigurationReportBuilder reportBuilder = new ConfigurationReportBuilder();
- File xemConfFile = new File(getEnvProperties().replace("${xemelios.prg}/root/xemelios.properties"));
- DataImpl dataLayer = DataLayerManager.getImplementation();
- File dbConfFile = new File(getEnvProperties().replace("${xemelios." + dataLayer.getLayerName() + ".config.filename}"));
- File logFile = new File(getEnvProperties().replace("${xemelios.prg}/root/xemelios.log"));
- File componentsFile = new File(getEnvProperties().getProperty(Constants.SYS_PROP_INSTALLED_FILENAME));
+ final ConfigurationReportBuilder reportBuilder = new ConfigurationReportBuilder();
+ final File xemConfFile = new File(MainWindow.this.getEnvProperties().replace("${xemelios.prg}/root/xemelios.properties"));
+ final DataImpl dataLayer = DataLayerManager.getImplementation();
+ final File dbConfFile = new File(MainWindow.this.getEnvProperties().replace("${xemelios." + dataLayer.getLayerName() + ".config.filename}"));
+ final File logFile = new File(MainWindow.this.getEnvProperties().replace("${xemelios.prg}/root/xemelios.log"));
+ final File componentsFile = new File(MainWindow.this.getEnvProperties().getProperty(Constants.SYS_PROP_INSTALLED_FILENAME));
reportBuilder.addJarsDescription(ClassPathUtils.getJarsDescription());
reportBuilder.addFileContent(xemConfFile, "ISO-8859-1", "Xemelios configuration file");
reportBuilder.addFileContent(logFile, "ISO-8859-1", "Xemelios log file");
reportBuilder.addFileContent(componentsFile, "UTF-8", "Xemelios components file");
- JFileChooser fc = new JFileChooser();
+ final JFileChooser fc = new JFileChooser();
fc.setDialogTitle("Enregistrer le rapport de configuration sous...");
fc.addChoosableFileFilter(new FileFilter() {
@Override
- public boolean accept(File f) {
+ public boolean accept(final File f) {
return f.getName().toLowerCase().endsWith(".txt");
}
f = new File(f.getParentFile(), f.getName() + ".txt");
}
- PrintWriter pw = new PrintWriter(f);
+ final PrintWriter pw = new PrintWriter(f);
try {
pw.write(reportBuilder.getReport());
pw.flush();
pw.close();
}
}
- } catch (Exception ex) {
- logger.error(ex, ex);
+ } catch (final Exception ex) {
+ MainWindow.logger.error(ex, ex);
JOptionPane.showMessageDialog(MainWindow.getInstance(), ex.getMessage(), "Une erreur inattendu est survenue", JOptionPane.ERROR_MESSAGE);
} finally {
MainWindow.getInstance().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
};
helper.add(dlInfos);
mBar.add(helper);
- setJMenuBar(mBar);
+ this.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));
+ final Hashtable<String, Object> values = DataLayerManager.getImplementation().getRedefinedConfigValues(this.connectedUser);
+ for (final String key : values.keySet()) {
+ final String path = key.startsWith("/") ? key.substring(1) : key;
+ this.docModels.setValue(path, values.get(key));
}
- } catch (Exception ex) {
- logger.error("while applying overriden documents configration", ex);
+ } catch (final Exception ex) {
+ MainWindow.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());
+ final ActionImport aiArch = new ActionImport("Archive XeMeLios", Constants.XEMELIOS_ARCHIVE_SIGN);
+ this.importerMenu.add(new JMenuItem(aiArch));
+ for (final DocumentModel dm : this.docModels.getDocuments()) {
+ if (!this.getConnectedUser().hasDocument(dm.getId())) {
+ MainWindow.logger.debug(this.getConnectedUser().getId() + " is not allowed on " + dm.getId());
continue;
}
- if (dm.getDisplayInMenuIf() != null && !"true".equals(applicationProperties.getProperty(dm.getDisplayInMenuIf()))) {
+ if (dm.getDisplayInMenuIf() != null && !"true".equals(this.applicationProperties.getProperty(dm.getDisplayInMenuIf()))) {
continue;
}
- ActionImport ai = new ActionImport(dm.getTitre(), dm.getId());
+ final ActionImport ai = new ActionImport(dm.getTitre(), dm.getId());
if (dm.isControlable()) {
- ActionControl ac = new ActionControl(dm.getTitre(), dm.getId());
- controlerMenu.add(new JMenuItem(ac));
+ final ActionControl ac = new ActionControl(dm.getTitre(), dm.getId());
+ this.controlerMenu.add(new JMenuItem(ac));
}
if (dm.isImportable()) {
- importerMenu.add(new JMenuItem(ai));
+ this.importerMenu.add(new JMenuItem(ai));
}
- JMenu searchEntry = new JMenu(dm.getTitre());
+ final JMenu searchEntry = new JMenu(dm.getTitre());
JMenuItem browseEntry = null;
if (dm.isBrowsable()) {
final DocumentModel dm2 = dm;
private static final long serialVersionUID = 1L;
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(final ActionEvent e) {
if (dm2.getNavigateToDocumentSwingClassName() == null) {
// comportement par défaut
- DlgSelectNavigationTarget dlg = new DlgSelectNavigationTarget(dm2, getConnectedUser(), instance);
+ final DlgSelectNavigationTarget dlg = new DlgSelectNavigationTarget(dm2, MainWindow.this.getConnectedUser(), MainWindow.instance);
if (dlg.run()) {
switch (dlg.getSpecialKeys().size()) {
case 0: {
- browse(dm2, dm2.getDefaultBrowsableEtat(), dlg.getCollectivite().key, dlg.getBudget().key, null, null);
+ MainWindow.this.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);
+ MainWindow.this.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);
+ MainWindow.this.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);
+ final Class clazz = Class.forName(dm2.getNavigateToDocumentSwingClassName());
+ final Constructor<Navigable> cc = clazz.getConstructor(new Class[] { DocumentModel.class, XemeliosUser.class, MainWindow.class });
+ final Navigable obj = cc.newInstance(dm2, MainWindow.this.getConnectedUser(), MainWindow.instance);
obj.run();
- } catch (Exception ex) {
+ } catch (final 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()))) {
+ for (final EtatModel em : dm.getEtats()) {
+ if (em.getDisplayInMenuIf() != null && !"true".equals(this.applicationProperties.getProperty(em.getDisplayInMenuIf()))) {
continue;
}
JMenu tmpMnu = null;
} else {
tmpMnu = searchEntry;
}
- for (ElementModel elm : em.getSearchableElements()) {
+ for (final ElementModel elm : em.getSearchableElements()) {
if (!elm.isDisplay()) {
continue;
}
- ActionSearch as = new ActionSearch(elm.getTitre(), dm.getId(), em.getId(), elm.getId());
+ final ActionSearch as = new ActionSearch(elm.getTitre(), dm.getId(), em.getId(), elm.getId());
tmpMnu.add(new JMenuItem(as));
searchCount++;
}
}
}
if (searchCount > 0) {
- searchMenu.add(searchEntry);
+ this.searchMenu.add(searchEntry);
}
if (browseEntry != null) {
- browseMenu.add(browseEntry);
+ this.browseMenu.add(browseEntry);
}
}
}
- protected void importer(String docId) {
+ protected void importer(final String docId) {
if (Constants.XEMELIOS_ARCHIVE_SIGN.equals(docId)) {
- importXemeliosArchive();
+ this.importXemeliosArchive();
} else {
- DocumentModel dm = docModels.getDocumentById(docId);
+ final DocumentModel dm = this.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.";
+ if (!DataLayerManager.getImplementation().canImportDocument(docId, this.connectedUser)) {
+ final 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, PropertiesExpansion.class);
- Object obj = cc.newInstance(getConnectedUser(), applicationProperties);
+ final Class clazz = Class.forName(dm.getImportClass());
+ final Constructor cc = clazz.getConstructor(XemeliosUser.class, PropertiesExpansion.class);
+ final Object obj = cc.newInstance(this.getConnectedUser(), this.applicationProperties);
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());
+ final EtatImporteur ei = (EtatImporteur) obj;
+ final ImportContent fToImport = this.getFilesToImport(dm.getExtension(), dm.getLibelleExtension());
if (fToImport.getImportCount() > 0) {
- doImport(ei, fToImport, dm, false);
+ this.doImport(ei, fToImport, dm, false);
}
- } catch (Exception ex) {
- logger.error("importer", ex);
+ } catch (final Exception ex) {
+ MainWindow.logger.error("importer", ex);
new DisplayExceptionDlg(this, ex);
} finally {
// waiter.stopProgress();
}
protected void importXemeliosArchive() {
- FileSystemView fsv = FileSystemView.getFileSystemView();
- if (lastInputDirectory == null) {
- lastInputDirectory = fsv.getHomeDirectory();
+ final FileSystemView fsv = FileSystemView.getFileSystemView();
+ if (this.lastInputDirectory == null) {
+ this.lastInputDirectory = fsv.getHomeDirectory();
}
- JFileChooser fc = new JFileChooser(lastInputDirectory, fsv);
+ final JFileChooser fc = new JFileChooser(this.lastInputDirectory, fsv);
FileFilter defaultFileFilter = null;
fc.addChoosableFileFilter(defaultFileFilter = new FileFilter() {
@Override
- public boolean accept(File arg0) {
+ public boolean accept(final File arg0) {
return arg0.isDirectory() || arg0.getName().toUpperCase().endsWith(".XAR");
}
fc.setDialogTitle("Choisissez une archive XeMeLios");
fc.setApproveButtonText("Importer");
if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
- File firstArchive = fc.getSelectedFile();
- lastInputDirectory = firstArchive.getParentFile();
- ArchiveWizardDisplayer awd = new ArchiveWizardDisplayer(this, firstArchive);
+ final File firstArchive = fc.getSelectedFile();
+ this.lastInputDirectory = firstArchive.getParentFile();
+ final ArchiveWizardDisplayer awd = new ArchiveWizardDisplayer(this, firstArchive);
}
}
- public void doImport(EtatImporteur ei, ImportContent fToImport, DocumentModel dm, boolean synchronizeMe) {
- ImportServiceSwingProvider issp = new ImportServiceSwingProvider(this, ei, fToImport.filesToImport.size() + fToImport.pjs.size());
+ public void doImport(final EtatImporteur ei, final ImportContent fToImport, final DocumentModel dm, final boolean synchronizeMe) {
+ final 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());
+ ei.setApplicationConfiguration(this.getEnvProperties());
// waiter.startProgress();
try {
ei.setFilesToImport(fToImport.filesToImport);
} else {
ei.execute();
}
- } catch (Exception ex) {
- logger.error("doImport", ex);
+ } catch (final Exception ex) {
+ MainWindow.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());
+ public void doImport(final EtatImporteur ei, final ImportContent fToImport, final DocumentModel dm, final DlgControl parentController, final MainControl.Triplet triplet, final boolean synchronizeMe) {
+ final ImportServiceSwingProvider issp = new ImportServiceSwingProvider(this, ei, fToImport.filesToImport.size() + fToImport.pjs.size());
if (synchronizeMe) {
issp.setDisplayFeedback(false);
}
ei.execute();
}
- } catch (Exception ex) {
- logger.error("doImport", ex);
+ } catch (final Exception ex) {
+ MainWindow.logger.error("doImport", ex);
new DisplayExceptionDlg(this, ex);
} finally {
// waiter.stopProgress();
}
try {
ei.get();
- } catch (Throwable t) {
+ } catch (final Throwable t) {
t.printStackTrace();
parentController.notifyImportFailed();
} finally {
}
}
- protected void controller(String docId) {
- MainControlWrapper mc = new MainControlWrapper(docModels.getDocumentById(docId), docModels, getConnectedUser(), applicationProperties);
- DlgControl dc = new DlgControl(this, docModels.getDocumentById(docId), mc);
+ protected void controller(final String docId) {
+ final MainControlWrapper mc = new MainControlWrapper(this.docModels.getDocumentById(docId), this.docModels, this.getConnectedUser(), this.applicationProperties);
+ final DlgControl dc = new DlgControl(this, this.docModels.getDocumentById(docId), mc);
dc.setVisible(true);
}
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();
+ final JInternalFrame[] childs = this.desk.getAllFrames();
+ for (final JInternalFrame child : childs) {
+ this.desk.remove(child);
+ child.dispose();
}
- Rectangle location = getBounds();
- StringBuilder propValue = new StringBuilder();
+ final Rectangle location = this.getBounds();
+ final 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();
+ final File propFile = new File(System.getProperty("user.home"), "xemelios.properties");
+ final Properties props = new Properties();
if (propFile.exists()) {
try {
props.load(new FileInputStream(propFile));
- } catch (IOException ioEx) {
+ } catch (final IOException ioEx) {
}
}
- props.setProperty(MAIN_WINDOW_POSITION, propValue.toString());
- if (lastInputDirectory != null) {
+ props.setProperty(MainWindow.MAIN_WINDOW_POSITION, propValue.toString());
+ if (this.lastInputDirectory != null) {
if (props.getProperty(Constants.SYS_PROP_LAST_INPUT_DIRECTORY) == null) {
- props.setProperty(Constants.SYS_PROP_LAST_INPUT_DIRECTORY, lastInputDirectory.getAbsolutePath());
+ props.setProperty(Constants.SYS_PROP_LAST_INPUT_DIRECTORY, this.lastInputDirectory.getAbsolutePath());
} else {
- props.put(Constants.SYS_PROP_LAST_INPUT_DIRECTORY, lastInputDirectory.getAbsolutePath());
+ props.put(Constants.SYS_PROP_LAST_INPUT_DIRECTORY, this.lastInputDirectory.getAbsolutePath());
}
}
try {
props.store(new FileOutputStream(propFile), "");
- } catch (Throwable t) {
+ } catch (final Throwable t) {
}
try {
- File[] files = FileUtils.getTempDir().listFiles();
- for (File f : files) {
+ final File[] files = FileUtils.getTempDir().listFiles();
+ for (final File f : files) {
f.delete();
}
FileUtils.getTempDir().delete();
- } catch (Throwable t) {
+ } catch (final Throwable t) {
}
- } catch (Exception ex) {
- logger.error("in runExit()", ex);
+ } catch (final Exception ex) {
+ MainWindow.logger.error("in runExit()", ex);
}
- savePersonnalConfig();
- saveCriteriasInputValues();
+ this.savePersonnalConfig();
+ this.saveCriteriasInputValues();
System.exit(0);
}
- public SearchWindow displaySearchWindow(ElementModel element) {
- ElementModel elm = element.clone();
- EtatModel em = element.getParent();
- DocumentModel dm = em.getParent();
+ public SearchWindow displaySearchWindow(final ElementModel element) {
+ final ElementModel elm = element.clone();
+ final EtatModel em = element.getParent();
+ final DocumentModel dm = em.getParent();
elm.setParent(em);
try {
- if (DataLayerManager.getImplementation().canSearch(dm, em, getConnectedUser())) {
+ if (DataLayerManager.getImplementation().canSearch(dm, em, this.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);
+ final SearchWindow sw = new SearchWindow(this, dm, elm, this.getConnectedUser());
+ this.desk.add(sw);
+ this.desk.getDesktopManager().maximizeFrame(sw);
return sw;
} else {
throw new ToolException(ToolException.ERROR_NO_DATA);
}
- } catch (ToolException tEx) {
+ } catch (final 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) {
+ } catch (final UnauthorizedException ex) {
JOptionPane.showMessageDialog(this, ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
- } catch (DataAccessException daEx) {
+ } catch (final DataAccessException daEx) {
new DisplayExceptionDlg(this, daEx);
- } catch (DataConfigurationException dcEx) {
+ } catch (final 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);
+ protected void search(final String docId, final String etatId, final String elementId) {
+ final DocumentModel dm = this.docModels.getDocumentById(docId).clone();
+ final EtatModel em = dm.getEtatById(etatId);
try {
- if (DataLayerManager.getImplementation().canSearch(dm, em, getConnectedUser())) {
- ElementModel elm = em.getElementById(elementId);
+ if (DataLayerManager.getImplementation().canSearch(dm, em, this.getConnectedUser())) {
+ final 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);
+ final SearchWindow sw = new SearchWindow(this, dm, elm, this.getConnectedUser());
+ this.desk.add(sw);
+ this.desk.getDesktopManager().maximizeFrame(sw);
sw.show();
} else {
throw new ToolException(ToolException.ERROR_NO_DATA);
}
- } catch (ToolException tEx) {
+ } catch (final 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) {
+ } catch (final UnauthorizedException ex) {
JOptionPane.showMessageDialog(this, ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
- } catch (DataAccessException daEx) {
+ } catch (final DataAccessException daEx) {
new DisplayExceptionDlg(this, daEx);
- } catch (DataConfigurationException dcEx) {
+ } catch (final DataConfigurationException dcEx) {
new DisplayExceptionDlg(this, dcEx);
}
}
protected boolean checkPassword() throws DataAccessException {
// Affichage de la fenêtre d'authentification :
- AuthEngine authEngine = AuthEngine.Holder.getAuthEngine();
+ final AuthEngine authEngine = AuthEngine.Holder.getAuthEngine();
XemeliosUser user = null;
if (authEngine.isLoginRequired() || authEngine.isPasswordRequired()) {
- if (startListener instanceof Splash) {
- Splash sp = (Splash) startListener;
+ if (this.startListener instanceof Splash) {
+ final Splash sp = (Splash) this.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());
+ final 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;
+ if (this.startListener instanceof Splash) {
+ final Splash sp = (Splash) this.startListener;
sp.setAlwaysOnTop(true);
sp.setVisible(true);
}
return false;
}
}
- if (startListener instanceof Splash) {
- Splash sp = (Splash) startListener;
+ if (this.startListener instanceof Splash) {
+ final Splash sp = (Splash) this.startListener;
sp.setAlwaysOnTop(true);
sp.setVisible(true);
}
user = authEngine.createUser(null, null);
}
if (user != null) {
- connectedUser = user;
+ this.connectedUser = user;
return true;
} else {
return false;
}
}
- protected DocumentsModel getDocumentsInfos(String repertoires) {
+ protected DocumentsModel getDocumentsInfos(final 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;
+ } catch (final Exception ex) {
+ MainWindow.logger.error(ex);
+ this.startListener.completeProgress();
+ if (this.startListener instanceof Splash) {
+ final Splash sp = (Splash) this.startListener;
sp.setAlwaysOnTop(false);
sp.setVisible(false);
}
}
protected ImportContent getFilesToImport(final String extension, final String titreEtat) {
- ImportContent ic = new ImportContent();
- FileSystemView fsv = FileSystemView.getFileSystemView();
- if (lastInputDirectory == null) {
- lastInputDirectory = fsv.getHomeDirectory();
+ final ImportContent ic = new ImportContent();
+ final FileSystemView fsv = FileSystemView.getFileSystemView();
+ if (this.lastInputDirectory == null) {
+ this.lastInputDirectory = fsv.getHomeDirectory();
}
- JFileChooser fc = new JFileChooser(lastInputDirectory, fsv);
+ final JFileChooser fc = new JFileChooser(this.lastInputDirectory, fsv);
FileFilter defaultFileFilter = null;
fc.addChoosableFileFilter(defaultFileFilter = new FileFilter() {
@Override
- public boolean accept(File arg0) {
+ public boolean accept(final File arg0) {
return arg0.isDirectory() || arg0.getName().toUpperCase().endsWith(extension.toUpperCase());
}
fc.addChoosableFileFilter(new FileFilter() {
@Override
- public boolean accept(File arg0) {
+ public boolean accept(final File arg0) {
return arg0.isDirectory() || arg0.getName().toUpperCase().endsWith(".XML");
}
fc.addChoosableFileFilter(new FileFilter() {
@Override
- public boolean accept(File arg0) {
+ public boolean accept(final File arg0) {
return arg0.isDirectory() || arg0.getName().toUpperCase().endsWith(".ZIP");
}
fc.addChoosableFileFilter(new FileFilter() {
@Override
- public boolean accept(File f) {
+ public boolean accept(final File f) {
return f.isDirectory() || f.getName().toUpperCase().endsWith(".GZ");
}
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fc.setMultiSelectionEnabled(true);
fc.setDialogTitle("Choisissez un fichier ou répertoire à importer");
- int selectedAction = fc.showOpenDialog(this);
+ final int selectedAction = fc.showOpenDialog(this);
if (selectedAction == JFileChooser.APPROVE_OPTION) {
File[] ret = null;
if (fc.getSelectedFile() != null && fc.getSelectedFile().isFile()) {
// ret = new File[1];
// ret[0] = fc.getSelectedFile();
ret = fc.getSelectedFiles();
- lastInputDirectory = ret[0].getParentFile();
+ this.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());
+ MainWindow.logger.debug("path=" + fc.getSelectedFile().getAbsolutePath());
// on crée le modèle de données pour l'affichage dans la boite de dialogue d'import
- String[] extensions = { "xml", "zip", extension };
+ final 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);
+ final ImportDialog test = new ImportDialog(this, "Sélectionnez les fichiers à importer");
+ final 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();
+ for (final Object element : resultats) {
+ ret[counter++] = ((ImportFile) element).getFile();
}
- lastInputDirectory = fc.getSelectedFile().getParentFile() != null ? fc.getSelectedFile().getParentFile() : fc.getSelectedFile();
+ this.lastInputDirectory = fc.getSelectedFile().getParentFile() != null ? fc.getSelectedFile().getParentFile() : 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()) {
+ final File tmpDir = FileUtils.getTempDir();
+ for (final File element : ret) {
+ if (element.getName().toLowerCase().endsWith(".zip")) {
+ if (element.exists()) {
ZipFile zf = null;
try {
- zf = new ZipFile(ret[i]);
- for (Enumeration<? extends ZipEntry> enumer = zf.entries(); enumer.hasMoreElements();) {
- ZipEntry ze = enumer.nextElement();
+ zf = new ZipFile(element);
+ for (final Enumeration<? extends ZipEntry> enumer = zf.entries(); enumer.hasMoreElements();) {
+ final ZipEntry ze = enumer.nextElement();
if (!ze.isDirectory()) {
String fileName = ze.getName();
- String entryName = fileName.toLowerCase();
+ final String entryName = fileName.toLowerCase();
fileName = fileName.replace(File.pathSeparatorChar, '_').replace(File.separatorChar, '_').replace(':', '|').replace('\'', '_').replace('/', '_');
- logger.debug(entryName);
+ MainWindow.logger.debug(entryName);
if (PJRef.isPJ(ze)) {
- PJRef pj = new PJRef(ze);
+ final 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];
+ final InputStream is = zf.getInputStream(ze);
+ final BufferedInputStream bis = new BufferedInputStream(is);
+ final File output = new File(tmpDir, fileName);
+ final BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(output));
+ final byte[] buffer = new byte[1024];
int read = bis.read(buffer);
while (read > 0) {
bos.write(buffer, 0, read);
}
}
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);
+ } catch (final ZipException zEx) {
+ JOptionPane.showMessageDialog(this, "Le fichier " + element.getName() + " n'est pas une archive ZIP valide", "Erreur", JOptionPane.ERROR_MESSAGE);
+ } catch (final IOException ioEx) {
+ JOptionPane.showMessageDialog(this, "Le fichier " + element.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) {
+ } catch (final Throwable t) {
}
}
}
}
- } else if (ret[i].getName().toLowerCase().endsWith(".gz")) {
+ } else if (element.getName().toLowerCase().endsWith(".gz")) {
try {
- String fileName = ret[i].getName();
+ String fileName = element.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];
+ final File output = new File(tmpDir, fileName);
+ final GZIPInputStream gis = new GZIPInputStream(new FileInputStream(element));
+ final BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(output));
+ final byte[] buffer = new byte[1024];
int read = gis.read(buffer);
while (read > 0) {
bos.write(buffer, 0, read);
bos.close();
gis.close();
ic.filesToImport.add(output);
- } catch (IOException ioEx) {
+ } catch (final IOException ioEx) {
// nothing to do
}
} else {
- ic.filesToImport.add(ret[i]);
+ ic.filesToImport.add(element);
}
}
} else {
}
protected void checkUpdateAvailability() {
- UpdateChecker uc = new UpdateChecker();
+ final UpdateChecker uc = new UpdateChecker();
uc.execute();
}
// statusField.setText(message);
// }
//
- public static final void main(String[] args) {
- PropertiesExpansion pe = new PropertiesExpansion(System.getProperties());
+ public static final void main(final String[] args) {
+ final PropertiesExpansion pe = new PropertiesExpansion(System.getProperties());
new MainWindow(pe, Constants.DISPLAY_NOM_APP, new EmptyStartListener(), args);
}
// waiter.stopProgress();
// }
//
- private void starterImport(String[] args) {
- if (startListener instanceof Splash) {
- Splash splash = (Splash) startListener;
+ private void starterImport(final String[] args) {
+ if (this.startListener instanceof Splash) {
+ final Splash splash = (Splash) this.startListener;
splash.setAlwaysOnTop(false);
splash.setVisible(false);
}
- if (connectedUser.hasRole(XemeliosUser.ROLE_IMPORT)) {
- for (String fName : args) {
+ if (this.connectedUser.hasRole(XemeliosUser.ROLE_IMPORT)) {
+ for (final String fName : args) {
File f = null;
try {
f = new File(fName);
- } catch (Throwable t) {
+ } catch (final 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());
+ final AskDocumentType adt = new AskDocumentType(this, fName, this.docModels, this.getEnvProperties());
adt.setVisible(true);
- DocumentModel dm = adt.getDocumentType();
+ final DocumentModel dm = adt.getDocumentType();
if (dm != null) {
try {
- Class clazz = Class.forName(dm.getImportClass());
- Constructor cc = clazz.getConstructor(XemeliosUser.class, PropertiesExpansion.class);
- Object obj = cc.newInstance(getConnectedUser(), applicationProperties);
+ final Class clazz = Class.forName(dm.getImportClass());
+ final Constructor cc = clazz.getConstructor(XemeliosUser.class, PropertiesExpansion.class);
+ final Object obj = cc.newInstance(this.getConnectedUser(), this.applicationProperties);
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);
+ final EtatImporteur ei = (EtatImporteur) obj;
+ final File[] fToImport = new File[] { f };
+ final ImportServiceSwingProvider issp = new ImportServiceSwingProvider(this, ei, fToImport.length);
ei.setImpSvcProvider(issp);
ei.setDocument(dm);
- ei.setApplicationConfiguration(getEnvProperties());
+ ei.setApplicationConfiguration(this.getEnvProperties());
//
// waiter.startProgress();
ei.setFilesToImport(fToImport);
ei.setPjs(new ArrayList<PJRef>());
ei.execute();
// waiter.stopProgress();
- } catch (Exception ex) {
- logger.error("starterImport", ex);
+ } catch (final Exception ex) {
+ MainWindow.logger.error("starterImport", ex);
/* DisplayExceptionDlg dlg = */
new DisplayExceptionDlg(this, ex);
} finally {
}
}
}
- if (startListener instanceof Splash) {
- Splash splash = (Splash) startListener;
+ if (this.startListener instanceof Splash) {
+ final Splash splash = (Splash) this.startListener;
splash.setAlwaysOnTop(false);
splash.setVisible(false);
}
}
- public SavedRequestsModel getSavedRequest(ElementModel el) {
- return config.getSavedRequests(el);
+ public SavedRequestsModel getSavedRequest(final ElementModel el) {
+ return this.config.getSavedRequests(el);
}
protected void savePersonnalConfig() {
- File f = new File(System.getProperty("user.home"));
- File fProp = new File(f, Constants.PERSONNAL_CONFIG_FILENAME);
+ final File f = new File(System.getProperty("user.home"));
+ final File fProp = new File(f, Constants.PERSONNAL_CONFIG_FILENAME);
OutputStreamWriter w = null;
try {
- 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);
+ final Charset cs = Charset.forName("ISO-8859-1");
+ final XmlOutputter xo = new XmlOutputter(w = new OutputStreamWriter(new FileOutputStream(fProp), cs), cs.name());
+ this.config.marshall(xo);
+ } catch (final Throwable t) {
+ MainWindow.logger.error("savePersonnalConfig", t);
} finally {
if (w != null) {
try {
w.flush();
w.close();
- } catch (Throwable t) {
+ } catch (final Throwable t) {
}
}
}
}
public void reloadPersonnalConfig() {
- loadPersonnalConfig();
+ this.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);
+ final File f = new File(System.getProperty("user.home"));
+ final File fProp = new File(f, Constants.PERSONNAL_CONFIG_FILENAME);
+ this.config = new PersonnalConfigurationModel(PersonnalConfigurationModel.QN);
if (fProp.exists()) {
try {
- PersonnalConfigParser parser = new PersonnalConfigParser();
+ final PersonnalConfigParser parser = new PersonnalConfigParser();
parser.parse(fProp);
- config = (PersonnalConfigurationModel) parser.getMarshallable();
- } catch (Throwable t) {
- logger.error("loadPersonnalConfig", t);
+ this.config = (PersonnalConfigurationModel) parser.getMarshallable();
+ } catch (final Throwable t) {
+ MainWindow.logger.error("loadPersonnalConfig", t);
}
}
// looking for shared requests files
- File[] sharedFiles = f.listFiles(new FilenameFilter() {
+ final File[] sharedFiles = f.listFiles(new FilenameFilter() {
@Override
- public boolean accept(File dir, String name) {
+ public boolean accept(final File dir, final 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());
+ for (final File share : sharedFiles) {
+ MainWindow.logger.debug("parsing " + share.getName());
try {
- PersonnalConfigParser parser = new PersonnalConfigParser();
+ final PersonnalConfigParser parser = new PersonnalConfigParser();
parser.parse(share);
- PersonnalConfigurationModel sharedConfig = (PersonnalConfigurationModel) parser.getMarshallable();
+ final 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);
+ this.config.merge(sharedConfig);
+ } catch (final Throwable t) {
+ MainWindow.logger.error("loadPersonnalConfig", t);
}
}
- logger.debug("personnal config loaded");
+ MainWindow.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);
+ final Properties props = new Properties();
+ final File f = new File(System.getProperty("user.home"));
+ final File fProp = new File(f, Constants.CRITERIAS_INPUTS_FILENAME);
if (fProp.exists()) {
try {
- FileInputStream fis = new FileInputStream(fProp);
+ final FileInputStream fis = new FileInputStream(fProp);
props.load(fis);
fis.close();
- } catch (IOException ioEx) {
+ } catch (final IOException ioEx) {
}
}
return props;
}
protected void saveCriteriasInputValues() {
- File f = new File(System.getProperty("user.home"));
- File fProp = new File(f, Constants.CRITERIAS_INPUTS_FILENAME);
+ final File f = new File(System.getProperty("user.home"));
+ final File fProp = new File(f, Constants.CRITERIAS_INPUTS_FILENAME);
try {
- FileOutputStream fos = new FileOutputStream(fProp);
- criteriasInputValues.store(fos, null);
+ final FileOutputStream fos = new FileOutputStream(fProp);
+ this.criteriasInputValues.store(fos, null);
fos.close();
- } catch (IOException ioEx) {
+ } catch (final 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);
+ public void browse(final DocumentModel dm, final EtatModel emParam, final String collectivite, final String budget, final String specialKey1, final String specialKey2) {
+ final EtatModel em = emParam == null ? dm.getDefaultBrowsableEtat() : emParam;
+ final 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());
+ final DataImpl impl = DataLayerManager.getImplementation();
+ final ArrayList<String> documents = impl.getDocumentListFromSpecialKeys(em.getBrowsableElement(), collectivite, budget, specialKey1, specialKey2, null, this.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);
- Pair pCollectivite = new Pair(collectivite, null);
- Document doc = impl.getDocumentAsDom(em, pCollectivite, new Pair(budget, null), docName, getConnectedUser());
- File xslFile = Xslt.getFile(dm, em, em.getBrowsableElement(), doc);
-
- 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));
+ final String docName = documents.get(0);
+ final Pair pCollectivite = new Pair(collectivite, null);
+ final Document doc = impl.getDocumentAsDom(em, pCollectivite, new Pair(budget, null), docName, this.getConnectedUser());
+ final File xslFile = Xslt.getFile(dm, em, em.getBrowsableElement(), doc);
+
+ final InputStream is = IoUtils.getInputStream(xslFile.getPath());
+ final TransformerFactory tFactory = FactoryProvider.getTransformerFactory();
+ final AbstractURIResolver uriResolver = dm.createUriResolver();
+ AbstractURIResolver.initializationHelper(uriResolver, doc, tFactory.getURIResolver(), xslFile.toURI().toURL().toExternalForm());
+
+ tFactory.setURIResolver(uriResolver);
+
+ final 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();
+ final XPath xp = this.xpf.newXPath();
xp.setNamespaceContext(dm.getNamespaces());
String idRepository = null;
if (dm.getReferenceNomenclaturePath() != null && dm.getReferenceNomenclaturePath().getCodePath() != null) {
if (idRepository != null && idRepository.length() == 0) {
idRepository = null;
}
- Document repository = impl.getRepositoryAsDom(dm, pCollectivite, idRepository, getConnectedUser());
+ final Document repository = impl.getRepositoryAsDom(dm, pCollectivite, idRepository, this.getConnectedUser());
if (repository != null) {
t.setParameter("repository", repository);
}
// on passe la config
- t.setParameter("config", getDocModels().getSmallDOM());
+ t.setParameter("config", this.getDocModels().getSmallDOM());
t.setParameter("collectivite", pCollectivite.key);
t.setParameter("budget", budget);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ final ByteArrayOutputStream baos = new ByteArrayOutputStream();
t.transform(new DOMSource(doc), new StreamResult(baos));
- ByteArrayInputStream htmlStream = new ByteArrayInputStream(baos.toByteArray());
- displayHtmlStream(htmlStream, em, desk, nc);
+ final ByteArrayInputStream htmlStream = new ByteArrayInputStream(baos.toByteArray());
+ this.displayHtmlStream(htmlStream, em, this.desk, nc);
}
- } catch (Throwable t) {
+ } catch (final Throwable t) {
JOptionPane.showMessageDialog(this, t.getMessage(), "Erreur", JOptionPane.ERROR_MESSAGE);
- logger.error("browse(...)", t);
+ MainWindow.logger.error("browse(...)", t);
}
}
- public void displayHtmlStream(InputStream is, EtatModel em, JDesktopPane desk) throws IOException {
- displayHtmlStream(is, em, desk, null);
+ public void displayHtmlStream(final InputStream is, final EtatModel em, final JDesktopPane desk) throws IOException {
+ this.displayHtmlStream(is, em, desk, null);
}
- public void displayHtmlStream(File f, EtatModel em) {
+ public void displayHtmlStream(final File f, final EtatModel em) {
try {
// String prefix = applicationProperties.getProperty(Constants.SYS_PROP_NAVIGATOR_PREFIX);
// if (prefix == null) {
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);
+ final HtmlViewer viewer = new HtmlViewer(f.toURI().toURL(), "Détail " + em.getTitre(), null, this);
+ this.desk.add(viewer);
+ this.desk.getDesktopManager().maximizeFrame(viewer);
viewer.show();
}
- } catch (Exception toEx) {
- Component comp2 = desk;
+ } catch (final Exception toEx) {
+ Component comp2 = this.desk;
while (comp2 != null && !(comp2 instanceof JFrame)) {
comp2 = comp2.getParent();
}
}
- 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];
+ public void displayHtmlStream(final InputStream is, final EtatModel em, final JDesktopPane desk, final NavigationContext nc) throws IOException {
+ final File tmp = File.createTempFile("xemelios-data-", ".html", FileUtils.getTempDir());
+ final BufferedInputStream bis = new BufferedInputStream(is);
+ final BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmp));
+ final byte[] buff = new byte[1024];
int lengthRead = bis.read(buff);
while (lengthRead > 0) {
bos.write(buff, 0, lengthRead);
if (em.useExternalBrowser()) {
StartUrl.startUrl(tmp.toURI().toURL().toExternalForm());
} else {
- HtmlViewer viewer = new HtmlViewer(tmp.toURI().toURL(), "Détail " + em.getTitre(), nc, this);
+ final 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) {
+ } catch (final Exception toEx) {
Component comp2 = desk;
while (comp2 != null && !(comp2 instanceof JFrame)) {
comp2 = comp2.getParent();
}
protected void initDataLayer() throws DataConfigurationException {
- logger.debug("entering initDataLayer");
- String availableLayers = applicationProperties.getProperty(Constants.SYS_PROP_AVAILABLE_LAYERS);
- StringTokenizer tokenizer = new StringTokenizer(availableLayers, ",");
+ MainWindow.logger.debug("entering initDataLayer");
+ final String availableLayers = this.applicationProperties.getProperty(Constants.SYS_PROP_AVAILABLE_LAYERS);
+ final StringTokenizer tokenizer = new StringTokenizer(availableLayers, ",");
while (tokenizer.hasMoreTokens()) {
- String className = tokenizer.nextToken();
- logger.debug("instanciating " + className);
+ final String className = tokenizer.nextToken();
+ MainWindow.logger.debug("instanciating " + className);
try {
Class.forName(className);
- } catch (Throwable t) {
- logger.error("error while initializing data layer class (" + className + ") :", t);
+ } catch (final Throwable t) {
+ MainWindow.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));
+ DataLayerManager.setApplicationProperties(this.applicationProperties);
+ MainWindow.logger.debug("setting dataImpl to " + this.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;
+ DataLayerManager.setDataImpl(this.applicationProperties.getProperty(Constants.SYS_PROP_DATA_IMPL));
+ } catch (final DataConfigurationException dcEx) {
+ if (this.getStartListener() instanceof Splash) {
+ final Splash splash = (Splash) this.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;
+ MainWindow.logger.error(dcEx);
+ if (this.getStartListener() instanceof Splash) {
+ final Splash splash = (Splash) this.startListener;
splash.setVisible(true);
splash.setAlwaysOnTop(true);
}
throw dcEx;
}
- logger.debug("exiting successfully initDataLayer");
+ MainWindow.logger.debug("exiting successfully initDataLayer");
}
private void reloadConfiguration() {
Loader.flushLoadedConfig();
- docModels = getDocumentsInfos(applicationProperties.getProperty(Constants.SYS_PROP_DOC_DEF_DIR));
+ this.docModels = this.getDocumentsInfos(this.applicationProperties.getProperty(Constants.SYS_PROP_DOC_DEF_DIR));
try {
DataLayerManager.getImplementation().reset();
- } catch (DataConfigurationException e) {
+ } catch (final DataConfigurationException e) {
e.printStackTrace();
new DisplayExceptionDlg(this, e);
}
}
public XemeliosUser getConnectedUser() {
- return connectedUser;
+ return this.connectedUser;
}
/**
*
*/
protected void checkUpdateScript() {
- File f = new File(applicationProperties.getProperty(Constants.SYS_PROP_XEMELIOS_PRG), "update-script.xml");
+ final File f = new File(this.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);
+ final DocumentBuilder domBuilder = FactoryProvider.getDocumentBuilderFactory().newDocumentBuilder();
+ final XPath xpath = this.xpf.newXPath();
+ final Document dom = domBuilder.parse(f);
+ final NodeList nl = (NodeList) xpath.evaluate("/update-script/*", dom, XPathConstants.NODESET);
for (int i = 0; i < nl.getLength(); i++) {
- Node node = nl.item(i);
+ final Node node = nl.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
- String nodeName = node.getNodeName();
+ final 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);
+ final String id = xpath.evaluate("./@id", node);
+ final String version = xpath.evaluate("./@version", node);
+ final String description = xpath.evaluate("./@description", node);
+ this.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);
+ final String className = xpath.evaluate("./@class", node);
+ final PropertiesExpansion props = new PropertiesExpansion(this.applicationProperties);
+ final 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);
+ final Node p = params.item(j);
+ final String paramName = xpath.evaluate("./@name", p);
+ final String paramValue = xpath.evaluate("./text()", p);
props.put(paramName, paramValue);
}
- executeConfigurator(className, props);
+ this.executeConfigurator(className, props);
} else if ("remove-component".equals(nodeName)) {
// TODO: implement this
} else {
- logger.warn("update-script: unexpected element <" + nodeName + "/>");
+ MainWindow.logger.warn("update-script: unexpected element <" + nodeName + "/>");
}
}
}
- } catch (Throwable t) {
+ } catch (final Throwable t) {
new DisplayExceptionDlg((Frame) null, t);
}
f.delete();
- String htmlindex = GeneratorHelpIndex.generateIndex(getDocModels(), getEnvProperties());
- String fileName = applicationProperties.replace("${xemelios.root}/help/documents/index.html");
+ final String htmlindex = GeneratorHelpIndex.generateIndex(this.getDocModels(), this.getEnvProperties());
+ final String fileName = this.applicationProperties.replace("${xemelios.root}/help/documents/index.html");
// logger.debug("fileName="+fileName);
- File findex = new File(fileName);
+ final File findex = new File(fileName);
if (findex.exists()) {
try {
- FileOutputStream fosindex = new FileOutputStream(findex);
- Charset cs = Charset.forName("UTF-8");
- OutputStreamWriter osw = new OutputStreamWriter(fosindex, cs);
+ final FileOutputStream fosindex = new FileOutputStream(findex);
+ final Charset cs = Charset.forName("UTF-8");
+ final OutputStreamWriter osw = new OutputStreamWriter(fosindex, cs);
osw.append(htmlindex);
osw.flush();
osw.close();
- logger.info("new " + findex.getPath() + " wrote.");
- } catch (FileNotFoundException ex) {
- logger.error(ex);
+ MainWindow.logger.info("new " + findex.getPath() + " wrote.");
+ } catch (final FileNotFoundException ex) {
+ MainWindow.logger.error(ex);
new DisplayExceptionDlg((Frame) null, ex);
- } catch (IOException ex) {
- logger.error(ex);
+ } catch (final IOException ex) {
+ MainWindow.logger.error(ex);
new DisplayExceptionDlg((Frame) null, ex);
}
}
}
}
- 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 installComponent(final String uri, final String version, final String description) throws Exception {
+ final fr.gouv.finances.cp.xemelios.updater.profils.ComponentModel cm = new fr.gouv.finances.cp.xemelios.updater.profils.ComponentModel(uri, version, description, false);
+ UpdateUtil.installComponent(this.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]);
+ protected void executeConfigurator(final String className, final PropertiesExpansion props) throws Exception {
+ MainWindow.logger.info("executing configurator " + className);
+ final Class clazz = Class.forName(className);
+ final Constructor cons = clazz.getConstructor(new Class[0]);
+ final Object o = cons.newInstance(new Object[0]);
if (o instanceof AbstractConfigurator) {
- AbstractConfigurator ac = (AbstractConfigurator) o;
+ final AbstractConfigurator ac = (AbstractConfigurator) o;
ac.setProperties(props);
ac.setMainWindow(this);
ac.doConfigure();
}
}
- public String getCriteriaInputValue(String criteriaId) {
+ public String getCriteriaInputValue(final String criteriaId) {
if (criteriaId == null) {
return null;
}
- return (String) criteriasInputValues.get(criteriaId);
+ return (String) this.criteriasInputValues.get(criteriaId);
}
- public synchronized void setCriteriaInputValue(String criteriaId, String value) {
+ public synchronized void setCriteriaInputValue(final String criteriaId, final String value) {
if (criteriaId == null) {
return;
}
if (value != null && value.length() > 0) {
- criteriasInputValues.put(criteriaId, value);
+ this.criteriasInputValues.put(criteriaId, value);
} else {
- criteriasInputValues.remove(criteriaId);
+ this.criteriasInputValues.remove(criteriaId);
}
}
private static class EmptyStartListener implements StartListener {
@Override
- public void notifyMessage(String msg) {
+ public void notifyMessage(final String msg) {
}
@Override
- public void notifyProgress(int progress) {
+ public void notifyProgress(final int progress) {
}
@Override
}
@Override
- public void setVisible(boolean visible) {
+ public void setVisible(final boolean visible) {
}
}
* Comment for <code>serialVersionUID</code>
*/
private static final long serialVersionUID = 3833182540793198128L;
- String docId, etatId;
+ String docId;
- public ActionImport(String titre, String docId) {
+ public ActionImport(final String titre, final String docId) {
super(titre);
this.docId = docId;
}
@Override
- public void actionPerformed(ActionEvent evt) {
- importer(docId);
+ public void actionPerformed(final ActionEvent evt) {
+ MainWindow.this.importer(this.docId);
}
}
* Comment for <code>serialVersionUID</code>
*/
private static final long serialVersionUID = 3833182540793198128L;
- String docId, etatId;
+ String docId;
- public ActionControl(String titre, String docId) {
+ public ActionControl(final String titre, final String docId) {
super(titre);
this.docId = docId;
}
@Override
- public void actionPerformed(ActionEvent evt) {
- controller(docId);
+ public void actionPerformed(final ActionEvent evt) {
+ MainWindow.this.controller(this.docId);
}
}
private static final long serialVersionUID = 3617860763465560632L;
String docId, etatId, elementId;
- public ActionSearch(String titre, String docId, String etatId, String elementId) {
+ public ActionSearch(final String titre, final String docId, final String etatId, final String elementId) {
super(titre);
this.docId = docId;
this.etatId = etatId;
}
@Override
- public void actionPerformed(ActionEvent evt) {
- search(docId, etatId, elementId);
+ public void actionPerformed(final ActionEvent evt) {
+ MainWindow.this.search(this.docId, this.etatId, this.elementId);
}
}
public DocumentsModel getDocModels() {
- return docModels;
+ return this.docModels;
}
protected void setMenusAccess() {
@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));
+ MainWindow.this.searchMenu.setEnabled(MainWindow.this.getConnectedUser().hasRole(XemeliosUser.ROLE_SEARCH));
+ MainWindow.this.browseMenu.setEnabled(MainWindow.this.getConnectedUser().hasRole(XemeliosUser.ROLE_BROWSE));
+ if (MainWindow.this.importerMenu != null) {
+ MainWindow.this.importerMenu.setEnabled(MainWindow.this.getConnectedUser().hasRole(XemeliosUser.ROLE_IMPORT));
}
- if (controlerMenu != null) {
- controlerMenu.setEnabled(getConnectedUser().hasRole(XemeliosUser.ROLE_IMPORT));
+ if (MainWindow.this.controlerMenu != null) {
+ MainWindow.this.controlerMenu.setEnabled(MainWindow.this.getConnectedUser().hasRole(XemeliosUser.ROLE_IMPORT));
}
- if (mnuClean != null) {
- mnuClean.setEnabled(getConnectedUser().hasRole(XemeliosUser.ROLE_CLEAN));
+ if (MainWindow.this.mnuClean != null) {
+ MainWindow.this.mnuClean.setEnabled(MainWindow.this.getConnectedUser().hasRole(XemeliosUser.ROLE_CLEAN));
}
- if (mnuSupprimer != null) {
- mnuSupprimer.setEnabled(getConnectedUser().hasRole(XemeliosUser.ROLE_CLEAN));
+ if (MainWindow.this.mnuSupprimer != null) {
+ MainWindow.this.mnuSupprimer.setEnabled(MainWindow.this.getConnectedUser().hasRole(XemeliosUser.ROLE_CLEAN));
}
- if (mnuConfigExports != null) {
- mnuConfigExports.setEnabled(getConnectedUser().hasRole(XemeliosUser.ROLE_EXPORT));
+ if (MainWindow.this.mnuConfigExports != null) {
+ MainWindow.this.mnuConfigExports.setEnabled(MainWindow.this.getConnectedUser().hasRole(XemeliosUser.ROLE_EXPORT));
}
}
};
}
public StartListener getStartListener() {
- return startListener;
+ return this.startListener;
}
public static MainWindow getInstance() {
- return instance;
+ return MainWindow.instance;
}
@Override
protected void finalize() {
- instance = null;
+ MainWindow.instance = null;
try {
if (DataLayerManager.getImplementation() != null) {
DataLayerManager.getImplementation().shutdown();
}
- } catch (DataConfigurationException dce) {
- logger.error(dce, dce);
+ } catch (final DataConfigurationException dce) {
+ MainWindow.logger.error(dce, dce);
}
}
protected void applyPatches() {
- AbstractConfigurator ac = new Log4JPatch();
+ final AbstractConfigurator ac = new Log4JPatch();
if (ac != null) {
try {
- ac.setProperties(applicationProperties);
+ ac.setProperties(this.applicationProperties);
ac.run();
- } catch (Exception ex) {
- logger.error("while applying patches", ex);
+ } catch (final Exception ex) {
+ MainWindow.logger.error("while applying patches", ex);
System.exit(2);
}
}
public ImportContent() {
super();
- filesToImport = new ArrayList<File>();
- pjs = new ArrayList<PJRef>();
+ this.filesToImport = new ArrayList<File>();
+ this.pjs = new ArrayList<PJRef>();
}
- public void setFilesToImport(ArrayList<File> array) {
+ public void setFilesToImport(final ArrayList<File> array) {
this.filesToImport = array;
}
public ArrayList<File> getFilesToImport() {
- return filesToImport;
+ return this.filesToImport;
}
public ArrayList<PJRef> getPjs() {
- return pjs;
+ return this.pjs;
}
public int getImportCount() {
- return filesToImport.size() + pjs.size();
+ return this.filesToImport.size() + this.pjs.size();
}
}
public JDesktopPane getDesk() {
- return desk;
+ return this.desk;
}
private void exporterFichier() {
- DlgExportAll dga = new DlgExportAll(this, true, DlgChooseDocuments.DIALOG_TYPE.FILE, docModels, getConnectedUser());
+ final DlgExportAll dga = new DlgExportAll(this, true, DlgChooseDocuments.DIALOG_TYPE.FILE, this.docModels, this.getConnectedUser());
dga.setVisible(true);
}
@Override
protected Boolean doInBackground() {
try {
- uu = new UpdateUtil(applicationProperties, getUpdaterProgress());
- 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);
+ this.uu = new UpdateUtil(MainWindow.this.applicationProperties, MainWindow.this.getUpdaterProgress());
+ this.uu.setCheckMethod(Constants.MAJ_CONFIRM); // on force pour avoir le MsgDialog de fin pour indiquer que c'est terminé
+ this.uu.checkForUpdates();
+ return this.uu.updateNeeded();
+ } catch (final Exception ex) {
+ MainWindow.logger.error("while checking updates availability", ex);
return false;
}
}
@Override
protected void done() {
try {
- uu.doUpdates();
- } catch (Throwable t) {
+ this.uu.doUpdates();
+ } catch (final Throwable t) {
}
}
}
protected Boolean doInBackground() {
try {
- uuu = new UpdateUtil(applicationProperties, getUpdaterProgress());
- 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());
+ this.uuu = new UpdateUtil(MainWindow.this.applicationProperties, MainWindow.this.getUpdaterProgress());
+ this.uuu.setCheckMethod(MainWindow.this.applicationProperties.getProperty(Constants.SYS_PROP_MAJ_STRATEGY));
+ this.uuu.checkForUpdates();
+ return this.uuu.updateNeeded();
+ } catch (final UnknownHostException ioEx) {
+ MainWindow.logger.info("Impossible d'accéder à " + ioEx.getMessage());
return false;
- } catch (Exception ex) {
+ } catch (final 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);
+ MainWindow.logger.error("while checking updates availability", ex);
// JOptionPane.showMessageDialog(MainWindow.instance, ex.getMessage(), "Erreur", JOptionPane.ERROR_MESSAGE);
return false;
}
@Override
protected void done() {
try {
- String checkMethod = applicationProperties.getProperty(Constants.SYS_PROP_MAJ_STRATEGY);
- if ((checkMethod == null || checkMethod.isEmpty() || "false".equals(checkMethod)))
+ String checkMethod = MainWindow.this.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);
+ }
+ MainWindow.logger.debug("start done... checkMethod=" + checkMethod);
- if (get().booleanValue()) {
+ if (this.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());
+ bDoUpdate = (JOptionPane.YES_OPTION == new DlgConfirmDownloadUpdate(MainWindow.this, this.uuu).run());
}
if (bDoUpdate) {
- logger.debug("doUpdates()...");
- uuu.doUpdates();
+ MainWindow.logger.debug("doUpdates()...");
+ this.uuu.doUpdates();
}
- logger.debug("end done...");
+ MainWindow.logger.debug("end done...");
}
- } catch (Throwable t) {
+ } catch (final Throwable t) {
}
}
}
protected JMenu loadToolMenu() {
- JMenu ret = new JMenu("Outils");
- String sDir = applicationProperties.getProperty(Constants.SYS_PROP_XEMELIOS_TOOLS_DIR);
+ final JMenu ret = new JMenu("Outils");
+ final String sDir = this.applicationProperties.getProperty(Constants.SYS_PROP_XEMELIOS_TOOLS_DIR);
if (sDir != null) {
- String[] directories = sDir.split(",");
+ final String[] directories = sDir.split(",");
for (String currentDirectory : directories) {
// replacing ${....} variables
- currentDirectory = applicationProperties.replace(currentDirectory);
- File dir = new File(currentDirectory);
+ currentDirectory = this.applicationProperties.replace(currentDirectory);
+ final File dir = new File(currentDirectory);
if (dir.exists() && dir.isDirectory()) {
- String installedFileLocation = applicationProperties.getProperty(Constants.SYS_PROP_INSTALLED_FILENAME);
+ final String installedFileLocation = this.applicationProperties.getProperty(Constants.SYS_PROP_INSTALLED_FILENAME);
InstalledModel installedComponents = new InstalledModel(InstalledModel.QN);
try {
installedComponents = InstalledModel.readFromFile(installedFileLocation);
- } catch (Exception ex) {
- logger.error("unable to find " + installedFileLocation);
+ } catch (final Exception ex) {
+ MainWindow.logger.error("unable to find " + installedFileLocation);
}
- File[] jars = dir.listFiles(new java.io.FileFilter() {
+ final File[] jars = dir.listFiles(new java.io.FileFilter() {
@Override
- public boolean accept(File pathname) {
+ public boolean accept(final File pathname) {
return (pathname.getName().toUpperCase().endsWith(".JAR"));
}
});
- for (File jar : jars) {
+ for (final File jar : jars) {
try {
- logger.debug("looking into " + jar.toURI().toURL().toExternalForm());
- JarFile jf = new JarFile(jar);
- Manifest mn = jf.getManifest();
+ MainWindow.logger.debug("looking into " + jar.toURI().toURL().toExternalForm());
+ final JarFile jf = new JarFile(jar);
+ final Manifest mn = jf.getManifest();
// System.out.println("***************************************************************************");
- String toolClassName = mn.getMainAttributes().getValue(ToolConstants.TOOL_CLASS);
+ final String toolClassName = mn.getMainAttributes().getValue(ToolConstants.TOOL_CLASS);
// System.out.println(toolClassName);
- String toolRequires = mn.getMainAttributes().getValue(ToolConstants.TOOL_REQUIRES);
+ final String toolRequires = mn.getMainAttributes().getValue(ToolConstants.TOOL_REQUIRES);
String toolDescription = null;
- String toolIcon = mn.getMainAttributes().getValue(ToolConstants.TOOL_ICON);
+ final 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("#");
+ final String[] requiredComps = toolRequires.split(",");
+ for (final String comp : requiredComps) {
+ final String[] compDetails = comp.split("#");
if (compDetails.length == 2) {
- ComponentModel existingComponent = installedComponents.getComponent(compDetails[0]);
+ final ComponentModel existingComponent = installedComponents.getComponent(compDetails[0]);
if (existingComponent == null) {
throw new Exception("Component " + compDetails[0] + " (" + compDetails[1] + ") required");
}
}
// tout est OK, on crée un ClassLoader pour cet outil
ClassLoader classLoader = null;
- if (!"true".equals(applicationProperties.getProperty(Constants.SYS_PROP_XEMELIOS_AVOID_TOOL_JAR_LOADING))) {
- logger.debug(jar.toURI().toURL().toExternalForm());
+ if (!"true".equals(this.applicationProperties.getProperty(Constants.SYS_PROP_XEMELIOS_AVOID_TOOL_JAR_LOADING))) {
+ MainWindow.logger.debug(jar.toURI().toURL().toExternalForm());
// on met un JarClassLoader pour ne pas verrouiller le fichier, qui n'est en fait pas utilisé pour le moment...
classLoader = new JarClassLoader();
((JarClassLoader) classLoader).add(jar.toURI().toURL());
Class clazz = null;
try {
clazz = Class.forName(toolClassName, true, classLoader);
- Class menuTitleClass = Class.forName(MenuTitle.class.getName(), true, classLoader);
+ final Class menuTitleClass = Class.forName(MenuTitle.class.getName(), true, classLoader);
@SuppressWarnings("unchecked")
- Object mt = clazz.getAnnotation(menuTitleClass);
+ final Object mt = clazz.getAnnotation(menuTitleClass);
if (mt != null) {
toolDescription = menuTitleClass.getMethod("value").invoke(mt).toString();
} else {
- logger.error("Plugin Class " + toolClassName + " doesn't provide annotation @MenuTitle");
+ MainWindow.logger.error("Plugin Class " + toolClassName + " doesn't provide annotation @MenuTitle");
}
- } catch (Exception ex) {
- logger.error(ex.getMessage(), ex);
+ } catch (final Exception ex) {
+ MainWindow.logger.error(ex.getMessage(), ex);
}
if (toolDescription != null && toolDescription.length() > 0) {
Action a = null;
if (toolIcon != null) {
- ImageIcon img = IhmFactory.getIconFromResource(toolIcon, classLoader);
+ final ImageIcon img = IhmFactory.getIconFromResource(toolIcon, classLoader);
if (img != null) {
a = new ActionPlugin(jar.toURI().toURL(), toolClassName, toolDescription, img);
} else {
} else {
a = new ActionPlugin(jar.toURI().toURL(), toolClassName, toolDescription);
}
- JMenuItem mnuItem = new JMenuItem(a);
+ final JMenuItem mnuItem = new JMenuItem(a);
ret.add(mnuItem);
}
- } catch (Exception ex) {
- logger.info("can not install plugin " + toolClassName + ": " + ex.getMessage());
+ } catch (final Exception ex) {
+ MainWindow.logger.info("can not install plugin " + toolClassName + ": " + ex.getMessage());
continue;
}
}
- } catch (Throwable t) {
+ } catch (final Throwable t) {
}
}
}
}
public PropertiesExpansion getEnvProperties() {
- return applicationProperties;
+ return this.applicationProperties;
}
private void doFirstStartConfiguration() {
- getStartListener().setVisible(false);
+ this.getStartListener().setVisible(false);
try {
- WizardPage.WizardResultProducer producer = new WizardPage.WizardResultProducer() {
+ final WizardPage.WizardResultProducer producer = new WizardPage.WizardResultProducer() {
@Override
- public boolean cancel(Map map) {
+ public boolean cancel(final Map map) {
return true;
}
@Override
- public Object finish(Map map) throws WizardException {
+ public Object finish(final 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");
+ final Properties props = new Properties();
+ final File f = new File(new File(MainWindow.this.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());
+ } catch (final IOException ioEx) {
+ MainWindow.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");
+ MainWindow.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");
+ MainWindow.this.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");
+ MainWindow.this.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);
+ MainWindow.this.getEnvProperties().remove(Constants.SYS_PROP_PROXY_DOMAIN);
+ MainWindow.this.getEnvProperties().remove(Constants.SYS_PROP_PROXY_PASSWD);
+ MainWindow.this.getEnvProperties().remove(Constants.SYS_PROP_PROXY_USER);
} else {
- logger.debug("on est pas dans le trésor");
+ MainWindow.logger.debug("on est pas dans le trésor");
if (Boolean.TRUE.equals(map.get("is.use.proxy"))) {
- logger.debug("on utilise un proxy");
+ MainWindow.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"))) {
+ MainWindow.this.getEnvProperties().setProperty(Constants.SYS_PROP_PROXY_SERVER, map.get("proxy.server").toString());
+ if (MainWindow.this.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());
+ MainWindow.this.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);
+ MainWindow.this.getEnvProperties().remove(Constants.SYS_PROP_PROXY_PORT);
}
- if (exists(map.get("proxy.user"))) {
+ if (MainWindow.this.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"))) {
+ MainWindow.this.getEnvProperties().setProperty(Constants.SYS_PROP_PROXY_USER, map.get("proxy.user").toString());
+ if (MainWindow.this.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());
+ MainWindow.this.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);
+ MainWindow.this.getEnvProperties().remove(Constants.SYS_PROP_PROXY_PASSWD);
}
- if (exists(map.get("proxy.domain"))) {
+ if (MainWindow.this.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());
+ MainWindow.this.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);
+ MainWindow.this.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);
+ MainWindow.this.getEnvProperties().remove(Constants.SYS_PROP_PROXY_USER);
+ MainWindow.this.getEnvProperties().remove(Constants.SYS_PROP_PROXY_PASSWD);
+ MainWindow.this.getEnvProperties().remove(Constants.SYS_PROP_PROXY_DOMAIN);
}
} else {
- logger.debug("on n'utilise pas de proxy");
+ MainWindow.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);
+ MainWindow.this.getEnvProperties().remove(Constants.SYS_PROP_PROXY_SERVER);
+ MainWindow.this.getEnvProperties().remove(Constants.SYS_PROP_PROXY_PORT);
+ MainWindow.this.getEnvProperties().remove(Constants.SYS_PROP_PROXY_USER);
+ MainWindow.this.getEnvProperties().remove(Constants.SYS_PROP_PROXY_PASSWD);
+ MainWindow.this.getEnvProperties().remove(Constants.SYS_PROP_PROXY_DOMAIN);
}
}
props.setProperty(Constants.SYS_PROP_FIRST_START, "true");
- getEnvProperties().setProperty(Constants.SYS_PROP_FIRST_START, "true");
+ MainWindow.this.getEnvProperties().setProperty(Constants.SYS_PROP_FIRST_START, "true");
try {
props.store(new FileOutputStream(f), null);
- } catch (IOException ioEx) {
+ } catch (final IOException ioEx) {
// meme pas j'y crois
}
try {
- UpdateUtil uu = new UpdateUtil(getEnvProperties(), getUpdaterProgress());
+ final UpdateUtil uu = new UpdateUtil(MainWindow.this.getEnvProperties(), MainWindow.this.getUpdaterProgress());
uu.checkForUpdates();
if (uu.updateNeeded()) {
uu.doUpdates();
}
- } catch (Exception ex) {
- logger.error("first update", ex);
+ } catch (final Exception ex) {
+ MainWindow.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) {
+ final Wizard wiz = WizardPage.createWizard(new Class[] { PnlPresentation.class, PnlFirstConfigProxy.class, PnlFirstAbo.class }, producer);
+ final Map response = (Map) WizardDisplayer.showWizard(wiz);
+ } catch (final Throwable t) {
t.printStackTrace();
}
- getStartListener().setVisible(true);
+ this.getStartListener().setVisible(true);
}
- private boolean exists(Object o) {
+ private boolean exists(final Object o) {
return o != null && o.toString().length() > 0;
}
private static final long serialVersionUID = 1L;
private String className = null;
- private URL jarUrl;
+ private final URL jarUrl;
- public ActionPlugin(URL jarUrl, String className, String desc) {
+ public ActionPlugin(final URL jarUrl, final String className, final String desc) {
super(desc);
this.jarUrl = jarUrl;
this.className = className;
}
- public ActionPlugin(URL jarUrl, String className, String desc, Icon icon) {
+ public ActionPlugin(final URL jarUrl, final String className, final String desc, final Icon icon) {
super(desc, icon);
this.jarUrl = jarUrl;
this.className = className;
}
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(final ActionEvent e) {
try {
// URLClassLoader cl = new URLClassLoader(new URL[] {jarUrl},this.getClass().getClassLoader());
ClassLoader cl = null;
- if (!"true".equals(applicationProperties.getProperty(Constants.SYS_PROP_XEMELIOS_AVOID_TOOL_JAR_LOADING))) {
+ if (!"true".equals(MainWindow.this.applicationProperties.getProperty(Constants.SYS_PROP_XEMELIOS_AVOID_TOOL_JAR_LOADING))) {
// cl = new ToolClassLoader(getClass().getClassLoader(), jarUrl);
- cl = new URLClassLoader(new URL[] { jarUrl }, this.getClass().getClassLoader());
+ cl = new URLClassLoader(new URL[] { this.jarUrl }, this.getClass().getClassLoader());
} else {
cl = this.getClass().getClassLoader();
}
// TODO: autoriser l'accès aux classes du classloader parent
- Class clazz = Class.forName(className, true, cl);
- Class abstractToolClass = Class.forName(AbstractTool.class.getName(), true, cl);
+ final Class clazz = Class.forName(this.className, true, cl);
+ final Class abstractToolClass = Class.forName(AbstractTool.class.getName(), true, cl);
final Object o = clazz.newInstance();
if (abstractToolClass.isAssignableFrom(clazz)) {
// AbstractTool at = (AbstractTool) o;
// at.run();
final Method meth = clazz.getMethod("run");
- Runnable runner = new Runnable() {
+ final Runnable runner = new Runnable() {
@Override
public void run() {
try {
meth.invoke(o);
- } catch (Throwable t) {
- logger.error(t.getMessage(), t);
+ } catch (final Throwable t) {
+ MainWindow.logger.error(t.getMessage(), t);
}
}
};
- Thread th = new Thread(runner);
+ final Thread th = new Thread(runner);
th.setContextClassLoader(cl);
th.run();
} else {
- throw new Exception(className + " does not extends " + AbstractTool.class.getName());
+ throw new Exception(this.className + " does not extends " + AbstractTool.class.getName());
}
- } catch (Exception ex) {
+ } catch (final Exception ex) {
new DisplayExceptionDlg(MainWindow.instance, ex);
}
}
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() {
+ this.add(new JLabel("Active(s): "));
+ this.add(this.lblActive = new JLabel("0"));
+ this.add(new JLabel(" Idle(s): "));
+ this.add(this.lblIdle = new JLabel("0"));
+ final Timer timer = new Timer(500, new ActionListener() {
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(final 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()));
+ final Pool pool = PoolManager.getInstance().getPool();
+ PoolStatDisplayer.this.lblActive.setText(Integer.toString(pool.getNumActive()));
+ PoolStatDisplayer.this.lblIdle.setText(Integer.toString(pool.getNumIdle()));
}
- } catch (Exception ex) {
+ } catch (final Exception ex) {
// TODO
}
}
public static class XemeliosArchiveImporterWorker extends SwingWorker<Errors, String> {
- private ArchiveImporter importer;
+ private final ArchiveImporter importer;
private Errors errors;
- public XemeliosArchiveImporterWorker(ArchiveImporter importer) {
+ public XemeliosArchiveImporterWorker(final ArchiveImporter importer) {
super();
this.importer = importer;
}
@Override
protected Errors doInBackground() throws Exception {
- errors = importer.doImport();
- return errors;
+ this.errors = this.importer.doImport();
+ return this.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()));
+ final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
+ MainWindow.logger.debug("Fin import archive a " + sdf.format(new Date()));
- if (errors != null && !errors.getErrors().isEmpty()) {
- StringBuilder sb = new StringBuilder("Erreur lors de l'import de l'archive : \n");
+ if (this.errors != null && !this.errors.getErrors().isEmpty()) {
+ final StringBuilder sb = new StringBuilder("Erreur lors de l'import de l'archive : \n");
- for (Errors.Error error : errors.getErrors()) {
+ for (final Errors.Error error : this.errors.getErrors()) {
sb.append("<").append(error.getSeverityMessage()).append("> ").append(error.getMessage()).append("\n");
}
- logger.warn(sb.toString());
+ MainWindow.logger.warn(sb.toString());
JOptionPane.showMessageDialog(MainWindow.getInstance(), sb.toString());
} else {
}
private Properties getHomeProperties() {
- File f = new File(System.getProperty("user.home"), "xemelios.properties");
- Properties props = new Properties();
+ final File f = new File(System.getProperty("user.home"), "xemelios.properties");
+ final Properties props = new Properties();
if (f.exists()) {
try {
props.load(new FileInputStream(f));
- } catch (IOException ioEx) {
+ } catch (final IOException ioEx) {
}
}
return props;
}
public PnlUpdaterProgress getUpdaterProgress() {
- return pup;
+ return this.pup;
}
}
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 java.awt.Cursor;
+
import javax.swing.JDialog;
import javax.swing.JTree;
import javax.swing.ScrollPaneConstants;
import javax.swing.tree.TreeSelectionModel;
+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.common.config.DocumentsModel;
+import fr.gouv.finances.dgfip.xemelios.data.DatabaseTreeDataDonnee;
import fr.gouv.finances.dgfip.xemelios.data.WaitableUI;
-import java.awt.Cursor;
/**
- *
- * @author nicolas.lecorre
+ *
+ * @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);
+ private final XemeliosUser user;
+ private final PropertiesExpansion applicationConfiguration;
- 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);
+ /** Creates new form PanelCleanDatabaseDonnees */
+ public PanelChooseDatabaseDonnees(final JDialog p, final DocumentsModel d, final XemeliosUser user, final PropertiesExpansion applicationConfiguration) {
+ this.dms = d;
+ this.user = user;
+ this.applicationConfiguration = applicationConfiguration;
+ try {
+ this.initComponents();
+ } catch (final UnauthorizedException ex) {
+ //
+ }
+ }
- jScrollPane1.setViewportView(jTree1);
+ /**
+ * This method is called from within the constructor to initialize the form.
+ */
+ private void initComponents() throws UnauthorizedException {
+ this.jPanel2 = new javax.swing.JPanel();
+ this.jLabel1 = new javax.swing.JLabel();
+ this.jTree1 = new JTree(new DatabaseTreeDataDonnee(this.dms, this, this.user, this.applicationConfiguration));
+ this.jTree1.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
+ this.jTree1.setScrollsOnExpand(true);
+ this.jScrollPane1 = new javax.swing.JScrollPane(this.jTree1);
+ this.jScrollPane1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
- 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())
- );
+ this.jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Documents"));
+ this.jPanel2.setMinimumSize(new java.awt.Dimension(1100, 83));
+ this.jPanel2.setPreferredSize(new java.awt.Dimension(239, 384));
+ this.jLabel1.setText("S\u00e9lectionnez dans la liste ci-dessous le ou les \u00e9l\u00e9ment(s)");
+ this.jLabel1.setVerticalAlignment(javax.swing.SwingConstants.TOP);
- 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;
+ this.jScrollPane1.setViewportView(this.jTree1);
+
+ final org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(this.jPanel2);
+ this.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(this.jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 642, Short.MAX_VALUE).add(this.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(this.jLabel1).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 323, Short.MAX_VALUE).addContainerGap()));
+
+ final 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(this.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(this.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;
+ return this.jTree1;
}
- public void startWait() {
- setCursor(new Cursor(Cursor.WAIT_CURSOR));
- }
+ @Override
+ public void startWait() {
+ this.setCursor(new Cursor(Cursor.WAIT_CURSOR));
+ }
- public void stopWait() {
- setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
- }
+ @Override
+ public void stopWait() {
+ this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
+ }
}
package fr.gouv.finances.cp.xemelios.ui;
-import fr.gouv.finances.cp.utils.PropertiesExpansion;
import java.awt.Component;
import java.util.Vector;
import org.apache.log4j.Logger;
import org.jdesktop.swingx.JXTreeTable;
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
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.data.ExportableData;
/**
- *
- * @author nicolas.lecorre
+ *
+ * @author nicolas.lecorre
*/
@SuppressWarnings("serial")
public class PanelChooseDatabaseFichier extends javax.swing.JPanel {
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;
+ private final XemeliosUser user;
+
+ private final PropertiesExpansion applicationConfiguration;
+
+ public DatabaseTreeDataFichier getData() {
+ return this.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 PanelChooseDatabaseFichier(final JDialog p, final DocumentsModel d, final boolean selectionMultiple, final XemeliosUser user, final PropertiesExpansion applicationConfiguration) {
+ this.dms = d;
+ this.selectionMultiple = selectionMultiple;
+ this.user = user;
+ this.applicationConfiguration = applicationConfiguration;
+ this.initComponents();
+ try {
+ this.fillDocType();
+ } catch (final UnauthorizedException ex) {
+ //
+ }
+ this.data = new DatabaseTreeDataFichier(this.listeFichiers);
+ this.data.setMode(this.getMode());
+ this.data.setSelectionMultiple(this.selectionMultiple);
+ this.listeFichiers.setTreeTableModel(this.data);
+ this.listeFichiers.setRootVisible(false);
+ }
+
+ private void fillDocType() throws UnauthorizedException {
+ final Vector<Pair> v = new Vector<Pair>();
+ v.add(new Pair("RIEN", "Tous"));
+ this.cbTypeDoc.addItem(new Pair("RIEN", "Tous"));
+ for (final DocumentModel d : this.dms.getDocuments()) {
+ if (d.getDisplayInMenuIf() == null || "true".equals(this.applicationConfiguration.getProperty(d.getDisplayInMenuIf()))) {
+ v.add(new Pair(d.getId(), d.getTitre()));
+ }
+ }
+ this.cbTypeDoc.setModel(new javax.swing.DefaultComboBoxModel(v));
+ this.fillColl();
+ this.fillBudg();
+ }
+
+ private void fillColl() throws UnauthorizedException {
+ final String selectedDocId = ((Pair) this.cbTypeDoc.getSelectedItem()).key;
+ final Vector<Pair> v = new Vector<Pair>();
+ v.add(new Pair("RIEN", "Toutes"));
+ if (!"RIEN".equals(selectedDocId)) {
+ final DocumentModel selectedDocumentModel = this.dms.getDocumentById(selectedDocId);
+ final Vector<Pair> collectivites = this.getCollectivitesFromDocumentModel(selectedDocumentModel);
+ v.addAll(collectivites);
+ }
+ this.cbCollectivite.setModel(new javax.swing.DefaultComboBoxModel(v));
+ this.fillBudg();
+ }
+
+ private void fillBudg() {
+ final String selectedDocId = ((Pair) this.cbTypeDoc.getSelectedItem()).key;
+ final Pair selectedColl = (Pair) this.cbCollectivite.getSelectedItem();
+ final Vector<Pair> v = new Vector<Pair>();
+ v.add(new Pair("RIEN", "Tous"));
+ if (!"RIEN".equals(selectedColl.key)) {
+ final DocumentModel selectedDocumentModel = this.dms.getDocumentById(selectedDocId);
+ try {
+ final Vector<Pair> budgets = DataLayerManager.getImplementation().getBudgets(selectedDocumentModel, selectedColl, this.user);
+ v.addAll(budgets);
+ } catch (final 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(final DocumentModel dm) throws UnauthorizedException {
+ Vector<Pair> ret = null;
+ try {
+ // TODO: mettre la hierarchie de collectivites
+ ret = DataLayerManager.getImplementation().getCollectivites(dm, null, this.user);
+ } catch (final DataAccessException daEx) {
+ logger.warn("", daEx);
+ ret = new Vector<Pair>();
+ } catch (final 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() {
+ this.jPanel2 = new javax.swing.JPanel();
+ this.jScrollPane2 = new javax.swing.JScrollPane();
+ this.listeFichiers = new JXTreeTablePropertyEditor(this.selectionMultiple);
+ this.bSelectAll = new javax.swing.JButton();
+ this.bUnSelectAll = new javax.swing.JButton();
+ this.jPanel1 = new javax.swing.JPanel();
+ this.jLabel1 = new javax.swing.JLabel();
+ this.cbCollectivite = new javax.swing.JComboBox();
+ this.jLabel2 = new javax.swing.JLabel();
+ this.jLabel3 = new javax.swing.JLabel();
+ this.cbBudget = new javax.swing.JComboBox();
+ this.jLabel4 = new javax.swing.JLabel();
+ this.cbTypeDoc = new javax.swing.JComboBox();
+ this.bRechercher = new javax.swing.JButton();
+
+ this.jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Documents"));
+ this.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) {
+ this.listeFichiers.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
+ }
+ this.listeFichiers.setRootVisible(true);
+ this.listeFichiers.setShowHorizontalLines(true);
+ this.listeFichiers.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_LAST_COLUMN);
+ this.jScrollPane2.setViewportView(this.listeFichiers);
+
+ this.bSelectAll.setText("Tout s\u00e9lectionner");
+ this.bUnSelectAll.setText("Tout d\u00e9s\u00e9lectionner");
+
+ if (!this.selectionMultiple) {
+ this.bSelectAll.setEnabled(false);
+ this.bUnSelectAll.setEnabled(false);
+ }
+
+ final org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(this.jPanel2);
+ this.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(this.jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 642, Short.MAX_VALUE))
+ .add(jPanel2Layout.createSequentialGroup().add(204, 204, 204).add(this.bSelectAll).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.bUnSelectAll))).addContainerGap()));
+ jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(
+ jPanel2Layout.createSequentialGroup().add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE).add(this.bSelectAll).add(this.bUnSelectAll)).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(this.jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE).addContainerGap()));
+
+ this.jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Recherche"));
+ this.jPanel1.setMinimumSize(new java.awt.Dimension(0, 0));
+ this.jPanel1.setPreferredSize(new java.awt.Dimension(0, 0));
+ this.jLabel1.setText("S\u00e9lectionnez dans la liste ci-dessous le type de document, la collectivit\u00e9 et le budget");
+ this.jLabel1.setVerticalAlignment(javax.swing.SwingConstants.TOP);
+
+ this.cbCollectivite.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
+ this.cbCollectivite.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PanelChooseDatabaseFichier.this.cbCollectiviteActionPerformed(evt);
+ }
+ });
+
+ this.jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
+ this.jLabel2.setText("Collectivit\u00e9");
+
+ this.jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
+ this.jLabel3.setText("Budget");
+
+ this.cbBudget.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
+ this.cbBudget.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PanelChooseDatabaseFichier.this.cbBudgetActionPerformed(evt);
+ }
+ });
+
+ this.jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
+ this.jLabel4.setText("Type de document");
+
+ this.cbTypeDoc.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
+ this.cbTypeDoc.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PanelChooseDatabaseFichier.this.cbTypeDocActionPerformed(evt);
+ }
+ });
+
+ this.bRechercher.setText("Rechercher");
+ this.bRechercher.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PanelChooseDatabaseFichier.this.bRechercherActionPerformed(evt);
+ }
+ });
+
+ this.bSelectAll.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PanelChooseDatabaseFichier.this.bSelectAllPerformed(evt);
+ }
+ });
+
+ this.bUnSelectAll.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PanelChooseDatabaseFichier.this.bUnSelectAllPerformed(evt);
+ }
+ });
+
+ final org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(this.jPanel1);
+ this.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(this.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(this.jLabel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .add(this.jLabel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, this.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(this.cbBudget, 0, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .add(this.cbTypeDoc, 0, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).add(this.cbCollectivite, 0, 313, Short.MAX_VALUE)).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 94, Short.MAX_VALUE).add(this.bRechercher)))
+ .addContainerGap()));
+
+ jPanel1Layout.linkSize(new java.awt.Component[] { this.jLabel2, this.jLabel3, this.jLabel4 }, org.jdesktop.layout.GroupLayout.HORIZONTAL);
+
+ jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(
+ jPanel1Layout
+ .createSequentialGroup()
+ .add(this.jLabel1)
+ .add(19, 19, 19)
+ .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE).add(this.jLabel4).add(this.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(this.jLabel2).add(this.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(this.jLabel3).add(this.cbBudget, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .add(this.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[] { this.cbBudget, this.cbCollectivite, this.cbTypeDoc }, org.jdesktop.layout.GroupLayout.VERTICAL);
+
+ final 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, this.jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 680, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.LEADING, this.jPanel2, 0, 680, Short.MAX_VALUE)).addContainerGap()));
+ layout.setVerticalGroup(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(
+ layout.createSequentialGroup().addContainerGap().add(this.jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 154, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(this.jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addContainerGap()));
+ }
+
+ private void cbTypeDocActionPerformed(final java.awt.event.ActionEvent evt) {
+ try {
+ this.fillColl();
+ } catch (final UnauthorizedException ex) {
+
+ }
+ }
+
+ private void bSelectAllPerformed(final java.awt.event.ActionEvent evt) {
+ this.selectAllChilds(this.data.getData(), true);
+ this.listeFichiers.repaint();
+ }
+
+ private void bUnSelectAllPerformed(final java.awt.event.ActionEvent evt) {
+ this.selectAllChilds(this.data.getData(), false);
+ this.listeFichiers.repaint();
+ }
+
+ private void selectAllChilds(final ExportableData d, final boolean selected) {
+ for (final ExportableData dd : d.getChilds()) {
+ dd.setSelected(selected);
+ this.selectAllChilds(dd, selected);
+ }
+ }
+
+ private void bRechercherActionPerformed(final java.awt.event.ActionEvent evt) {
+ try {
+ String coll = ((Pair) this.cbCollectivite.getSelectedItem()).key;
+ if ("RIEN".equals(coll)) {
+ coll = null;
+ }
+ String budg = ((Pair) this.cbBudget.getSelectedItem()).key;
+ if ("RIEN".equals(budg)) {
+ budg = null;
+ }
+ if (this.cbTypeDoc.getSelectedIndex() == 0) {
+ final Vector<ExportableData> datas = DataLayerManager.getImplementation().searchFichiers(this.dms, coll, budg, this.user);
+ this.data = new DatabaseTreeDataFichier(datas, this.listeFichiers);
+ this.data.setMode(this.getMode());
+ this.data.setSelectionMultiple(this.selectionMultiple);
+ this.listeFichiers.setTreeTableModel(this.data);
+ this.listeFichiers.getColumnModel().getColumn(1).setMaxWidth(25);
+ this.listeFichiers.setRootVisible(true);
+ } else {
+ final String selectedDocId = ((Pair) this.cbTypeDoc.getSelectedItem()).key;
+ final Vector<ExportableData> datas = new Vector<ExportableData>();
+ final ExportableData d = DataLayerManager.getImplementation().searchFichiers(this.dms.getDocumentById(selectedDocId), coll, budg, this.user);
+ if (d != null) {
+ datas.add(d);
+ }
+ this.data = new DatabaseTreeDataFichier(datas, this.listeFichiers);
+ this.data.setMode(this.getMode());
+ this.data.setSelectionMultiple(this.selectionMultiple);
+ this.listeFichiers.setTreeTableModel(this.data);
+ this.listeFichiers.getColumnModel().getColumn(1).setMaxWidth(25);
+ this.listeFichiers.setRootVisible(true);
+ }
+ } catch (final Exception e) {
+ logger.error("", e);
+ }
+ }
+
+ public void refresh() {
+ this.bRechercherActionPerformed(null);
+ }
+
+ private void cbBudgetActionPerformed(final java.awt.event.ActionEvent evt) {
+ // TODO add your handling code here:
+ }
+
+ private void cbCollectiviteActionPerformed(final java.awt.event.ActionEvent evt) {
+ this.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;
+ return this.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);
- }
+ private class JXTreeTablePropertyEditor extends JXTreeTable {
+ private TableCellEditor booleanEditor;
+ private TableCellRenderer booleanRenderer, booleanRendererExclusif, blankRenderer;
+ private boolean selectionMultiple = true;
+
+ // private TreeTableModel model = null;
+ public JXTreeTablePropertyEditor(final boolean selectionMultiple) {
+ super();
+ this.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
+ this.selectionMultiple = selectionMultiple;
+ this.booleanEditor = new DefaultCellEditor(new JCheckBox()) {
+ @Override
+ public Component getTableCellEditorComponent(final JTable table, final Object value, final boolean isSelected, final int row, final int column) {
+ final Component c = super.getTableCellEditorComponent(table, value, isSelected, row, column);
+ final JCheckBox chk = (JCheckBox) this.editorComponent;
+ chk.setSelected(((Boolean) value).booleanValue());
+ chk.setBackground(c.getBackground());
+ return chk;
+ }
+ };
+ this.booleanRendererExclusif = new DefaultTableCellRenderer() {
+ private final JRadioButton rb = new JRadioButton();
+
+ @Override
+ public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) {
+ final JLabel lbl = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
+ this.rb.setSelected(((Boolean) value).booleanValue());
+ this.rb.setBackground(lbl.getBackground());
+ this.rb.setBorder(lbl.getBorder());
+ return this.rb;
+ }
+ };
+ this.booleanRenderer = new DefaultTableCellRenderer() {
+ private final JCheckBox chk = new JCheckBox();
+
+ @Override
+ public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) {
+ final JLabel lbl = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
+ this.chk.setSelected(((Boolean) value).booleanValue());
+ this.chk.setBackground(lbl.getBackground());
+ this.chk.setBorder(lbl.getBorder());
+ return this.chk;
+ }
+ };
+ this.blankRenderer = new DefaultTableCellRenderer() {
+ @Override
+ public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) {
+ final JLabel lbl = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
+ lbl.setText("");
+ return lbl;
+ }
+ };
+ }
+
+ @Override
+ public TableCellEditor getCellEditor(final int row, final int column) {
+ if (row > 0 && column == 1) {
+ if (this.selectionMultiple) {
+ return this.booleanEditor;
+ } else {
+ return this.booleanEditor;// booleanEditorExclusif;
+ }
+ } else {
+ return super.getCellEditor(row, column);
+ }
+ }
+
+ @Override
+ public TableCellRenderer getCellRenderer(final int row, final int column) {
+ if (row == 0 && column == 1) {
+ return this.blankRenderer;
+ } else if (column == 1) {
+ if (this.selectionMultiple) {
+ return this.booleanRenderer;
+ } else {
+ final Object o = PanelChooseDatabaseFichier.this.listeFichiers.getPathForRow(row).getLastPathComponent();
+ if (PanelChooseDatabaseFichier.this.data.isCellEditable(o, column)) {
+ return this.booleanRendererExclusif;
+ } else {
+ return this.blankRenderer;
+ }
+ }
+ } else {
+ return super.getCellRenderer(row, column);
+ }
+ }
+ }
+
+ public DocumentModel getDMSelected() {
+ return this.dms.getDocumentById(((Pair) this.cbTypeDoc.getSelectedItem()).key);
+ }
public int getMode() {
- return mode;
+ return this.mode;
}
- public void setMode(int mode) {
+ public void setMode(final int mode) {
this.mode = mode;
}
-
+
}
package fr.gouv.finances.cp.xemelios.ui;
import java.awt.Rectangle;
+import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeListener;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStream;
import java.util.Iterator;
+import javax.swing.JComponent;
import javax.swing.JInternalFrame;
+import javax.swing.KeyStroke;
+import javax.swing.SwingUtilities;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
+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 org.apache.log4j.Logger;
+import org.jdesktop.swingx.JXTable;
+import org.w3c.dom.Document;
-
+import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
+import fr.gouv.finances.cp.xemelios.ui.resulttable.EtatResultTableModel;
+import fr.gouv.finances.cp.xemelios.ui.search.PnlSearch;
import fr.gouv.finances.dgfip.utils.Pair;
import fr.gouv.finances.dgfip.utils.Xslt;
-import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
+import fr.gouv.finances.dgfip.utils.xml.transform.AbstractURIResolver;
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.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 = Xslt.getFile(getElementModel().getParent().getParent(), getElementModel().getParent(), getElementModel(), doc);
- InputStream is = new FileInputStream(f);
-// InputStream htmlStream = DematTransform.transform(doc,is,parameters,f.getParentFile().toURI().toURL().toExternalForm());
- TransformerFactory tFactory = FactoryProvider.getTransformerFactory();
-logger.debug("URI Resolver from "+f.getParentFile().toURI().toURL().toExternalForm());
- URIResolver uriResolver = new CustomURIResolver(tFactory.getURIResolver(), f.getParentFile().toURI().toURL().toExternalForm());
- tFactory.setURIResolver(uriResolver);
- Transformer t = tFactory.newTransformer(new StreamSource(is)); // , f.toURI().toURL().toExternalForm()
- 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; }
+ /**
+ * 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(final MainWindow pf, final DocumentModel dm, final ElementModel em, final XemeliosUser user) throws ToolException {
+ super("Recherche - " + em.getTitre() + " <" + SearchWindow.frameCount + ">", true, true, true);
+ this.user = user;
+ this.em = em;
+ this.rank = SearchWindow.frameCount;
+ final String titre = "Recherche - " + em.getTitre() + " <" + SearchWindow.frameCount++ + ">";
+ final PnlSearch.DisplayParameters dp = new PnlSearch.DisplayParameters();
+ this.pnlSearch = new PnlSearch(dm, em.getParent(), em, dp, user, MainWindow.getInstance().getEnvProperties()) {
+
+ @Override
+ public void resizeParent(final 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(final boolean iconified) {
+ if (iconified) {
+ MainWindow.getInstance().getDesk().getDesktopManager().iconifyFrame(SearchWindow.this);
+ } else {
+ MainWindow.getInstance().getDesk().getDesktopManager().deiconifyFrame(SearchWindow.this);
+ }
+ }
+
+ @Override
+ public void setTitle(final String newTitle) {
+ SearchWindow.this.setTitle(newTitle);
+ }
+
+ @Override
+ public void redisplayTitle() {
+ SearchWindow.this.setTitle(titre);
+ }
+
+ @Override
+ public void startWaiter() {
+ SearchWindow.this.getGlassPane().setVisible(true);
+ }
+
+ @Override
+ public void stopWaiter() {
+ SearchWindow.this.getGlassPane().setVisible(false);
+ this.invalidate();
+ this.repaint();
+ }
+
+ @Override
+ public boolean canExport() {
+ return this.canExport && !(SearchWindow.this.isIcon());
+ }
+
+ @Override
+ public void actionOnRowPerformed(final MouseEvent evt, int row) {
+ if (row >= 0 && evt.getClickCount() == 2 && evt.getButton() == MouseEvent.BUTTON1) {
+ if (this.getElementModel().getXslt() == null || this.getElementModel().getXslt().length() == 0) {
+ return;
+ }
+ try {
+ row = ((JXTable) this.getTable()).convertRowIndexToModel(row);
+ final EtatResultTableModel etrm = (EtatResultTableModel) this.getTable().getModel();
+ final DataHandler dh = etrm.getRowAt(row, 0);
+ final Document doc = dh.getDocument();
+ final String docId = dh.getDocumentId();
+ final XPath xp = FactoryProvider.getXPathFactory().newXPath();
+ // Hashtable<String,Object> parameters = new Hashtable<String,Object>();
+ xp.setNamespaceContext(this.getDocumentModel().getNamespaces());
+ String idRepository = null;
+ if (this.getDocumentModel().getReferenceNomenclaturePath() != null && this.getDocumentModel().getReferenceNomenclaturePath().getCodePath() != null) {
+ idRepository = (String) xp.evaluate(this.getDocumentModel().getReferenceNomenclaturePath().getCodePath().getPath(), doc.getDocumentElement(), XPathConstants.STRING);
+ }
+ if (idRepository != null && !(idRepository.length() > 0)) {
+ idRepository = null;
+ }
+
+ final Document repository = DataLayerManager.getImplementation().getRepositoryAsDom(this.getDocumentModel(), this.getCurrentCollectivite(), idRepository, this.getUser());
+ final File f = Xslt.getFile(this.getElementModel().getParent().getParent(), this.getElementModel().getParent(), this.getElementModel(), doc);
+ final InputStream is = new FileInputStream(f);
+ // InputStream htmlStream = DematTransform.transform(doc,is,parameters,f.getParentFile().toURI().toURL().toExternalForm());
+ final TransformerFactory tFactory = FactoryProvider.getTransformerFactory();
+ final AbstractURIResolver uriResolver = this.getDocumentModel().createUriResolver();
+ AbstractURIResolver.initializationHelper(uriResolver, doc, tFactory.getURIResolver(), f.getParentFile().toURI().toURL().toExternalForm());
+
+ tFactory.setURIResolver(uriResolver);
+
+ SearchWindow.logger.debug("URI Resolver from " + f.getParentFile().toURI().toURL().toExternalForm());
+
+ tFactory.setURIResolver(uriResolver);
+ final Transformer t = tFactory.newTransformer(new StreamSource(is)); // , f.toURI().toURL().toExternalForm()
+ t.setParameter(HtmlViewer.PARAM_DESTINATION, this.getElementModel().getParent().useExternalBrowser() ? HtmlViewer.VALUE_DESTINATION_EXTERNAL : HtmlViewer.VALUE_DESTINATION_INTERNAL);
+ for (int pos = 0; pos < etrm.getHiddens().size(); pos++) {
+ final HiddenModel hm = etrm.getHiddens().get(pos);
+ if (hm.getName().startsWith("xsl-param:")) {
+ final String paramName = hm.getName().substring("xsl-param:".length());
+ final 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", this.getCurrentCollectivite().key);
+ t.setParameter("budget", this.getCurrentBudget().key);
+ t.setParameter("collectivite-lib", this.getCurrentCollectivite().libelle);
+ t.setParameter("budget-lib", this.getCurrentBudget().libelle);
+ t.setParameter("displayedDocId", docId);
+ final ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ t.transform(new DOMSource(doc), new StreamResult(baos));
+ MainWindow.getInstance().displayHtmlStream(new ByteArrayInputStream(baos.toByteArray()), this.getElementModel().getParent(), MainWindow.getInstance().getDesk());
+ } catch (final Exception ex) {
+ new DisplayExceptionDlg(SwingUtilities.getWindowAncestor(this), ex);
+ }
+ }
+ }
+ };
+ final InternalFrameListener adapter = new InternalFrameAdapter() {
+ @Override
+ public void internalFrameClosing(final InternalFrameEvent e) {
+ SearchWindow.this.pnlSearch.clearResources();
+ SearchWindow.this.pnlSearch.notifyParentStateChanged();
+ }
+
+ @Override
+ public void internalFrameIconified(final InternalFrameEvent e) {
+ SearchWindow.this.setTitle(SearchWindow.this.em.getTitre() + " <" + SearchWindow.this.rank + ">");
+ SearchWindow.this.pnlSearch.notifyParentStateChanged();
+ }
+
+ @Override
+ public void internalFrameDeiconified(final InternalFrameEvent e) {
+ SearchWindow.this.pnlSearch.redisplayTitle();
+ SearchWindow.this.pnlSearch.notifyParentStateChanged();
+ }
+
+ @Override
+ public void internalFrameActivated(final InternalFrameEvent e) {
+ SearchWindow.this.moveToFront();
+ SearchWindow.this.pnlSearch.notifyParentStateChanged();
+ }
+ };
+ this.addInternalFrameListener(adapter);
+ this.setContentPane(this.pnlSearch);
+ this.setGlassPane(new InfiniteGlassPane());
+ this.setIconifiable(true);
+ final KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
+ this.getRootPane().registerKeyboardAction(this.pnlSearch.getActionSearch(), "CANCEL", ks, JComponent.WHEN_IN_FOCUSED_WINDOW);
+ }
+
+ /**
+ * Permet de supprimer tous les critères
+ */
+ public void clearAll() {
+ this.pnlSearch.clearAll();
+ }
+
+ /**
+ * Permet d'ajouter un critère
+ *
+ * @return
+ */
+ public CriteriaViewer addLine() {
+ return this.pnlSearch.addLine();
+ }
+
+ /**
+ * Permet de lancer la recherche
+ */
+ public void search() {
+ this.pnlSearch.search();
+ }
+
+ public boolean canExport() {
+ return this.pnlSearch.canExport();
+ }
+
+ @Override
+ public void setVisible(final boolean visible) {
+ if (!visible && this.em != null) {
+ final Iterator<PropertyChangeListener> it = this.em.getPropertyListeners();
+ if (it != null) {
+ while (it.hasNext()) {
+ it.next();
+ it.remove();
+ }
+ }
+ }
+ super.setVisible(visible);
+ }
+
+ public void setCollectivite(final Pair collectivite) {
+ this.pnlSearch.setCollectivite(collectivite);
+ }
+
+ public void setBudget(final Pair budget) {
+ this.pnlSearch.setBudget(budget);
+ }
+
+ public boolean isEtatExportable() {
+ return this.em.getParent().isExportable();
+ }
+
+ public XemeliosUser getUser() {
+ return this.user;
+ }
}
package fr.gouv.finances.cp.xemelios.ui;
/**
- * an interface to receive notifications from various components
+ * an interface to receive notifications from various components
+ *
* @author chm
- *
+ *
*/
public interface UpdatableToolbar {
public void updateToolbarButtons();
- public void setBaseUrl(String url);
+
+ public void setBaseUrl(String url);
}
*/
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.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+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.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.utils.FileUtils;
+
/**
- *
+ *
* @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;
- }
-
- }
+ 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
+ this.applicationConfiguration = new PropertiesExpansion(System.getProperties());
+ this.config = Loader.getDocumentsInfos(this.applicationConfiguration.getProperty(Constants.SYS_PROP_DOC_DEF_DIR));
+ }
+
+ public ViewXemeliosDocument() throws Exception {
+ this.init();
+ final JFileChooser jfc = new JFileChooser(System.getProperty("user.home"));
+ jfc.addChoosableFileFilter(new FileFilter() {
+ @Override
+ public boolean accept(final File f) {
+ return f.getName().toLowerCase().endsWith(".xml");
+ }
+
+ @Override
+ public String getDescription() {
+ return "Fichiers XML";
+ }
+ });
+ jfc.addChoosableFileFilter(new FileFilter() {
+ @Override
+ public boolean accept(final File f) {
+ return true;
+ }
+
+ @Override
+ public String getDescription() {
+ return "Tous les fichiers";
+ }
+ });
+ jfc.setMultiSelectionEnabled(false);
+ if (jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
+ final File f = jfc.getSelectedFile();
+ // on est en mode super-dégradé, par de configuration d'execution
+ final AskDocumentType adt = new AskDocumentType(null, f.getName(), this.config, new PropertiesExpansion());
+ adt.setVisible(true);
+ final DocumentModel dm = adt.getDocumentType();
+ this.openFile(f.getAbsolutePath(), dm.getId());
+ }
+ }
+
+ public ViewXemeliosDocument(final String inFileName) throws Exception {
+ this.init();
+ final AskDocumentType adt = new AskDocumentType(null, inFileName, this.config, new PropertiesExpansion());
+ adt.setVisible(true);
+ final DocumentModel dm = adt.getDocumentType();
+ this.openFile(inFileName, dm.getId());
+ }
+
+ public ViewXemeliosDocument(final String inFileName, final String docId) throws Exception {
+ this.init();
+ this.openFile(inFileName, docId);
+ }
+
+ protected void openFile(final String inFileName, final String docId) throws Exception {
+ final DocumentModel docConfig = this.config.getDocumentById(docId);
+ if (docConfig == null) {
+ JOptionPane.showMessageDialog(null, docId + ": configuration non trouvée.", "Erreur", JOptionPane.ERROR_MESSAGE);
+ return;
+ }
+ final Hashtable<String, File> documents = new Hashtable<String, File>();
+ final StringBuffer uri = new StringBuffer();
+ final File fileToRead = new File(inFileName);
+ File fichierEnrichi = null;
+
+ if (docConfig.getGlobalImportXsltFile() != null) {
+ fichierEnrichi = new File(FileUtils.getTempDir(), "_" + fileToRead.getName() + "_");
+ final TransformerFactory tFactory = FactoryProvider.getTransformerFactory();
+ final Transformer tr = tFactory.newTransformer(new StreamSource(new File(docConfig.getBaseDirectory(), docConfig.getGlobalImportXsltFile())));
+ final 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());
+ final EditorHtmlViewer ehv = new EditorHtmlViewer(documents, this.config, uri.toString(), new LocalUser(), this.applicationConfiguration);
+ ehv.setLocationRelativeTo(null);
+ ehv.setVisible(true);
+ }
+
+ public static void main(final 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 (final 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 this.getId();
+ }
+
+ @Override
+ public boolean hasRole(final String arg0) {
+ return true;
+ }
+
+ @Override
+ public boolean hasDocument(final String arg0) {
+ return true;
+ }
+
+ @Override
+ public boolean hasCollectivite(final String arg0, final DocumentModel dm) {
+ return true;
+ }
+
+ }
}
/**
* 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;
+ 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();
- }
+ public WindowMenu(final JDesktopPane desk) {
+ super();
+ this.desk = desk;
+ this.initialize();
+ }
+
+ /**
+ * @param s
+ */
+ public WindowMenu(final String s, final JDesktopPane desk) {
+ super(s);
+ this.desk = desk;
+ this.initialize();
+ }
+
+ /**
+ * @param a
+ */
+ public WindowMenu(final Action a, final JDesktopPane desk) {
+ super(a);
+ this.desk = desk;
+ this.initialize();
+ }
+
+ /**
+ * @param s
+ * @param b
+ */
+ public WindowMenu(final String s, final boolean b, final JDesktopPane desk) {
+ super(s, b);
+ this.desk = desk;
+ this.initialize();
+ }
+
+ private void initialize() {
+ this.cstMenus = new JMenuItem[3];
+ this.cstMenus[0] = new JMenuItem("Cascade");
+ this.cstMenus[0].addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ cascade(WindowMenu.this.desk);
+ }
+ });
+ this.cstMenus[1] = new JMenuItem("Mosaïque");
+ this.cstMenus[1].addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ tile(WindowMenu.this.desk);
+ }
+ });
+ this.cstMenus[2] = new JMenuItem("Tout réduire");
+ this.cstMenus[2].addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ // DesktopManager dm = desk.getDesktopManager();
+ for (final JInternalFrame frame : WindowMenu.this.desk.getAllFrames()) {
+ try {
+ frame.setIcon(true);
+ } catch (final Throwable t) {
+ }
+ }
+ }
+ });
+ }
+
+ @Override
+ public void menuSelectionChanged(final boolean isIncluded) {
+ if (isIncluded) {
+ this.showWindowMenu();
+ }
+ super.menuSelectionChanged(isIncluded);
+ }
+
+ private void showWindowMenu() {
+ if (this.desk == null) {
+ logger.error("desk is null !");
+ return;
+ }
+ final JInternalFrame[] frames = this.desk.getAllFrames();
+ this.removeAll();
+ this.reAddMenus(frames);
+ for (final JInternalFrame frame : frames) {
+ final JMenuItem item = new JMenuItem(new ToFrontAction(frame));
+ if (this.desk.getSelectedFrame() == frame) {
+ item.setIcon(flagIcon);
+ }
+ this.add(item);
+ }
+ }
+
+ private void reAddMenus(final JInternalFrame[] frames) {
+ for (final JMenuItem it : this.cstMenus) {
+ this.add(it);
+ }
+ if (frames != null && frames.length > 0) {
+ this.addSeparator();
+ }
+ }
+
+ public static void cascade(final JDesktopPane desktopPane, final int layer) {
+ final JInternalFrame[] frames = desktopPane.getAllFramesInLayer(layer);
+ if (frames.length == 0) {
+ return;
+ }
+
+ cascade(frames, desktopPane.getBounds(), 24);
+ }
+
+ public static void cascade(final JDesktopPane desktopPane) {
+ final JInternalFrame[] frames = desktopPane.getAllFrames();
+ if (frames.length == 0) {
+ return;
+ }
+
+ cascade(frames, desktopPane.getBounds(), 24);
+ }
+
+ private static void cascade(final JInternalFrame[] frames, final Rectangle dBounds, final int separation) {
+ final int margin = frames.length * separation + separation;
+ final int width = dBounds.width - margin;
+ final 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 (final Throwable t) {
+ }
+ frames[i].toFront();
+ if (i == 0) {
+ frames[i].getDesktopPane().getDesktopManager().activateFrame(frames[i]);
+ try {
+ frames[i].setSelected(true);
+ } catch (final Throwable t) {
+ }
+ }
+ }
+ }
+
+ public static void tile(final JDesktopPane desktopPane, final int layer) {
+ final JInternalFrame[] frames = desktopPane.getAllFramesInLayer(layer);
+ if (frames.length == 0) {
+ return;
+ }
+
+ tile(frames, desktopPane.getBounds());
+ }
+
+ public static void tile(final JDesktopPane desktopPane) {
+ final JInternalFrame[] frames = desktopPane.getAllFrames();
+ if (frames.length == 0) {
+ return;
+ }
+
+ tile(frames, desktopPane.getBounds());
+ }
+
+ private static void tile(final JInternalFrame[] frames, final Rectangle dBounds) {
+ final int cols = (int) Math.sqrt(frames.length);
+ int rows = (int) (Math.ceil(((double) frames.length) / cols));
+ final 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 (final 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 (final Throwable t) {
+ }
+ }
+ }
+ }
+
+ public class ToFrontAction extends AbstractAction {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+ private JInternalFrame frame = null;
- 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 ToFrontAction(final JInternalFrame frame) {
+ super(frame.getTitle());
+ this.frame = frame;
+ }
- 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) {}
- }
- }
- }
- }
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ if (!this.frame.isSelected()) {
+ this.frame.getDesktopPane().getDesktopManager().activateFrame(this.frame);
+ try {
+ this.frame.setIcon(false);
+ this.frame.setSelected(true);
+ } catch (final Throwable t) {
+ }
+ } else {
+ if (this.frame.isIcon()) {
+ this.frame.getDesktopPane().getDesktopManager().activateFrame(this.frame);
+ try {
+ this.frame.setIcon(false);
+ this.frame.setSelected(true);
+ } catch (final Throwable t) {
+ }
+ } else {
+ try {
+ this.frame.setIcon(true);
+ } catch (final Throwable t) {
+ }
+ }
+ }
+ }
+ }
}
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.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 fr.gouv.finances.dgfip.xemelios.utils.XemeliosUtils;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;
+
import org.apache.log4j.Logger;
-import java.lang.reflect.Method;
-import java.lang.reflect.Constructor;
+
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+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 fr.gouv.finances.dgfip.xemelios.utils.XemeliosUtils;
/**
- *
- * @author chm
+ *
+ * @author chm
*/
public class DlgSystemConfiguration extends javax.swing.JDialog {
- private static final Logger logger = Logger.getLogger(DlgSystemConfiguration.class);
- 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);
- 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);
- }
- PnlImport imp = new PnlImport(MainWindow.getInstance().getEnvProperties());
- tabs.add("Import d'archives", imp);
- panels.add(imp);
- Connection con = null;
- try {
- con = PoolManager.getInstance().getConnection();
- if("true".equals(MainWindow.getInstance().getEnvProperties().getProperty(Constants.SYS_PROP_FORCE_AUTH_CFG)) || XemeliosUtils.isLocalComputerServer(con)) {
- String className = DataLayerManager.getImplementation().getParameterValue("authEngineClassName");
- try {
- final Class clazz = Class.forName("fr.gouv.finances.dgfip.xemelios.auth.impl.std.db.ui.PnlConfigAuthentication");
- Constructor cc = clazz.getConstructor(String.class, PropertiesExpansion.class);
- final Object o = cc.newInstance(className, MainWindow.getInstance().getEnvProperties());
- ParamSaver pm = new ParamSaver() {
- @Override
- public void saveConfiguration() {
- try {
- Method meth = clazz.getMethod("saveData");
- Object retVal = meth.invoke(o);
- boolean ret = ((Boolean)retVal).booleanValue();
- if(!ret) {
- 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);
- }
- } catch(Exception ex) {
- logger.error("saveConfiguration", ex);
- }
- }
- };
- panels.add(pm);
- tabs.add("Authentification",(JComponent)o);
- } catch(Exception ex) {
- logger.error("Adding PnlConfigAuthentication");
- }
- }
- } 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
-
+ private static final Logger logger = Logger.getLogger(DlgSystemConfiguration.class);
+ private AbstractAction escapeAction;
+ ArrayList<ParamSaver> panels;
+
+ /** Creates new form DlgTestProxy */
+ public DlgSystemConfiguration(final java.awt.Frame parent, final boolean modal) {
+ super(parent, modal);
+ this.panels = new ArrayList<ParamSaver>();
+ this.initComponents();
+ final PnlProxy pnlProxy = new PnlProxy(MainWindow.getInstance().getEnvProperties());
+ this.tabs.addTab("Proxy", pnlProxy);
+ this.panels.add(pnlProxy);
+ final PnlUpdate pnlUpdate = new PnlUpdate(MainWindow.getInstance().getEnvProperties());
+ this.tabs.addTab("Mises à jour", pnlUpdate);
+ this.panels.add(pnlUpdate);
+ final PnlProfils pnlProfils = new PnlProfils(MainWindow.getInstance().getEnvProperties());
+ this.tabs.add("Abonnements", pnlProfils);
+ this.panels.add(pnlProfils);
+ if ("true".equals(MainWindow.getInstance().getEnvProperties().getProperty(Constants.SYS_PROP_PNL_SYSPROP))) {
+ final PnlSystemProperties pnlSysProps = new PnlSystemProperties(MainWindow.getInstance().getEnvProperties());
+ this.tabs.addTab("Propriétés Systèmes", pnlSysProps);
+ this.panels.add(pnlSysProps);
+ }
+ final PnlImport imp = new PnlImport(MainWindow.getInstance().getEnvProperties());
+ this.tabs.add("Import d'archives", imp);
+ this.panels.add(imp);
+ Connection con = null;
+ try {
+ con = PoolManager.getInstance().getConnection();
+ if ("true".equals(MainWindow.getInstance().getEnvProperties().getProperty(Constants.SYS_PROP_FORCE_AUTH_CFG)) || XemeliosUtils.isLocalComputerServer(con)) {
+ final String className = DataLayerManager.getImplementation().getParameterValue("authEngineClassName");
+ try {
+ final Class clazz = Class.forName("fr.gouv.finances.dgfip.xemelios.auth.impl.std.db.ui.PnlConfigAuthentication");
+ final Constructor cc = clazz.getConstructor(String.class, PropertiesExpansion.class);
+ final Object o = cc.newInstance(className, MainWindow.getInstance().getEnvProperties());
+ final ParamSaver pm = new ParamSaver() {
+ @Override
+ public void saveConfiguration() {
+ try {
+ final Method meth = clazz.getMethod("saveData");
+ final Object retVal = meth.invoke(o);
+ final boolean ret = ((Boolean) retVal).booleanValue();
+ if (!ret) {
+ 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);
+ }
+ } catch (final Exception ex) {
+ logger.error("saveConfiguration", ex);
+ }
+ }
+ };
+ this.panels.add(pm);
+ this.tabs.add("Authentification", (JComponent) o);
+ } catch (final Exception ex) {
+ logger.error("Adding PnlConfigAuthentication");
+ }
+ }
+ } catch (final DataConfigurationException ex) {
+ // on peut ignorer
+ } finally {
+ if (con != null) {
+ PoolManager.getInstance().releaseConnection(con);
+ }
+ }
+ this.setLocationRelativeTo(this.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() {
+
+ this.pbClose = new javax.swing.JButton();
+ this.pbSave = new javax.swing.JButton();
+ this.tabs = new javax.swing.JTabbedPane();
+
+ this.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+ this.setTitle("Paramétrage de XéMéLios");
+
+ this.pbClose.setText("Fermer");
+ this.pbClose.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgSystemConfiguration.this.pbCloseActionPerformed(evt);
+ }
+ });
+
+ this.pbSave.setText("Enregistrer");
+ this.pbSave.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgSystemConfiguration.this.pbSaveActionPerformed(evt);
+ }
+ });
+
+ this.tabs.setTabLayoutPolicy(javax.swing.JTabbedPane.SCROLL_TAB_LAYOUT);
+
+ final org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this.getContentPane());
+ this.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, this.tabs, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 567, Short.MAX_VALUE)
+ .add(layout.createSequentialGroup().add(this.pbSave).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.pbClose))).addContainerGap()));
+ layout.setVerticalGroup(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(
+ org.jdesktop.layout.GroupLayout.TRAILING,
+ layout.createSequentialGroup().addContainerGap().add(this.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(this.pbClose).add(this.pbSave)).addContainerGap()));
+
+ this.pack();
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void pbSaveActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbSaveActionPerformed
+ for (final ParamSaver ps : this.panels) {
+ ps.saveConfiguration();
+ }
+ }// GEN-LAST:event_pbSaveActionPerformed
+
+ private void pbCloseActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbCloseActionPerformed
+ this.setVisible(false);
+ }// GEN-LAST:event_pbCloseActionPerformed
+
+ @Override
+ protected JRootPane createRootPane() {
+ final KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
+ final JRootPane rp = new JRootPane();
+ this.escapeAction = new AbstractAction("Annuler") {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ DlgSystemConfiguration.this.pbCloseActionPerformed(evt);
+ }
+ };
+ rp.registerKeyboardAction(this.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
+
}
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();
+ /**
+ * Called by DlgTestProxy to notify each panel to save configuration
+ */
+ public void saveConfiguration();
}
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;
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+
/**
- *
- * @author chm
+ *
+ * @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; }
- }
+ private static Logger logger = Logger.getLogger(PnlExport.class);
+ private final 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(final PropertiesExpansion applicationConfiguration) {
+ this.applicationConfiguration = applicationConfiguration;
+ this.initComponents();
+ this.initializeData();
+ }
+
+ protected void initializeData() {
+ final String exporterClassName = this.applicationConfiguration.getProperty(Constants.SYS_PROP_XEMELIOS_EXPORTER_CLASS);
+ for (final ExporterConfig ec : exporters) {
+ if (ec.getClassName().equals(exporterClassName)) {
+ this.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() {
+
+ this.jLabel1 = new javax.swing.JLabel();
+ this.cbxExporter = new JComboBox(exporters);
+ this.jLabel2 = new javax.swing.JLabel();
+ this.jScrollPane1 = new javax.swing.JScrollPane();
+ this.dfDesc = new javax.swing.JTextArea();
+ this.jScrollPane2 = new javax.swing.JScrollPane();
+ this.jTextArea1 = new javax.swing.JTextArea(PANEL_DESCRIPTION);
+
+ this.jLabel1.setText("Méthode d'export Excel");
+
+ this.cbxExporter.addItemListener(new java.awt.event.ItemListener() {
+ @Override
+ public void itemStateChanged(final java.awt.event.ItemEvent evt) {
+ PnlExport.this.cbxExporterItemStateChanged(evt);
+ }
+ });
+
+ this.jLabel2.setText("Description");
+
+ this.dfDesc.setColumns(20);
+ this.dfDesc.setEditable(false);
+ this.dfDesc.setRows(5);
+ this.jScrollPane1.setViewportView(this.dfDesc);
+
+ this.jScrollPane2.setBorder(null);
+
+ this.jTextArea1.setBackground(javax.swing.UIManager.getDefaults().getColor("Panel.background"));
+ this.jTextArea1.setColumns(20);
+ this.jTextArea1.setRows(5);
+ this.jTextArea1.setBorder(null);
+ this.jScrollPane2.setViewportView(this.jTextArea1);
+
+ final 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(this.jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
+ .add(layout.createSequentialGroup().add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(this.jLabel1).add(this.jLabel2)).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(this.jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 238, Short.MAX_VALUE).add(this.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(this.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(this.jLabel1).add(this.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(this.jLabel2).add(this.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(final java.awt.event.ItemEvent evt) {// GEN-FIRST:event_cbxExporterItemStateChanged
+ if (this.cbxExporter.getSelectedItem() != null) {
+ this.dfDesc.setText(((ExporterConfig) this.cbxExporter.getSelectedItem()).getDescription());
+ }
+ }// GEN-LAST:event_cbxExporterItemStateChanged
+
+ @Override
+ public void saveConfiguration() {
+ // PropertiesExpansion props = new PropertiesExpansion(System.getProperties());
+ final Properties xemProps = new Properties();
+
+ final File xemPropsFile = new File(this.applicationConfiguration.replace("${xemelios.prg}/root/xemelios.properties"));
+ if (!xemPropsFile.exists()) {
+ final String className = ((ExporterConfig) this.cbxExporter.getSelectedItem()).getClassName();
+ System.setProperty(Constants.SYS_PROP_XEMELIOS_EXPORTER_CLASS, className);
+ } else {
+ try {
+ xemProps.load(new FileInputStream(xemPropsFile));
+ final String className = ((ExporterConfig) this.cbxExporter.getSelectedItem()).getClassName();
+ xemProps.put(Constants.SYS_PROP_XEMELIOS_EXPORTER_CLASS, className);
+ this.applicationConfiguration.setProperty(Constants.SYS_PROP_XEMELIOS_EXPORTER_CLASS, className);
+ final FileOutputStream fos = new FileOutputStream(xemPropsFile);
+ xemProps.store(fos, "");
+ fos.close();
+ } catch (final 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 final String className;
+ private final String title;
+ private final String description;
+
+ public ExporterConfig(final String className, final String title, final String description) {
+ super();
+ this.className = className;
+ this.title = title;
+ this.description = description;
+ }
+
+ @Override
+ public String toString() {
+ return this.title;
+ }
+
+ public String getClassName() {
+ return this.className;
+ }
+
+ public String getTitle() {
+ return this.title;
+ }
+
+ public String getDescription() {
+ return this.description;
+ }
+ }
}
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 fr.gouv.finances.dgfip.xemelios.importers.archives.ArchiveImporter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
+
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import fr.gouv.finances.dgfip.xemelios.importers.archives.ArchiveImporter;
+
/**
- *
+ *
* @author cmarchand
*/
public class PnlImport extends javax.swing.JPanel implements ParamSaver {
- private final PropertiesExpansion applicationConfiguration;
- private static final transient String PARTIEL_DESCRIPTION = "<html><p>Lors de l'import d'une archive, demande à l'utilisateur quelles données il faut importer.</p></html>";
- private static final transient String TOTAL_DESCRIPTION = "<html><p>Lors de l'import d'une archive, importe toutes les données sans questionner l'utilisateur. C'est le comportement par défaut.</p></html>";
- ComboBoxModel cbxModel;
-
- /** Creates new form PnlImport */
- public PnlImport(PropertiesExpansion applicationConfiguration) {
- this.applicationConfiguration = applicationConfiguration;
- Pair p1 = new Pair(Constants.IMPORT_ARCHIVE_TOTAL,"Import total (sans demande)") ;
- Pair p2 = new Pair(Constants.IMPORT_ARCHIVE_PARTIEL, "Import partiel (avec demande)");
- cbxModel = new DefaultComboBoxModel(new Pair[]{p1,p2});
- String value = ArchiveImporter.getImportMode(this.applicationConfiguration);
- Pair current = null;
- if(Constants.IMPORT_ARCHIVE_PARTIEL.equals(applicationConfiguration.getProperty(Constants.SYS_PROP_IMPORT_ARCHIVE_MODE)))
- current = p2;
- else
- current = p1;
- cbxModel.setSelectedItem(current);
- initComponents();
- cbxModeImportActionPerformed(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();
- cbxModeImport = new javax.swing.JComboBox();
- lblDesc = new javax.swing.JLabel();
-
- jLabel1.setText("Mode d'import");
-
- cbxModeImport.setModel(cbxModel);
- cbxModeImport.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- cbxModeImportActionPerformed(evt);
- }
- });
-
- lblDesc.setText("<description>");
-
- 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)
- .addGroup(layout.createSequentialGroup()
- .addComponent(jLabel1)
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
- .addComponent(cbxModeImport, 0, 272, Short.MAX_VALUE))
- .addComponent(lblDesc))
- .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(cbxModeImport, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
- .addComponent(lblDesc)
- .addContainerGap(234, Short.MAX_VALUE))
- );
- }// </editor-fold>//GEN-END:initComponents
-
- private void cbxModeImportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbxModeImportActionPerformed
-// if(evt!=null) JOptionPane.showMessageDialog(this, cbxModel.getSelectedItem().toString());
- if(Constants.IMPORT_ARCHIVE_PARTIEL.equals(getKey(cbxModel.getSelectedItem()))) {
- lblDesc.setText(PARTIEL_DESCRIPTION);
- } else {
- lblDesc.setText(TOTAL_DESCRIPTION);
- }
- }//GEN-LAST:event_cbxModeImportActionPerformed
-
- private String getKey(Object obj) {
- return ((Pair)(obj)).key;
- }
-
- // Variables declaration - do not modify//GEN-BEGIN:variables
- private javax.swing.JComboBox cbxModeImport;
- private javax.swing.JLabel jLabel1;
- private javax.swing.JLabel lblDesc;
- // End of variables declaration//GEN-END:variables
-
- @Override
- public void saveConfiguration() {
- applicationConfiguration.setProperty(Constants.SYS_PROP_IMPORT_ARCHIVE_MODE, getKey(cbxModel.getSelectedItem()));
- File xemPropsFile = new File(applicationConfiguration.replace("${xemelios.prg}/root/xemelios.properties"));
- if(xemPropsFile.exists()) {
- try {
- Properties xemProps = new Properties();
- xemProps.load(new FileInputStream(xemPropsFile));
- xemProps.setProperty(Constants.SYS_PROP_IMPORT_ARCHIVE_MODE, getKey(cbxModel.getSelectedItem()));
- FileOutputStream fos = new FileOutputStream(xemPropsFile);
- xemProps.store(fos,"");
- fos.close();
- } catch(IOException ioEx) { }
- }
- }
+ private final PropertiesExpansion applicationConfiguration;
+ private static final transient String PARTIEL_DESCRIPTION = "<html><p>Lors de l'import d'une archive, demande à l'utilisateur quelles données il faut importer.</p></html>";
+ private static final transient String TOTAL_DESCRIPTION = "<html><p>Lors de l'import d'une archive, importe toutes les données sans questionner l'utilisateur. C'est le comportement par défaut.</p></html>";
+ ComboBoxModel cbxModel;
+
+ /** Creates new form PnlImport */
+ public PnlImport(final PropertiesExpansion applicationConfiguration) {
+ this.applicationConfiguration = applicationConfiguration;
+ final Pair p1 = new Pair(Constants.IMPORT_ARCHIVE_TOTAL, "Import total (sans demande)");
+ final Pair p2 = new Pair(Constants.IMPORT_ARCHIVE_PARTIEL, "Import partiel (avec demande)");
+ this.cbxModel = new DefaultComboBoxModel(new Pair[] { p1, p2 });
+ final String value = ArchiveImporter.getImportMode(this.applicationConfiguration);
+ Pair current = null;
+ if (Constants.IMPORT_ARCHIVE_PARTIEL.equals(applicationConfiguration.getProperty(Constants.SYS_PROP_IMPORT_ARCHIVE_MODE))) {
+ current = p2;
+ } else {
+ current = p1;
+ }
+ this.cbxModel.setSelectedItem(current);
+ this.initComponents();
+ this.cbxModeImportActionPerformed(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() {
+
+ this.jLabel1 = new javax.swing.JLabel();
+ this.cbxModeImport = new javax.swing.JComboBox();
+ this.lblDesc = new javax.swing.JLabel();
+
+ this.jLabel1.setText("Mode d'import");
+
+ this.cbxModeImport.setModel(this.cbxModel);
+ this.cbxModeImport.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PnlImport.this.cbxModeImportActionPerformed(evt);
+ }
+ });
+
+ this.lblDesc.setText("<description>");
+
+ final 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).addGroup(layout.createSequentialGroup().addComponent(this.jLabel1).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(this.cbxModeImport, 0, 272, Short.MAX_VALUE))
+ .addComponent(this.lblDesc)).addContainerGap()));
+ layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
+ layout.createSequentialGroup().addContainerGap()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(this.jLabel1).addComponent(this.cbxModeImport, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED).addComponent(this.lblDesc).addContainerGap(234, Short.MAX_VALUE)));
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void cbxModeImportActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_cbxModeImportActionPerformed
+ // if(evt!=null) JOptionPane.showMessageDialog(this, cbxModel.getSelectedItem().toString());
+ if (Constants.IMPORT_ARCHIVE_PARTIEL.equals(this.getKey(this.cbxModel.getSelectedItem()))) {
+ this.lblDesc.setText(PARTIEL_DESCRIPTION);
+ } else {
+ this.lblDesc.setText(TOTAL_DESCRIPTION);
+ }
+ }// GEN-LAST:event_cbxModeImportActionPerformed
+
+ private String getKey(final Object obj) {
+ return ((Pair) (obj)).key;
+ }
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JComboBox cbxModeImport;
+ private javax.swing.JLabel jLabel1;
+ private javax.swing.JLabel lblDesc;
+
+ // End of variables declaration//GEN-END:variables
+
+ @Override
+ public void saveConfiguration() {
+ this.applicationConfiguration.setProperty(Constants.SYS_PROP_IMPORT_ARCHIVE_MODE, this.getKey(this.cbxModel.getSelectedItem()));
+ final File xemPropsFile = new File(this.applicationConfiguration.replace("${xemelios.prg}/root/xemelios.properties"));
+ if (xemPropsFile.exists()) {
+ try {
+ final Properties xemProps = new Properties();
+ xemProps.load(new FileInputStream(xemPropsFile));
+ xemProps.setProperty(Constants.SYS_PROP_IMPORT_ARCHIVE_MODE, this.getKey(this.cbxModel.getSelectedItem()));
+ final FileOutputStream fos = new FileOutputStream(xemPropsFile);
+ xemProps.store(fos, "");
+ fos.close();
+ } catch (final IOException ioEx) {
+ }
+ }
+ }
}
*/
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.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.nio.charset.Charset;
import java.util.ArrayList;
+
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
+
import org.apache.commons.httpclient.HttpClient;
import org.apache.log4j.Logger;
+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.ComponentModel;
+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.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;
+
/**
- *
+ *
* @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;
- /**
+ private static Logger logger = Logger.getLogger(PnlProfils.class);
+ private final PropertiesExpansion applicationProperties;
+ private final 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_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(aFlag) updateProfils();
- }
- private void updateProfils() {
- if (profilsLoaded) {
- return;
- }
-
- 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.setProfils(psm.getProfils());
- profilsLoaded = true;
- } catch (Exception ex) {
- logger.error(ex, ex);
- 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);
-
- 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);
- pTableModel.fireTableDataChanged();
- //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;
- }
- }
-
- 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";
- }
- }
-
- public void setProfils(ArrayList<ProfilModel> profils) {
- this.profils = profils;
- }
-
- @Override
- public void tableChanged(TableModelEvent e) {
- //throw new UnsupportedOperationException("Not supported yet.");
- }
-
- }
-
- 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);
- updateProfils();
- }//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;
- }
- }
+ public static final transient int COL_DESCRIPTION = 1;
+
+ /**
+ * Creates new form PnlProfils
+ *
+ * @param applicationProperties
+ */
+ public PnlProfils(final PropertiesExpansion applicationProperties) {
+ this.applicationProperties = applicationProperties;
+ this.psm = new ProfilsModel(ProfilsModel.QN);
+ this.pTableModel = new ProfilsTableModel(this.psm.getProfils());
+ this.profilsLoaded = false;
+
+ this.initComponents();
+ final DescCellRenderer renderer = new DescCellRenderer(this.pTableModel);
+ this.jxTableProfils.setDefaultRenderer(String.class, renderer);
+
+ this.jButtonEnregistrer.setVisible(false);
+
+ this.jxTableProfils.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
+ this.jxTableProfils.setShowGrid(true, false);
+ this.jxTableProfils.setSortable(false);
+
+ TableColumn col;
+ col = this.jxTableProfils.getColumnModel().getColumn(COL_ABONNEMENT);
+ col.setPreferredWidth(80);
+ col.setMinWidth(60);
+
+ col = this.jxTableProfils.getColumnModel().getColumn(COL_DESCRIPTION);
+ col.setPreferredWidth(250);
+
+ this.jButtonDetail.setEnabled(false);
+
+ this.jxTableProfils.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
+
+ @Override
+ public void valueChanged(final ListSelectionEvent e) {
+ final int row = PnlProfils.this.jxTableProfils.getSelectedRow();
+ if (row >= 0 && PnlProfils.this.psm.getProfils().get(row).getComponents().size() > 0) {
+ PnlProfils.this.jButtonDetail.setEnabled(true);
+ } else {
+ PnlProfils.this.jButtonDetail.setEnabled(false);
+ }
+ }
+ });
+ }
+
+ @Override
+ public void setVisible(final boolean aFlag) {
+ super.setVisible(aFlag);
+ if (aFlag) {
+ this.updateProfils();
+ }
+ }
+
+ private void updateProfils() {
+ if (this.profilsLoaded) {
+ return;
+ }
+
+ try {
+ final String urlLocation = this.applicationProperties.getProperty(Constants.SYS_PROP_MAJ_PROFILS_URL);
+ final HttpClient client = NetAccess.getHttpClient(MainWindow.getInstance().getEnvProperties());
+
+ this.psm = ProfilsModel.loadModel(urlLocation, client);
+ logger.debug("Profils chargés : " + this.psm.toString());
+ this.pTableModel.setProfils(this.psm.getProfils());
+ this.profilsLoaded = true;
+ } catch (final Exception ex) {
+ logger.error(ex, ex);
+ 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);
+
+ this.jButtonComposants.setEnabled(false);
+ this.jButtonDetail.setEnabled(false);
+ this.jButtonEnregistrer.setEnabled(false);
+
+ return; // inutile de charger les abonnements courant de l'utilisateur
+ }
+
+ try {
+ this.im = InstalledModel.readFromFile(this.applicationProperties.getProperty(Constants.SYS_PROP_INSTALLED_FILENAME));
+ this.im.setFileLocation(this.applicationProperties.getProperty(Constants.SYS_PROP_INSTALLED_FILENAME));
+ if (this.im != null) {
+ logger.debug("Installed:nbre Component=" + this.im.getComponents().size());
+ for (final ComponentModel cm : this.im.getComponents()) {
+ logger.debug("c uri=" + cm.getUri() + " / desc=" + cm.getDescription());
+ }
+ logger.debug("Installed:nbre Profil=" + this.im.getProfils().size());
+ for (final ProfilModel pm : this.im.getProfils()) {
+ logger.debug("p id=" + pm.getId() + " / desc=" + pm.getDescription());
+ }
+
+ // inscription des profils requis, enregistrement.
+ boolean bTouched = false;
+ for (final ProfilModel pm : this.psm.getProfils()) {
+ if (pm.isRequired()) {
+ if (this.im.getProfilIdx(pm.getId()) == InstalledModel.NOT_FOUND) {
+ final ProfilModel npm = new ProfilModel(pm.getId(), pm.getDescription());
+ this.im.getProfils().add(npm);
+ bTouched = true;
+ }
+ }
+ }
+ if (bTouched) {
+ this.im.setComponents(this.createComponentsList());
+ }
+ }
+ } catch (final 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
+ */
+ this.jButtonDetail.setEnabled(false);
+ this.pTableModel.fireTableDataChanged();
+ // jxTableProfils.setModel(pTableModel);
+ final DescCellRenderer renderer = new DescCellRenderer(this.pTableModel);
+ this.jxTableProfils.setDefaultRenderer(String.class, renderer);
+ this.pTableModel.fireTableDataChanged();
+ }
+
+ @Override
+ public void saveConfiguration() {
+ this.jButtonEnregistrerActionPerformed(null);
+ }
+
+ private class ProfilsTableModel extends AbstractTableModel implements TableModelListener {
+
+ ArrayList<ProfilModel> getProfils() {
+ return this.profils;
+ }
+
+ private ArrayList<ProfilModel> profils;
+
+ @Override
+ public void setValueAt(final Object aValue, final int rowIndex, final int columnIndex) {
+ // super.setValueAt(aValue, rowIndex, columnIndex);
+ // logger.debug("rowIndex=" + rowIndex + "/columnIndex=" + columnIndex + "/aValue=" + aValue.toString());
+ switch (columnIndex) {
+ case COL_ABONNEMENT:
+ final ProfilModel pm = this.profils.get(rowIndex);
+ final int idxFound = PnlProfils.this.im.getProfilIdx(pm.getId());
+ if (idxFound != InstalledModel.NOT_FOUND) { // profil trouvé
+ if (aValue.equals(false)) { // case doit être décochée
+ PnlProfils.this.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
+ final ProfilModel npm = new ProfilModel(pm.getId(), pm.getDescription());
+ PnlProfils.this.im.getProfils().add(npm); // on ajoute le profil à la liste des profils installés
+ }
+ }
+ for (final ProfilModel pml : PnlProfils.this.im.getProfils()) {
+ logger.debug("p id=" + pml.getId() + " / desc=" + pml.getDescription());
+ }
+ break;
+ default:
+ break;
+ }
+ }
+
+ public ProfilsTableModel(final ArrayList<ProfilModel> profils) {
+ this.profils = profils;
+ }
+
+ @Override
+ public int getRowCount() {
+ return this.profils.size();
+ }
+
+ @Override
+ public int getColumnCount() {
+ return 2;
+ }
+
+ @Override
+ public Object getValueAt(final int rowIndex, final int columnIndex) {
+ final ProfilModel pm = this.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 (PnlProfils.this.im == null) {
+ return false; // pas d'entrée profil dans installed.xml
+ } else {
+ for (final ProfilModel ipm : PnlProfils.this.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(final int rowIndex, final int columnIndex) {
+ switch (columnIndex) {
+ case COL_ABONNEMENT:
+ // profil obligatoire, donc la selection n'est pas modifiable
+ if (this.profils.get(rowIndex).isRequired()) {
+ return false;
+ } else {
+ return true;
+ }
+ case COL_DESCRIPTION:
+ return false;
+ default:
+ return false;
+ }
+ }
+
+ @Override
+ public Class<?> getColumnClass(final 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(final int column) {
+ switch (column) {
+ case COL_ABONNEMENT:
+ return "abonnement";
+ case COL_DESCRIPTION:
+ return "description";
+ default:
+ return "unknow column";
+ }
+ }
+
+ public void setProfils(final ArrayList<ProfilModel> profils) {
+ this.profils = profils;
+ }
+
+ @Override
+ public void tableChanged(final TableModelEvent e) {
+ // throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ }
+
+ private ArrayList<ComponentModel> createComponentsList() {
+ // Création de la liste des composants actifs selon les composants "editable" et les profils
+ final ArrayList<ComponentModel> nic = new ArrayList<ComponentModel>();
+ // Trt des composants "editable"
+ for (final ComponentModel ic : this.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 (final ProfilModel ip : this.im.getProfils()) {
+ for (final ProfilModel p : this.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 (final 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
+ final int idx = this.im.getComponentIdx(c.getUri());
+ if (idx != InstalledModel.NOT_FOUND) {
+ c = this.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() {
+
+ this.jLabel1 = new javax.swing.JLabel();
+ this.jButtonComposants = new javax.swing.JButton();
+ this.jButtonEnregistrer = new javax.swing.JButton();
+ this.jScrollPane1 = new javax.swing.JScrollPane();
+ this.jxTableProfils = new org.jdesktop.swingx.JXTable();
+ this.jButtonDetail = new javax.swing.JButton();
+
+ this.jLabel1.setFont(this.jLabel1.getFont().deriveFont(this.jLabel1.getFont().getStyle() | java.awt.Font.BOLD));
+ this.jLabel1.setText("Liste des profils");
+
+ this.jButtonComposants.setText("Avancé");
+ this.jButtonComposants.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PnlProfils.this.jButtonComposantsActionPerformed(evt);
+ }
+ });
+
+ this.jButtonEnregistrer.setText("Enregistrer");
+ this.jButtonEnregistrer.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PnlProfils.this.jButtonEnregistrerActionPerformed(evt);
+ }
+ });
+
+ this.jxTableProfils.setModel(this.pTableModel);
+ this.jScrollPane1.setViewportView(this.jxTableProfils);
+
+ this.jButtonDetail.setText("Détails");
+ this.jButtonDetail.setActionCommand("Détail");
+ this.jButtonDetail.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PnlProfils.this.jButtonDetailActionPerformed(evt);
+ }
+ });
+
+ final 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(this.jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 452, Short.MAX_VALUE)
+ .addComponent(this.jLabel1, javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(javax.swing.GroupLayout.Alignment.LEADING,
+ layout.createSequentialGroup().addComponent(this.jButtonComposants).addGap(18, 18, 18).addComponent(this.jButtonDetail).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 215, Short.MAX_VALUE).addComponent(this.jButtonEnregistrer)))
+ .addContainerGap()));
+ layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
+ layout.createSequentialGroup().addContainerGap().addComponent(this.jLabel1).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(this.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(this.jButtonComposants).addComponent(this.jButtonEnregistrer).addComponent(this.jButtonDetail)).addGap(26, 26, 26)));
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void jButtonComposantsActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButtonComposantsActionPerformed
+ // TODO add your handling code here:
+ final DlgComposants dlgComposants = new DlgComposants(MainWindow.getInstance(), true);
+ dlgComposants.setVisible(true);
+ this.updateProfils();
+ }// GEN-LAST:event_jButtonComposantsActionPerformed
+
+ private void jButtonEnregistrerActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButtonEnregistrerActionPerformed
+ // TODO add your handling code here:
+ if (!this.profilsLoaded) {
+ return;
+ }
+ this.im.setComponents(this.createComponentsList());
+ for (final ProfilModel pm : this.im.getProfils()) {
+ pm.setDontWriteOptionalAttributes(true);
+ }
+ try {
+ final Charset cs = Charset.forName("ISO-8859-1");
+ final File fo = new File(this.applicationProperties.getProperty(Constants.SYS_PROP_INSTALLED_FILENAME));
+ this.im.outputToFile(fo, cs);
+ } catch (final IOException ex) {
+ logger.error(ex);
+ }
+ this.setVisible(false);
+
+ }// GEN-LAST:event_jButtonEnregistrerActionPerformed
+
+ private void jButtonDetailActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButtonDetailActionPerformed
+ // TODO add your handling code here:
+
+ logger.debug("Selected Row=" + this.jxTableProfils.getSelectedRow());
+ final ProfilModel pm = this.psm.getProfils().get(this.jxTableProfils.getSelectedRow());
+ logger.debug("profil=" + pm.getDescription() + "/nbComposants=" + pm.getComponents().size());
+
+ final DlgProfilDetail nd = new DlgProfilDetail(MainWindow.getInstance(), this.psm.getProfils().get(this.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 final ProfilsTableModel model;
+
+ public DescCellRenderer(final ProfilsTableModel model) {
+ super();
+ this.model = model;
+ }
+
+ @Override
+ public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) {
+ final Component parentComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
+ final Component renderer = parentComponent;
+ if (column == 1) {
+ final ProfilModel pm = this.model.getProfils().get(row);
+ if (pm.isRequired()) {
+ final Font oldFont = renderer.getFont();
+ final Font newFont = oldFont.deriveFont(Font.ITALIC | Font.BOLD); // oldFont.getStyle() |
+ renderer.setFont(newFont);
+ }
+
+ }
+ return renderer;
+ }
+ }
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
+import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
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 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
+ *
+ * @author chm
*/
public class PnlProxy extends javax.swing.JPanel implements ParamSaver {
- private static final String URL_TO_REACH = "http://xemelios.org/updatesV5/profils.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(applicationConfiguration.getProperty(Constants.SYS_PROP_MAJ_PROFILS_URL));
- } catch(MalformedURLException muEx) {
- try {
- url = new URL(URL_TO_REACH);
- } catch(Exception ex2) {
- 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.toExternalForm());
- 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
-
+ private static final String URL_TO_REACH = "http://xemelios.org/updatesV5/profils.xml";
+ private static final Logger logger = Logger.getLogger(PnlProxy.class);
+ private final PropertiesExpansion applicationConfiguration;
+
+ /** Creates new form PnlProxy */
+ public PnlProxy(final PropertiesExpansion applicationConfiguration) {
+ this.applicationConfiguration = applicationConfiguration;
+ this.initComponents();
+ this.initValues();
+ }
+
+ private void initValues() {
+ final String proxyServer = this.applicationConfiguration.getProperty(Constants.SYS_PROP_PROXY_SERVER);
+ final String proxyPort = this.applicationConfiguration.getProperty(Constants.SYS_PROP_PROXY_PORT);
+ final String proxyUser = this.applicationConfiguration.getProperty(Constants.SYS_PROP_PROXY_USER);
+ final String proxyPassword = this.applicationConfiguration.getProperty(Constants.SYS_PROP_PROXY_PASSWD);
+ final String proxyDomain = this.applicationConfiguration.getProperty(Constants.SYS_PROP_PROXY_DOMAIN);
+ this.setValues(proxyServer, proxyPort, proxyUser, proxyPassword, proxyDomain);
+ }
+
+ private void setValues(final String server, final String port, final String user, final String password, final String proxyDomain) {
+ if (server != null) {
+ this.dfProxyServer.setText(server);
+ this.chkUseProxy.setSelected(true);
+ } else {
+ this.dfProxyServer.setText("");
+ this.chkUseProxy.setSelected(false);
+ }
+ this.enableProxyControls(this.chkUseProxy.isSelected());
+ this.dfProxyPort.setText(port != null ? port : "");
+ if (user != null) {
+ this.dfProxyUser.setText(user);
+ this.chkAuthenticationRequired.setSelected(true);
+ } else {
+ this.dfProxyUser.setText("");
+ this.chkAuthenticationRequired.setSelected(false);
+ }
+ this.enableAuthenticationControls(this.chkAuthenticationRequired.isSelected());
+ this.dfProxyPassword.setText(password != null ? Scramble.unScramblePassword(password) : "");
+ this.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 (this.dfProxyServer.getText() != null && this.dfProxyServer.getText().length() > 0) {
+ proxyHost = this.dfProxyServer.getText();
+ }
+ if (this.dfProxyPort.getText() != null && this.dfProxyPort.getText().length() > 0) {
+ proxyPort = this.dfProxyPort.getText();
+ }
+ if (this.dfProxyUser.getText() != null && this.dfProxyUser.getText().length() > 0) {
+ proxyUser = this.dfProxyUser.getText();
+ }
+ if (this.dfProxyPassword.getPassword().length > 0) {
+ proxyPasswd = new String(this.dfProxyPassword.getPassword());
+ }
+ if (proxyPort != null) {
+ try {
+ intProxyPort = Integer.parseInt(proxyPort);
+ } catch (final NumberFormatException nfEx) {
+ JOptionPane.showMessageDialog(this, proxyPort + " n'est pas un numéro de port valide.", "ERREUR", JOptionPane.ERROR_MESSAGE);
+ return;
+ }
+ }
+ if (this.dfDomainName.getText() != null && this.dfDomainName.getText().length() > 0) {
+ domainName = this.dfDomainName.getText();
+ }
+ URL url = null;
+ try {
+ url = new URL(this.applicationConfiguration.getProperty(Constants.SYS_PROP_MAJ_PROFILS_URL));
+ } catch (final MalformedURLException muEx) {
+ try {
+ url = new URL(URL_TO_REACH);
+ } catch (final Exception ex2) {
+ JOptionPane.showMessageDialog(this, "URL not valid : " + URL_TO_REACH, "ERROR", JOptionPane.ERROR_MESSAGE);
+ }
+ return;
+ }
+
+ // METHOD WITH APACHE COMMONS-HTTPCLIENT
+ final HttpClient client = new HttpClient();
+ final 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 {
+ final InetAddress ip = InetAddress.getByName("127.0.0.1");
+ hostName = ip.getHostName();
+ } catch (final Exception ex) {
+ logger.error("", ex);
+ }
+ creds = new NTCredentials(proxyUser, proxyPasswd, hostName, domainName);
+ } else {
+ creds = new UsernamePasswordCredentials(proxyUser, proxyPasswd);
+ }
+ client.getState().setProxyCredentials(AuthScope.ANY, creds);
+ }
+ final HttpMethod meth = new GetMethod(url.toExternalForm());
+ 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 {
+ final String resp = meth.getResponseBodyAsString();
+ JOptionPane.showMessageDialog(this, "Connexion réussie !", "Ok, ça marche...", JOptionPane.INFORMATION_MESSAGE);
+ }
+ } catch (final 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() {
+
+ this.chkAuthenticationRequired = new javax.swing.JCheckBox();
+ this.chkUseProxy = new javax.swing.JCheckBox();
+ this.pbTest = new javax.swing.JButton();
+ this.lblServer = new javax.swing.JLabel();
+ this.dfProxyServer = new javax.swing.JTextField();
+ this.lblPort = new javax.swing.JLabel();
+ this.dfProxyPort = new javax.swing.JTextField();
+ this.lblUser = new javax.swing.JLabel();
+ this.dfProxyUser = new javax.swing.JTextField();
+ this.lblPassword = new javax.swing.JLabel();
+ this.dfProxyPassword = new javax.swing.JPasswordField();
+ this.lblDomain = new javax.swing.JLabel();
+ this.dfDomainName = new javax.swing.JTextField();
+
+ this.chkAuthenticationRequired.setText("Mon serveur proxy requiert une authentification");
+ this.chkAuthenticationRequired.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
+ this.chkAuthenticationRequired.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PnlProxy.this.chkAuthenticationRequiredActionPerformed(evt);
+ }
+ });
+
+ this.chkUseProxy.setText("J'utilise un serveur proxy pour me connecter à internet");
+ this.chkUseProxy.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
+ this.chkUseProxy.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PnlProxy.this.chkUseProxyActionPerformed(evt);
+ }
+ });
+
+ this.pbTest.setText("Tester");
+ this.pbTest.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PnlProxy.this.pbTestActionPerformed(evt);
+ }
+ });
+
+ this.lblServer.setText("Serveur");
+
+ this.lblPort.setText("Port");
+
+ this.lblUser.setText("Utilisateur");
+
+ this.lblPassword.setText("Mot de passe");
+
+ this.lblDomain.setText("Domaine Windows");
+
+ final 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(this.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(this.lblUser).add(this.lblPassword).add(this.lblDomain))
+ .add(12, 12, 12)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(this.dfProxyUser, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 290, Short.MAX_VALUE)
+ .add(this.dfProxyPassword, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 290, Short.MAX_VALUE).add(this.dfDomainName, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 290, Short.MAX_VALUE)))
+ .add(org.jdesktop.layout.GroupLayout.LEADING, this.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(this.lblServer).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.dfProxyServer, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 265, Short.MAX_VALUE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.lblPort)).add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup().addContainerGap().add(this.chkUseProxy)))
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.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(this.chkUseProxy)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE).add(this.lblServer).add(this.dfProxyServer, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .add(this.lblPort).add(this.dfProxyPort, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)).add(16, 16, 16).add(this.chkAuthenticationRequired)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE).add(this.lblUser).add(this.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(this.lblPassword).add(this.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(this.lblDomain).add(this.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(this.pbTest).addContainerGap()));
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void pbTestActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbTestActionPerformed
+ this.runTest();
+ }// GEN-LAST:event_pbTestActionPerformed
+
+ private void chkUseProxyActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_chkUseProxyActionPerformed
+ final boolean selected = this.chkUseProxy.isSelected();
+ this.enableProxyControls(selected);
+ }// GEN-LAST:event_chkUseProxyActionPerformed
+
+ private void chkAuthenticationRequiredActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_chkAuthenticationRequiredActionPerformed
+ final boolean selected = this.chkAuthenticationRequired.isSelected();
+ this.enableAuthenticationControls(selected);
+ }// GEN-LAST:event_chkAuthenticationRequiredActionPerformed
+
+ private void enableProxyControls(final boolean state) {
+ this.lblServer.setEnabled(state);
+ this.dfProxyServer.setEnabled(state);
+ this.lblPort.setEnabled(state);
+ this.dfProxyPort.setEnabled(state);
+ this.chkAuthenticationRequired.setEnabled(state);
+ if (!state) {
+ this.dfProxyServer.setText("");
+ this.dfProxyPort.setText("");
+ }
+ if (state) {
+ this.enableAuthenticationControls(this.chkAuthenticationRequired.isSelected());
+ } else {
+ this.enableAuthenticationControls(false);
+ }
+ }
+
+ private void enableAuthenticationControls(final boolean state) {
+ this.lblUser.setEnabled(state);
+ this.dfProxyUser.setEnabled(state);
+ this.lblPassword.setEnabled(state);
+ this.dfProxyPassword.setEnabled(state);
+ this.lblDomain.setEnabled(state);
+ this.dfDomainName.setEnabled(state);
+ if (!state) {
+ this.dfProxyUser.setText("");
+ this.dfProxyPassword.setText("");
+ this.dfDomainName.setText("");
+ }
+ }
+
+ @Override
+ public void saveConfiguration() {
+ // initialize a properties expansion from system properties
+ // PropertiesExpansion props = new PropertiesExpansion(System.getProperties());
+ final Properties xemProps = new Properties();
+
+ final File xemPropsFile = new File(this.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 (this.dfProxyServer.getText() != null && this.dfProxyServer.getText().length() > 0) {
+ proxyHost = this.dfProxyServer.getText();
+ }
+ if (this.dfProxyPort.getText() != null && this.dfProxyPort.getText().length() > 0) {
+ proxyPort = this.dfProxyPort.getText();
+ }
+ if (this.dfProxyUser.getText() != null && this.dfProxyUser.getText().length() > 0) {
+ proxyUser = this.dfProxyUser.getText();
+ }
+ if (this.dfProxyPassword.getPassword().length > 0) {
+ proxyPasswd = new String(this.dfProxyPassword.getPassword());
+ }
+ if (this.dfDomainName.getText() != null && this.dfDomainName.getText().length() > 0) {
+ domainName = this.dfDomainName.getText();
+ }
+
+ if (proxyHost != null) {
+ xemProps.put(Constants.SYS_PROP_PROXY_SERVER, proxyHost);
+ xemProps.put(Constants.SYS_PROP_PROXY_PORT, proxyPort);
+ this.applicationConfiguration.setProperty(Constants.SYS_PROP_PROXY_SERVER, proxyHost);
+ this.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));
+ this.applicationConfiguration.setProperty(Constants.SYS_PROP_PROXY_USER, proxyUser);
+ this.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);
+ this.applicationConfiguration.remove(Constants.SYS_PROP_PROXY_USER);
+ this.applicationConfiguration.remove(Constants.SYS_PROP_PROXY_PASSWD);
+ }
+ if (domainName != null) {
+ xemProps.put(Constants.SYS_PROP_PROXY_DOMAIN, domainName);
+ this.applicationConfiguration.setProperty(Constants.SYS_PROP_PROXY_DOMAIN, domainName);
+ } else {
+ xemProps.remove(Constants.SYS_PROP_PROXY_DOMAIN);
+ this.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);
+ this.applicationConfiguration.remove(Constants.SYS_PROP_PROXY_SERVER);
+ this.applicationConfiguration.remove(Constants.SYS_PROP_PROXY_PORT);
+ this.applicationConfiguration.remove(Constants.SYS_PROP_PROXY_USER);
+ this.applicationConfiguration.remove(Constants.SYS_PROP_PROXY_PASSWD);
+ }
+ final FileOutputStream fos = new FileOutputStream(xemPropsFile);
+ xemProps.store(fos, "");
+ fos.close();
+ } catch (final 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
+
}
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;
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+
/**
- *
- * @author chm
+ *
+ * @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();
- pbReload = 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);
- }
- });
-
- pbReload.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fr/gouv/finances/cp/xemelios/ui/resources/view-refresh.png"))); // NOI18N
- pbReload.setToolTipText("Recharger");
- pbReload.addActionListener(new java.awt.event.ActionListener() {
- public void actionPerformed(java.awt.event.ActionEvent evt) {
- pbReloadActionPerformed(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, layout.createSequentialGroup()
- .add(jLabel1)
- .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 221, Short.MAX_VALUE)
- .add(pbReload))
- .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
- .add(jLabel2)
- .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
- .add(dfValue, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 293, 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(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
- .add(jLabel1)
- .add(pbReload))
- .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
- .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE)
- .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
- .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE, false)
- .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.PREFERRED_SIZE, 28, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
- .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
-
- private void pbReloadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbReloadActionPerformed
- for(Prop p:listModel.data) {
- p.propValue = applicationConfiguration.getProperty(p.propName);
- }
- lstProps.setModel(listModel);
- }//GEN-LAST:event_pbReloadActionPerformed
-
- @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 pbReload;
- 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];
- }
-
- }
+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 final PropertiesExpansion applicationConfiguration;
+
+ /** Creates new form PnlUpdate */
+ public PnlSystemProperties(final PropertiesExpansion applicationConfiguration) {
+ this.applicationConfiguration = applicationConfiguration;
+ this.preInitComponents();
+ this.initComponents();
+ this.postInitComponents();
+ }
+
+ protected void preInitComponents() {
+ this.properties = new TreeSet<Prop>();
+ for (final Object key : this.applicationConfiguration.keySet()) {
+ final String propName = key.toString();
+ if (propName.startsWith("xemelios")) {
+ final Prop prop = new Prop(propName, this.applicationConfiguration.getProperty(propName));
+ this.properties.add(prop);
+ }
+ }
+ // on va chercher celles existantes (potentiellement)
+ final Class clazz = Constants.class;
+ final Field[] fields = clazz.getFields();
+ for (final Field field : fields) {
+ if (field.getType().equals(String.class) && (field.getModifiers() | (Modifier.PUBLIC + Modifier.STATIC + Modifier.FINAL)) > 0) {
+ try {
+ final String propName = field.get(null).toString();
+ if (propName.startsWith("xemelios") || field.getName().startsWith("SYS_PROP")) {
+ final Prop p = new Prop(propName, null);
+ if (!this.properties.contains(p)) {
+ this.properties.add(p);
+ }
+ }
+ } catch (final Exception ex) {
+ logger.debug("while introspecting", ex);
+ }
+ }
+ }
+ this.listModel = new LM(this.properties);
+ }
+
+ protected void postInitComponents() {
+ this.lstProps.addListSelectionListener(new ListSelectionListener() {
+
+ @Override
+ public void valueChanged(final ListSelectionEvent e) {
+ PnlSystemProperties.this.currentProp = (Prop) PnlSystemProperties.this.lstProps.getSelectedValue();
+ if (PnlSystemProperties.this.currentProp != null) {
+ PnlSystemProperties.this.dfValue.setEditable(true);
+ PnlSystemProperties.this.dfValue.setText(PnlSystemProperties.this.currentProp.getPropValue());
+ PnlSystemProperties.this.pbSet.setEnabled(true);
+ } else {
+ PnlSystemProperties.this.dfValue.setEditable(false);
+ PnlSystemProperties.this.dfValue.setText(null);
+ PnlSystemProperties.this.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() {
+
+ this.jLabel1 = new javax.swing.JLabel();
+ this.jScrollPane1 = new javax.swing.JScrollPane();
+ this.lstProps = new javax.swing.JList();
+ this.jLabel2 = new javax.swing.JLabel();
+ this.dfValue = new javax.swing.JTextField();
+ this.pbSet = new javax.swing.JButton();
+ this.pbReload = new javax.swing.JButton();
+
+ this.jLabel1.setText("Propriétés systèmes");
+
+ this.lstProps.setModel(this.listModel);
+ this.lstProps.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
+ this.jScrollPane1.setViewportView(this.lstProps);
+
+ this.jLabel2.setText("Valeur");
+
+ this.pbSet.setIcon(new javax.swing.ImageIcon(this.getClass().getResource("/fr/gouv/finances/cp/xemelios/ui/resources/edit-redo.png"))); // NOI18N
+ this.pbSet.setToolTipText("Enregistrer la valeur");
+ this.pbSet.setEnabled(false);
+ this.pbSet.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PnlSystemProperties.this.pbSetActionPerformed(evt);
+ }
+ });
+
+ this.pbReload.setIcon(new javax.swing.ImageIcon(this.getClass().getResource("/fr/gouv/finances/cp/xemelios/ui/resources/view-refresh.png"))); // NOI18N
+ this.pbReload.setToolTipText("Recharger");
+ this.pbReload.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PnlSystemProperties.this.pbReloadActionPerformed(evt);
+ }
+ });
+
+ final 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, this.jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 374, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup().add(this.jLabel1).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 221, Short.MAX_VALUE).add(this.pbReload))
+ .add(org.jdesktop.layout.GroupLayout.LEADING,
+ layout.createSequentialGroup().add(this.jLabel2).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.dfValue, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 293, Short.MAX_VALUE).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(this.pbSet))).addContainerGap()));
+ layout.setVerticalGroup(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(
+ layout.createSequentialGroup()
+ .addContainerGap()
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE).add(this.jLabel1).add(this.pbReload))
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(this.jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE, false).add(this.jLabel2).add(this.dfValue, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .add(this.pbSet, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 28, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)).addContainerGap()));
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void pbSetActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbSetActionPerformed
+ if (this.currentProp != null) {
+ String value = this.dfValue.getText();
+ if (value != null && value.length() == 0) {
+ value = null;
+ }
+ this.currentProp.setPropValue(value);
+ System.setProperty(this.currentProp.getPropName(), value);
+ }
+ }// GEN-LAST:event_pbSetActionPerformed
+
+ private void pbReloadActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbReloadActionPerformed
+ for (final Prop p : this.listModel.data) {
+ p.propValue = this.applicationConfiguration.getProperty(p.propName);
+ }
+ this.lstProps.setModel(this.listModel);
+ }// GEN-LAST:event_pbReloadActionPerformed
+
+ @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 pbReload;
+ 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(final String propName, final String propValue) {
+ super();
+ this.propName = propName;
+ this.propValue = propValue;
+ }
+
+ @Override
+ public String toString() {
+ return this.propName;
+ }
+
+ public String getDocumentation() {
+ return this.documentation;
+ }
+
+ public void setDocumentation(final String documentation) {
+ this.documentation = documentation;
+ }
+
+ public String getPropName() {
+ return this.propName;
+ }
+
+ public void setPropName(final String propName) {
+ this.propName = propName;
+ }
+
+ public String getPropValue() {
+ return this.propValue;
+ }
+
+ public void setPropValue(final String propValue) {
+ this.propValue = propValue;
+ }
+
+ public boolean equals(final Prop other) {
+ return this.propName.equals(other.getPropName());
+ }
+
+ @Override
+ public int compareTo(final Object o) {
+ final Prop other = (Prop) o;
+ return this.propName.compareTo(other.getPropName());
+ }
+ }
+
+ private class LM extends AbstractListModel {
+ private final Prop[] data;
+
+ public LM(final TreeSet<Prop> properties) {
+ super();
+ this.data = new Prop[properties.size()];
+ properties.toArray(this.data);
+ }
+
+ @Override
+ public int getSize() {
+ return this.data.length;
+ }
+
+ @Override
+ public Object getElementAt(final int index) {
+ return this.data[index];
+ }
+
+ }
}
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;
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import fr.gouv.finances.dgfip.utils.Pair;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+
/**
- *
- * @author chm
+ *
+ * @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"));
- pnlConfig.setEnabled(false);
-
- lblConfig.setText(CONFIG_STRAT);
- lblConfig.setEnabled(false);
-
- jLabel2.setText("Configuration");
- jLabel2.setEnabled(false);
-
- cbxConfig.setEnabled(false);
-
- 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);
- if(xemPropsFile.exists()) {
- 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
-
+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 final PropertiesExpansion applicationProperties;
+
+ /** Creates new form PnlUpdate */
+ public PnlUpdate(final PropertiesExpansion applicationProperties) {
+ this.applicationProperties = applicationProperties;
+ this.initComponents();
+ this.initValues();
+ }
+
+ private void initValues() {
+ String currentStrat = this.applicationProperties.getProperty(Constants.SYS_PROP_MAJ_STRATEGY);
+ if (currentStrat == null) {
+ currentStrat = Constants.MAJ_CONFIRM;
+ }
+ for (int i = 0; i < this.cbxStrategie.getItemCount(); i++) {
+ final Pair p = (Pair) this.cbxStrategie.getItemAt(i);
+ if (p.key.equals(currentStrat)) {
+ this.cbxStrategie.setSelectedIndex(i);
+ break;
+ }
+ }
+ String currentConfig = this.applicationProperties.getProperty(Constants.SYS_PROP_MAJ_CONFIG);
+ if (currentStrat == null) {
+ currentConfig = Constants.MAJ_PROD;
+ }
+ for (int i = 0; i < this.cbxConfig.getItemCount(); i++) {
+ final Pair p = (Pair) this.cbxConfig.getItemAt(i);
+ if (p.key.equals(currentConfig)) {
+ this.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() {
+
+ this.pnlStrategie = new javax.swing.JPanel();
+ this.lblStrat = new javax.swing.JLabel();
+ this.jLabel1 = new javax.swing.JLabel();
+ this.cbxStrategie = new javax.swing.JComboBox(STRATEGIES);
+ this.pnlConfig = new javax.swing.JPanel();
+ this.lblConfig = new javax.swing.JLabel();
+ this.jLabel2 = new javax.swing.JLabel();
+ this.cbxConfig = new javax.swing.JComboBox(CONFIGS);
+
+ this.pnlStrategie.setBorder(javax.swing.BorderFactory.createTitledBorder("Stratégie de mise à jour"));
+
+ this.lblStrat.setText(STRAT_STRING);
+
+ this.jLabel1.setText("Stratégie de mise à jour");
+
+ final org.jdesktop.layout.GroupLayout pnlStrategieLayout = new org.jdesktop.layout.GroupLayout(this.pnlStrategie);
+ this.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(this.jLabel1).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.cbxStrategie, 0, 174, Short.MAX_VALUE))
+ .add(this.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(this.lblStrat).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(pnlStrategieLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE).add(this.jLabel1).add(this.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)));
+
+ this.pnlConfig.setBorder(javax.swing.BorderFactory.createTitledBorder("Configuration"));
+ this.pnlConfig.setEnabled(false);
+
+ this.lblConfig.setText(CONFIG_STRAT);
+ this.lblConfig.setEnabled(false);
+
+ this.jLabel2.setText("Configuration");
+ this.jLabel2.setEnabled(false);
+
+ this.cbxConfig.setEnabled(false);
+
+ final org.jdesktop.layout.GroupLayout pnlConfigLayout = new org.jdesktop.layout.GroupLayout(this.pnlConfig);
+ this.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(this.lblConfig, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 340, Short.MAX_VALUE)
+ .add(pnlConfigLayout.createSequentialGroup().add(this.jLabel2).add(71, 71, 71).add(this.cbxConfig, 0, 184, Short.MAX_VALUE))).addContainerGap()));
+ pnlConfigLayout.setVerticalGroup(pnlConfigLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(
+ pnlConfigLayout.createSequentialGroup().add(this.lblConfig).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(pnlConfigLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE).add(this.jLabel2).add(this.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)));
+
+ final 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, this.pnlConfig, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.LEADING, this.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(this.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(this.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() {
+ final Properties xemProps = new Properties();
+
+ final File xemPropsFile = new File(this.applicationProperties.replace("${xemelios.prg}/root/xemelios.properties"));
+ try {
+ if (xemPropsFile.exists()) {
+ xemProps.load(new FileInputStream(xemPropsFile));
+ }
+ xemProps.setProperty(Constants.SYS_PROP_MAJ_STRATEGY, ((Pair) this.cbxStrategie.getSelectedItem()).key);
+ this.applicationProperties.setProperty(Constants.SYS_PROP_MAJ_STRATEGY, ((Pair) this.cbxStrategie.getSelectedItem()).key);
+ xemProps.setProperty(Constants.SYS_PROP_MAJ_CONFIG, ((Pair) this.cbxConfig.getSelectedItem()).key);
+ this.applicationProperties.setProperty(Constants.SYS_PROP_MAJ_CONFIG, ((Pair) this.cbxConfig.getSelectedItem()).key);
+ if (xemPropsFile.exists()) {
+ final FileOutputStream fos = new FileOutputStream(xemPropsFile);
+ xemProps.store(fos, "");
+ fos.close();
+ }
+ } catch (final 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
+
}
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);
+ 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");
+ /** Creates new form PnlVersion */
+ public PnlVersion() {
+ this.initComponents();
+ String spec_version = System.getProperty("java.specification.version");
+ final String upd_version = System.getProperty("java.version");
+ final 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);
- }
+ final double vnum = Double.parseDouble(spec_version);
+ if (vnum >= 1.6d) {
+ spec_version = spec_version.concat("(OK)");
+ } else {
+ spec_version = spec_version.concat("(KO)");
+ }
+ this.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() {
+ /**
+ * 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();
+ this.jLabel1 = new javax.swing.JLabel();
+ this.jScrollPane1 = new javax.swing.JScrollPane();
+ this.jTextArea1 = new javax.swing.JTextArea();
- jLabel1.setText("Version JAVA utilisée :");
+ this.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);
+ this.jTextArea1.setBackground(javax.swing.UIManager.getDefaults().getColor("Panel.background"));
+ this.jTextArea1.setColumns(20);
+ this.jTextArea1.setRows(5);
+ this.jTextArea1.setBorder(null);
+ this.jScrollPane1.setViewportView(this.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
+ final 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(this.jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
+ .addComponent(this.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(this.jLabel1).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(this.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;
- // 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
+ // End of variables declaration//GEN-END:variables
- @Override
- public void saveConfiguration() {
- //throw new UnsupportedOperationException("Not supported yet.");
- }
+ @Override
+ public void saveConfiguration() {
+ // throw new UnsupportedOperationException("Not supported yet.");
+ }
}
*/
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.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;
+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;
+
/**
- *
+ *
* @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) {
-
- }
- @Override
- 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; }
- public 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(")");
- }
-
- }
+ private static final Logger logger = Logger.getLogger(DlgSelectCollectivite.class);
+
+ private final DocumentModel dm;
+ private final XemeliosUser user;
+ private final JFrame parent;
+ private JComboBox cbxCollectivites;
+ private ParentCollectiviteContainer container;
+ private boolean response;
+
+ public DlgSelectCollectivite(final DocumentModel dm, final XemeliosUser user, final JFrame parent) {
+ super(parent, "Choisir une collectivité", true);
+ this.dm = dm;
+ this.user = user;
+ this.parent = parent;
+ this.initComponents();
+ }
+
+ protected void initComponents() {
+ this.setLayout(new BorderLayout());
+ final JPanel vPane = new JPanel(new VerticalFlowLayout());
+ // final Pair parentColls[] = new Pair[dm.getCollectivitePath().getParentsCount()];
+ this.container = new ParentCollectiviteContainer(this.dm.getCollectivitePath().getParentsCount());
+ final JPanel collPane = new JPanel(new GridBagLayout());
+ final 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 (this.dm.getCollectivitePath().getParentsCount() > 0) {
+ for (int i = this.dm.getCollectivitePath().getParentsCount() - 1; i >= 0; i--) {
+ final PnlCollectivite pnl = new PnlCollectivite(this, this.dm, this.dm.getCollectivitePath().getParent(i), this.container, this.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;
+ this.cbxCollectivites = new JComboBox();
+ collPane.add(this.cbxCollectivites, cstr);
+ this.addComplementElements(collPane, cstr);
+ vPane.add(collPane);
+ final JPanel hPane = new JPanel(new BorderLayout());
+ final JPanel buttonPane = new JPanel();
+ final JButton pbCancel = new JButton("Annuler");
+ pbCancel.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ DlgSelectCollectivite.this.setVisible(false);
+ }
+ });
+ buttonPane.add(pbCancel);
+ final JButton pbOk = new JButton("Ok");
+ pbOk.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ if (DlgSelectCollectivite.this.cbxCollectivites.getSelectedIndex() >= 0) {
+ DlgSelectCollectivite.this.response = true;
+ DlgSelectCollectivite.this.setVisible(false);
+ }
+ }
+ });
+ buttonPane.add(pbOk);
+ hPane.add(buttonPane, BorderLayout.CENTER);
+ vPane.add(hPane);
+ this.add(vPane, BorderLayout.CENTER);
+ this.container.addListener(this);
+ if (this.dm.getCollectivitePath().getParentsCount() == 0) {
+ this.valueChanged(1, null);
+ }
+ this.pack();
+ this.setLocationRelativeTo(this.parent);
+ }
+
+ public void addComplementElements(final JPanel collPane, final GridBagConstraints cstr) {
+
+ }
+
+ @Override
+ public void valueChanged(final int pos, final Pair newValue) {
+ if (pos == 1) { // direct parent has changed
+ this.cbxCollectivites.removeAllItems();
+ try {
+ final Vector<Pair> colls = DataLayerManager.getImplementation().getCollectivites(this.dm, this.container.getParents(), this.user);
+ for (final Pair p : colls) {
+ this.cbxCollectivites.addItem(new MyPair(p));
+ }
+ } catch (final Exception ex) {
+ logger.error("while querying collectivites:", ex);
+ }
+ } else {
+ this.cbxCollectivites.removeAllItems();
+ }
+ }
+
+ @Override
+ public void setVisible(final boolean b) {
+ if (b) {
+ this.response = false;
+ }
+ super.setVisible(b);
+ }
+
+ public boolean run() {
+ this.setVisible(true);
+ return this.response;
+ }
+
+ public Pair getCollectivite() {
+ return (Pair) this.cbxCollectivites.getSelectedItem();
+ }
+
+ public DocumentModel getDm() {
+ return this.dm;
+ }
+
+ public XemeliosUser getUser() {
+ return this.user;
+ }
+
+ JComboBox getCbxCollectivite() {
+ return this.cbxCollectivites;
+ }
+
+ public static class ParentCollectiviteContainer {
+ Pair parentColls[];
+ List<ParentCollectiviteListener> listeners;
+ private int size = 0;
+
+ public ParentCollectiviteContainer(final int size) {
+ super();
+ this.size = size;
+ this.parentColls = new Pair[size];
+ this.listeners = new ArrayList<ParentCollectiviteListener>();
+ }
+
+ public void setPair(final int pos, final Pair value) {
+ this.parentColls[pos] = value;
+ for (int i = pos - 1; i >= 0; i--) {
+ this.parentColls[i] = null;
+ this.fireValueChanged(pos + 1, value);
+ }
+ this.fireValueChanged(pos + 1, value);
+ }
+
+ public Pair getPair(final int pos) {
+ return this.parentColls[pos];
+ }
+
+ protected void fireValueChanged(final int pos, final Pair value) {
+ for (final ParentCollectiviteListener listener : this.listeners) {
+ listener.valueChanged(pos, value);
+ }
+ }
+
+ void addListener(final ParentCollectiviteListener listener) {
+ this.listeners.add(listener);
+ }
+
+ public int getSize() {
+ return this.size;
+ }
+
+ public Pair[] getParents() {
+ return this.parentColls;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuffer sb = new StringBuffer();
+ sb.append("[");
+ for (int i = 0; i < this.parentColls.length; i++) {
+ sb.append(this.parentColls[i]);
+ if (i != (this.parentColls.length - 1)) {
+ sb.append(",");
+ }
+ }
+ sb.append("]");
+ return sb.toString();
+ }
+ }
+
+ private class MyPair extends Pair {
+ public MyPair(final Pair p) {
+ super(p.key, p.libelle);
+ }
+
+ @Override
+ public String toString() {
+ return this.libelle.concat(" (").concat(this.key).concat(")");
+ }
+
+ }
}
*/
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;
+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;
+
/**
- *
+ *
* @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;
+ private static final Logger logger = Logger.getLogger(DlgSelectCollectivite.class);
+ ArrayList<JComboBox> specialKeysLists;
+ ArrayList<SpecialKeyModel> models;
+ ArrayList<Pair> specialKeys;
+ private JComboBox cbxBudget;
+
+ public DlgSelectNavigationTarget(final DocumentModel dm, final XemeliosUser user, final JFrame parent) {
+ super(dm, user, parent);
+ this.setTitle("Choisir une collectivité, un budget ...");
+ }
+
+ public Pair getBudget() {
+ return (Pair) this.cbxBudget.getSelectedItem();
+ }
- 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; }
+ public List<Pair> getSpecialKeys() {
+ return this.specialKeys;
+ }
- @Override
- public void addComplementElements(JPanel collPane, GridBagConstraints cstr) {
- getCbxCollectivite().addItemListener(new ItemListener() {
- @Override
- 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() {
- @Override
- 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() {
- @Override
- 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);
- }
- }
- }
- }
- });
- }
- }
- }
+ @Override
+ public void addComplementElements(final JPanel collPane, final GridBagConstraints cstr) {
+ this.getCbxCollectivite().addItemListener(new ItemListener() {
+ @Override
+ public void itemStateChanged(final ItemEvent e) {
+ if (e.getStateChange() == ItemEvent.DESELECTED) {
+ DlgSelectNavigationTarget.this.cbxBudget.removeAllItems();
+ } else {
+ try {
+ final Vector<Pair> data = DataLayerManager.getImplementation().getBudgets(DlgSelectNavigationTarget.this.getDm(), DlgSelectNavigationTarget.this.getCollectivite(), DlgSelectNavigationTarget.this.getUser());
+ for (final Pair p : data) {
+ DlgSelectNavigationTarget.this.cbxBudget.addItem(p);
+ }
+ DlgSelectNavigationTarget.this.cbxBudget.setSelectedIndex(0);
+ } catch (final 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);
+ this.cbxBudget = new JComboBox();
+ cstr.gridx = 1;
+ cstr.weightx = 0d;
+ cstr.gridwidth = 2;
+ cstr.anchor = GridBagConstraints.WEST;
+ collPane.add(this.cbxBudget, cstr);
+ if (!this.getDm().getSpecialKeys().isEmpty()) {
+ this.cbxBudget.addItemListener(new ItemListener() {
+ @Override
+ public void itemStateChanged(final ItemEvent e) {
+ try {
+ if (DlgSelectNavigationTarget.this.getBudget() != null) {
+ final Vector<Pair> data = DataLayerManager.getImplementation().getSpecialKeys1(DlgSelectNavigationTarget.this.getDm(), DlgSelectNavigationTarget.this.getCollectivite(), DlgSelectNavigationTarget.this.getBudget(), true, DlgSelectNavigationTarget.this.getUser());
+ final JComboBox cbx = DlgSelectNavigationTarget.this.specialKeysLists.get(0);
+ cbx.removeAllItems();
+ for (final Pair p : data) {
+ cbx.addItem(p);
+ }
+ cbx.setSelectedIndex(0);
+ }
+ } catch (final Exception ex) {
+ logger.error("while getting keys1:", ex);
+ }
+ }
+ });
+ this.specialKeysLists = new ArrayList<JComboBox>();
+ this.models = new ArrayList<SpecialKeyModel>();
+ this.specialKeys = new ArrayList<Pair>();
+ for (final SpecialKeyModel skm : this.getDm().getSpecialKeys()) {
+ cstr.gridy++;
+ cstr.gridx = 0;
+ cstr.gridwidth = 1;
+ cstr.weightx = 1d;
+ cstr.anchor = GridBagConstraints.EAST;
+ collPane.add(new JLabel(skm.getLibelle()), cstr);
+ final JComboBox cbx = new JComboBox();
+ cstr.gridx = 1;
+ cstr.weightx = 0d;
+ cstr.gridwidth = 2;
+ cstr.anchor = GridBagConstraints.WEST;
+ collPane.add(cbx, cstr);
+ this.specialKeysLists.add(cbx);
+ cbx.addItemListener(new ItemListener() {
+ @Override
+ public void itemStateChanged(final ItemEvent e) {
+ final JComboBox thisOne = (JComboBox) e.getItemSelectable();
+ final int rank = DlgSelectNavigationTarget.this.specialKeysLists.indexOf(thisOne);
+ if (e.getStateChange() == ItemEvent.DESELECTED) {
+ for (int i = rank + 1; i < DlgSelectNavigationTarget.this.specialKeysLists.size(); i++) {
+ final JComboBox cbx = DlgSelectNavigationTarget.this.specialKeysLists.get(i);
+ cbx.removeAllItems();
+ }
+ while (DlgSelectNavigationTarget.this.specialKeys.size() > rank) {
+ DlgSelectNavigationTarget.this.specialKeys.remove(rank);
+ }
+ } else {
+ DlgSelectNavigationTarget.this.specialKeys.add((Pair) thisOne.getSelectedItem());
+ // SpecialKeyModel skm = models.get(rank);
+ if (rank == 0) {
+ try {
+ final Vector<Pair> data = DataLayerManager.getImplementation().getSpecialKeys2(DlgSelectNavigationTarget.this.getDm(), DlgSelectNavigationTarget.this.getCollectivite(), DlgSelectNavigationTarget.this.getBudget(), (Pair) thisOne.getSelectedItem(), true,
+ DlgSelectNavigationTarget.this.getUser());
+ final JComboBox cbx = DlgSelectNavigationTarget.this.specialKeysLists.get(1);
+ for (final Pair p : data) {
+ cbx.addItem(p);
+ }
+ cbx.setSelectedIndex(0);
+ } catch (final IndexOutOfBoundsException aioobEx) {
+ // ignore
+ } catch (final Exception ex) {
+ logger.error("while getting keys2:", ex);
+ }
+ } else if (rank == 1) {
+ final JComboBox previousOne = DlgSelectNavigationTarget.this.specialKeysLists.get(0);
+ try {
+ final Vector<Pair> data = DataLayerManager.getImplementation().getSpecialKeys3(DlgSelectNavigationTarget.this.getDm(), DlgSelectNavigationTarget.this.getCollectivite(), DlgSelectNavigationTarget.this.getBudget(), (Pair) thisOne.getSelectedItem(),
+ (Pair) previousOne.getSelectedItem(), true, DlgSelectNavigationTarget.this.getUser());
+ final JComboBox cbx = DlgSelectNavigationTarget.this.specialKeysLists.get(2);
+ for (final Pair p : data) {
+ cbx.addItem(p);
+ }
+ cbx.setSelectedIndex(0);
+ } catch (final IndexOutOfBoundsException aioobEx) {
+ // ignore
+ } catch (final Exception ex) {
+ logger.error("while getting keys3:", ex);
+ }
+ }
+ }
+ }
+ });
+ }
+ }
+ }
}
*/
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;
+import fr.gouv.finances.dgfip.utils.Pair;
+
/**
- *
+ *
* @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;
- }
-
- }
+ private static final long serialVersionUID = 1L;
+
+ private final String title, message;
+ private final Vector<Pair> elements;
+ private boolean response = false;
+ private final PairTableModel tableModel;
+
+ /** Creates new form DlgSelectPair */
+ public DlgSelectPair(final JDialog parent, final String title, final String message, final Vector<Pair> elements) {
+ super(parent, true);
+ this.title = title;
+ this.message = message;
+ this.elements = elements;
+ this.tableModel = new PairTableModel(this.elements);
+ this.initComponents();
+ this.table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
+ this.setLocationRelativeTo(parent);
+ }
+
+ public Pair showSelectionBox() {
+ this.response = false;
+ this.setVisible(true);
+ if (this.response) {
+ return this.elements.get(this.table.convertRowIndexToModel(this.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() {
+
+ this.jLabel1 = new javax.swing.JLabel();
+ this.pbOk = new javax.swing.JButton();
+ this.pbCancel = new javax.swing.JButton();
+ this.jScrollPane1 = new javax.swing.JScrollPane();
+ this.table = new org.jdesktop.swingx.JXTable();
+
+ this.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+ this.setTitle(this.title);
+
+ this.jLabel1.setText(this.message);
+
+ this.pbOk.setText("Ok");
+ this.pbOk.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgSelectPair.this.pbOkActionPerformed(evt);
+ }
+ });
+
+ this.pbCancel.setText("Annuler");
+ this.pbCancel.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgSelectPair.this.pbCancelActionPerformed(evt);
+ }
+ });
+
+ this.table.setModel(this.tableModel);
+ this.table.addMouseListener(new java.awt.event.MouseAdapter() {
+ @Override
+ public void mouseClicked(final java.awt.event.MouseEvent evt) {
+ DlgSelectPair.this.tableMouseClicked(evt);
+ }
+ });
+ this.jScrollPane1.setViewportView(this.table);
+
+ final org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this.getContentPane());
+ this.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(this.jScrollPane1).add(this.jLabel1)).addContainerGap())
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup().addContainerGap(174, Short.MAX_VALUE).add(this.pbCancel).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.pbOk).addContainerGap()));
+ layout.setVerticalGroup(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(
+ layout.createSequentialGroup().addContainerGap().add(this.jLabel1).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.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(this.pbOk).add(this.pbCancel)).addContainerGap()));
+
+ this.pack();
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void pbCancelActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbCancelActionPerformed
+ this.setVisible(false);
+ }// GEN-LAST:event_pbCancelActionPerformed
+
+ private void pbOkActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbOkActionPerformed
+ if (this.table.getSelectedRowCount() > 0) {
+ this.response = true;
+ this.setVisible(false);
+ }
+ }// GEN-LAST:event_pbOkActionPerformed
+
+ private void tableMouseClicked(final java.awt.event.MouseEvent evt) {// GEN-FIRST:event_tableMouseClicked
+ if (evt.getClickCount() >= 2) {
+ this.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(final Vector<Pair> data) {
+ super();
+ this.data = data;
+ }
+
+ @Override
+ public Object getValueAt(final int row, final int column) {
+ final Pair p = this.data.get(row);
+ if (column == 0) {
+ return p.key;
+ } else {
+ return p.libelle;
+ }
+ }
+
+ @Override
+ public boolean isCellEditable(final int row, final int column) {
+ return false;
+ }
+
+ @Override
+ public String getColumnName(final int column) {
+ switch (column) {
+ case 0:
+ return "Code";
+ default:
+ return "Libellé";
+ }
+ }
+
+ @Override
+ public int getColumnCount() {
+ return 2;
+ }
+
+ public void setData(final Vector<Pair> data) {
+ this.data = data;
+ this.fireTableDataChanged();
+ }
+
+ @Override
+ public int getRowCount() {
+ return this.data != null ? this.data.size() : 0;
+ }
+
+ }
}
import fr.gouv.finances.dgfip.utils.Pair;
/**
- *
+ *
* @author chm
*/
public interface ParentCollectiviteListener {
- public void valueChanged(int pos, Pair newValue);
+ public void valueChanged(int pos, Pair newValue);
}
*/
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;
+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;
+
/**
- *
+ *
* @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;
-
- public 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() {
- @Override
- 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();
- }
-
- @Override
- 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;
- }
-
- }
+ private static final Logger logger = Logger.getLogger(PnlCollectivite.class);
+ private final DocumentModel dm;
+ private ParentModel parentModel = null;
+ private final DlgSelectCollectivite.ParentCollectiviteContainer collectivites;
+ private XemeliosUser user = null;
+ private JTextField df;
+ private Pair selectedPair;
+ private final int level;
+ private final JDialog parentDialog;
+ private JLabel lbl;
+ private JButton pb;
+
+ public PnlCollectivite(final JDialog parentDialog, final DocumentModel dm, final ParentModel parentModel, final DlgSelectCollectivite.ParentCollectiviteContainer collectivites, final XemeliosUser user) {
+ super();
+ this.parentDialog = parentDialog;
+ this.dm = dm;
+ this.parentModel = parentModel;
+ this.level = parentModel.getLevel();
+ this.collectivites = collectivites;
+ this.user = user;
+ this.initComponents();
+ collectivites.addListener(this);
+ }
+
+ protected void initComponents() {
+ this.lbl = new JLabel(this.getLibelle());
+ this.df = new JTextField();
+ this.df.setEditable(false);
+ this.df.setColumns(40);
+ this.pb = new JButton("...") {
+ @Override
+ public int getHeight() {
+ return PnlCollectivite.this.df.getHeight();
+ }
+
+ @Override
+ public int getWidth() {
+ return this.getHeight();
+ }
+ };
+ this.pb.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ // logger.debug(collectivites);
+ if (PnlCollectivite.this.collectivites.getSize() >= PnlCollectivite.this.level) {
+ final Pair[] localParents = new Pair[PnlCollectivite.this.collectivites.getSize() - PnlCollectivite.this.level];
+ for (int i = PnlCollectivite.this.parentModel.getLevel(); i < PnlCollectivite.this.collectivites.getSize(); i++) {
+ localParents[i - PnlCollectivite.this.level] = PnlCollectivite.this.collectivites.getPair(i);
+ }
+ try {
+ final Vector<Pair> colls = DataLayerManager.getImplementation().getParentCollectivites(PnlCollectivite.this.dm, PnlCollectivite.this.level, localParents, PnlCollectivite.this.user);
+ final Vector<Pair> tmpColls = new Vector<Pair>();
+ for (final Pair p : colls) {
+ tmpColls.add(new MyPair(p));
+ }
+ final DlgSelectPair dlg = new DlgSelectPair(PnlCollectivite.this.parentDialog, "Collectivités", PnlCollectivite.this.parentModel.getLibelle(), tmpColls);
+ final Pair p = dlg.showSelectionBox();
+ if (p != null) {
+ PnlCollectivite.this.selectedPair = p;
+ PnlCollectivite.this.df.setText(PnlCollectivite.this.selectedPair.toString());
+ PnlCollectivite.this.collectivites.setPair(PnlCollectivite.this.parentModel.getLevel() - 1, PnlCollectivite.this.selectedPair);
+ }
+ } catch (final Exception ex) {
+ logger.error("looking for parents:", ex);
+ }
+ }
+ // logger.debug(collectivites);
+ }
+ });
+ // add(pb);
+ }
+
+ protected String getLibelle() {
+ return this.parentModel.getLibelle();
+ }
+
+ @Override
+ public void valueChanged(final int pos, final Pair newValue) {
+ // logger.debug(getLibelle()+"("+level+") received valueChanged("+pos+","+newValue+")");
+ if (pos > this.level) {
+ this.selectedPair = null;
+ this.df.setText("");
+ }
+ }
+
+ public JLabel getLabel() {
+ return this.lbl;
+ }
+
+ public JTextField getTextField() {
+ return this.df;
+ }
+
+ public JButton getButton() {
+ return this.pb;
+ }
+
+ private class MyPair extends Pair {
+ public MyPair(final Pair p) {
+ super(p.key, p.libelle);
+ }
+
+ @Override
+ public String toString() {
+ if (!this.key.equals(this.libelle)) {
+ return this.libelle.concat(" (").concat(this.key).concat(")");
+ } else {
+ return this.libelle;
+ }
+ }
+ }
}
import org.apache.log4j.Logger;
-import fr.gouv.finances.dgfip.utils.Pair;
import fr.gouv.finances.cp.utils.StartUrl;
+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.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.common.config.ElementModel;
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
+ *
+ * @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+1]:"");
- }
- }
- @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;
- }
+ private static Logger logger = Logger.getLogger(DlgSearchConfig.class);
+
+ //
+ private File _f = null;
+
+ private DlgSearchConfig _sc = null;
+
+ // la liste des documents
+ private final 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 final XemeliosUser user;
+
+ /** Creates new form SearchConfigs */
+ public DlgSearchConfig(final JFrame parent, final DocumentsModel dm, final int mode, final XemeliosUser user) {
+ super(parent, true);
+ this._sc = this;
+ this.user = user;
+ this.docModels = dm;
+ this.setMode(mode);
+ // logger.debug("mode is "+mode);
+ this.initComponents();
+
+ }
+
+ private void activateSupModButtons(final boolean active) {
+ this.bSupprimer.setEnabled(active);
+ this.bChanger.setEnabled(active);
+ }
+
+ private void activateNewRechButton(final boolean active) {
+ this.bNouveau.setEnabled(active);
+ this.bRechercher.setEnabled(active);
+ }
+
+ private void shouldActivateNewRech() {
+ if (!((Pair) this.cbEtat.getSelectedItem()).key.equals("RIEN")) {
+ this.activateNewRechButton(true);
+ } else {
+ this.activateNewRechButton(false);
+ }
+ }
+
+ /**
+ * This method is called from within the constructor to initialize the form.
+ */
+ private void initComponents() {
+ this.jPanel1 = new javax.swing.JPanel();
+ this.jLabel2 = new javax.swing.JLabel();
+ this.cbDoc = new javax.swing.JComboBox();
+ this.jLabel3 = new javax.swing.JLabel();
+ this.cbEtat = new javax.swing.JComboBox();
+ this.bRechercher = new javax.swing.JButton();
+ this.jPanel2 = new javax.swing.JPanel();
+ this.jScrollPane2 = new javax.swing.JScrollPane();
+ this.jTable1 = new javax.swing.JTable();
+ this.bNouveau = new javax.swing.JButton();
+ this.bChanger = new javax.swing.JButton();
+ this.bSupprimer = new javax.swing.JButton();
+ this.bExecuter = new javax.swing.JButton();
+ this.bFermer = new javax.swing.JButton();
+
+ this.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+
+ this.jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Recherche"));
+ this.jLabel2.setText("Document");
+
+ final Vector<Pair> cbDocItems = this.getDocsIds();
+ this.cbDoc.setModel(new javax.swing.DefaultComboBoxModel(cbDocItems));
+ this.cbDoc.setSelectedIndex(0);
+ this.cbDoc.setBorder(javax.swing.BorderFactory.createEtchedBorder());
+ this.cbDoc.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ final JComboBox cb = (JComboBox) e.getSource();
+ final String petName = ((Pair) cb.getSelectedItem()).key;
+ DlgSearchConfig.this.updateEtats(petName);
+ // activateNewRechButton(false);
+ DlgSearchConfig.this.shouldActivateNewRech();
+ DlgSearchConfig.this.activateSupModButtons(false);
+ }
+ });
+
+ this.jLabel3.setText("Etat");
+
+ this.cbEtat.setBorder(javax.swing.BorderFactory.createEtchedBorder());
+ this.cbEtat.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ DlgSearchConfig.this.shouldActivateNewRech();
+ }
+ });
+
+ this.bRechercher.setText("Rechercher");
+ this.bRechercher.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgSearchConfig.this.bRechercherActionPerformed(evt);
+ }
+ });
+
+ final org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(this.jPanel1);
+ this.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(this.jLabel2).add(this.jLabel3))
+ .add(39, 39, 39)
+ .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(this.cbDoc, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 356, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
+ .add(jPanel1Layout.createSequentialGroup().add(this.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(this.bRechercher)))
+ .addContainerGap()));
+ jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(
+ jPanel1Layout.createSequentialGroup().addContainerGap().add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE).add(this.jLabel2).add(this.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(this.cbEtat, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 24, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE).add(this.jLabel3).add(this.bRechercher))
+ .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
+
+ this.jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Configurations"));
+ this.jScrollPane2.setViewportView(this.jTable1);
+
+ this.jTable1.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(final MouseEvent e) {
+ if (e.getClickCount() == 2) {
+ if (DlgSearchConfig.this.mode != EXEC_FROM_CONF) {
+ DlgSearchConfig.this.bExecuterActionPerformed(null);
+ } else {
+ DlgSearchConfig.this.bChangerActionPerformed(null);
+ }
+ }
+ }
+ });
+ this.jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
+ this.jTable1.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
+ @Override
+ public void valueChanged(final ListSelectionEvent e) {
+ if (DlgSearchConfig.this.jTable1.getSelectedRow() >= 0) {
+ DlgSearchConfig.this.bSupprimer.setEnabled(true);
+ DlgSearchConfig.this.bChanger.setEnabled(true);
+ if (DlgSearchConfig.this.getMode() != EXEC_FROM_CONF) {
+ DlgSearchConfig.this.bExecuter.setEnabled(true);
+ }
+ } else {
+ DlgSearchConfig.this.bSupprimer.setEnabled(false);
+ DlgSearchConfig.this.bChanger.setEnabled(false);
+ DlgSearchConfig.this.bExecuter.setEnabled(false);
+ }
+ }
+ });
+
+ final org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(this.jPanel2);
+ this.jPanel2.setLayout(jPanel2Layout);
+ jPanel2Layout.setHorizontalGroup(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(org.jdesktop.layout.GroupLayout.TRAILING,
+ jPanel2Layout.createSequentialGroup().addContainerGap().add(this.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(this.jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 327, Short.MAX_VALUE).addContainerGap()));
+
+ this.bNouveau.setText("Nouveau");
+ this.bNouveau.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgSearchConfig.this.bNouveauActionPerformed(evt);
+ }
+ });
+
+ this.bChanger.setText("Modifier");
+ this.bChanger.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgSearchConfig.this.bChangerActionPerformed(evt);
+ }
+ });
+
+ this.bSupprimer.setText("Supprimer");
+ this.bSupprimer.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgSearchConfig.this.bSupprimerActionPerformed(evt);
+ }
+ });
+ this.bExecuter.setText("Exécuter");
+ this.bExecuter.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgSearchConfig.this.bExecuterActionPerformed(evt);
+ }
+ });
+ this.bFermer.setText("Fermer");
+ this.bFermer.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgSearchConfig.this.bFermerActionPerformed(evt);
+ }
+ });
+
+ final org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this.getContentPane());
+ this.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, this.jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.LEADING, this.jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .add(layout.createSequentialGroup().add(this.bExecuter).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.bSupprimer).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.bChanger).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(this.bNouveau).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 50, Short.MAX_VALUE).add(this.bFermer))).addContainerGap()));
+ layout.setVerticalGroup(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(
+ layout.createSequentialGroup().add(this.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(this.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(this.bNouveau).add(this.bChanger).add(this.bSupprimer).add(this.bExecuter).add(this.bFermer)).addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
+ this.setTitle("Liste des configurations d'export");
+ this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
+ this.pack();
+ this.setLocationRelativeTo(this.getParent());
+
+ // désactivation de certains boutons
+ this.activateNewRechButton(false);
+ this.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) {
+ final String petName = ((Pair) this.cbDoc.getSelectedItem()).key;
+ this.updateEtats(petName);
+
+ }
+ this.setGlassPane(this.interruptible = new InterruptibleInfiniteGlassPane());
+ this.bExecuter.setEnabled(false);
+ }
+
+ private void bSupprimerActionPerformed(final 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(this.jTable1.getSelectedRow()), this.user);
+ this.bRechercherActionPerformed(null);
+ } catch (final Exception e) {
+ logger.error("Erreur lors de la suppression d'une configuration", e);
+ }
+ }
+
+ private void bFermerActionPerformed(final java.awt.event.ActionEvent evt) {
+ this.dispose();
+ }
+
+ private void bExecuterActionPerformed(final java.awt.event.ActionEvent evt) {
+ if (this.mode == EXEC_FROM_CONF) {
+ return;
+ }
+ if (this.jTable1.getSelectedRow() < 0) {
+ return;
+ }
+ final JFileChooser fc = new JFileChooser();
+ fc.setFileFilter(new FileFilter() {
+ @Override
+ public boolean accept(final File f) {
+ return f.isDirectory() || f.getName().toUpperCase().endsWith(".XLS");
+ }
+
+ @Override
+ public String getDescription() {
+ return "Fichier Excel";
+ }
+ });
+ if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
+ this._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 = this._f.getAbsolutePath();
+ final int len = fileName.length();
+ if (fileName.substring(len - 4).indexOf('.') < 0) {
+ fileName = fileName + ".xls";
+ this._f = new File(fileName);
+ }
+ if (this._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 (this.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() {
+ final String etatKey = ((Pair) DlgSearchConfig.this.cbEtat.getSelectedItem()).key;
+ final Exporter ex = new Exporter(DlgSearchConfig.this._f, DlgSearchConfig.this.ertm.getResultSet(), DlgSearchConfig.this.dm, etatKey, DlgSearchConfig.this.em, DlgSearchConfig.this.listeConfigs.get(DlgSearchConfig.this.jTable1.getSelectedRow()), MainWindow.getInstance()
+ .getEnvProperties());
+ ex.setParentFrame(DlgSearchConfig.this._sc);
+ DlgSearchConfig.this.interruptible.setThreadToInterrupt(ex);
+ DlgSearchConfig.this.getGlassPane().setVisible(true);
+ ex.execute();
+ }
+ });
+ } catch (final Exception e) {
+ logger.error(e);
+ }
+ } else {
+ try {
+ SwingUtilities.invokeLater(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ final String docKey = ((Pair) DlgSearchConfig.this.cbDoc.getSelectedItem()).key;
+ final String etatKey = ((Pair) DlgSearchConfig.this.cbEtat.getSelectedItem()).key;
+ DlgSearchConfig.this.em = (DlgSearchConfig.this.docModels.getDocumentById(docKey)).getEtatById(etatKey).getImportableElement();
+
+ /**
+ * CREATION de la requête en fonction de ce que l'on exporte
+ */
+
+ final DataResultSet drs = DataLayerManager.getImplementation().getDataResultSetForExport(DlgSearchConfig.this.whatToExport, DlgSearchConfig.this.em, DlgSearchConfig.this.coll, DlgSearchConfig.this.budg, DlgSearchConfig.this.fic, DlgSearchConfig.this.SK1,
+ DlgSearchConfig.this.SK2, DlgSearchConfig.this.user);
+ final Exporter ex = new Exporter(DlgSearchConfig.this._f, drs, DlgSearchConfig.this.dm, etatKey, DlgSearchConfig.this.em, DlgSearchConfig.this.listeConfigs.get(DlgSearchConfig.this.jTable1.getSelectedRow()), MainWindow.getInstance().getEnvProperties());
+ ex.setParentFrame(DlgSearchConfig.this._sc);
+ DlgSearchConfig.this.interruptible.setThreadToInterrupt(ex);
+ DlgSearchConfig.this.getGlassPane().setVisible(true);
+ ex.execute();
+ } catch (final UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(DlgSearchConfig.this.getParent(), ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (final DataConfigurationException dae) {
+ logger.error("", dae);
+ } catch (final SQLException sqle) {
+ logger.error("", sqle);
+ }
+ }
+ });
+ } catch (final Exception e) {
+ logger.error(e);
+ }
+ }
+ }
+ }
+
+ public void showXLS() {
+ try {
+ this.getGlassPane().setVisible(false);
+ this.setVisible(false);
+ StartUrl.startUrl(this._f.toURI().toURL().toExternalForm());
+ } catch (final Throwable t) {
+ }
+ }
+
+ public void bRechercherActionPerformed(final java.awt.event.ActionEvent evt) {
+ this.jTable1.removeAll();
+ try {
+ final String docKey = ((Pair) this.cbDoc.getSelectedItem()).key;
+ final String etatKey = ((Pair) this.cbEtat.getSelectedItem()).key;
+ if (!"RIEN".equals(docKey) && !"RIEN".equals(etatKey)) {
+ this.listeConfigs = DataLayerManager.getImplementation().getListeConfigsExport(docKey, etatKey, this.user);
+ this.jTable1.setModel(new ConfigTableModel(this.listeConfigs));
+ }
+ } catch (final Throwable t) {
+ }
+
+ }
+
+ private void bChangerActionPerformed(final java.awt.event.ActionEvent evt) {
+ final String docKey = ((Pair) this.cbDoc.getSelectedItem()).key;
+ final String etatKey = ((Pair) this.cbEtat.getSelectedItem()).key;
+ final DocumentModel dm2 = this.docModels.getDocumentById(docKey);
+ final EditConfig ec = new EditConfig(this, dm2, this.listeConfigs.get(this.jTable1.getSelectedRow()), this.user);
+ ec.setVisible(true);
+ }
+
+ private void bNouveauActionPerformed(final java.awt.event.ActionEvent evt) {
+ final String docKey = ((Pair) this.cbDoc.getSelectedItem()).key;
+ final String etatKey = ((Pair) this.cbEtat.getSelectedItem()).key;
+ final DocumentModel dm2 = this.docModels.getDocumentById(docKey);
+ final EditConfig ec = new EditConfig(this, dm2, etatKey, this.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() {
+ final Vector<Pair> ret = new Vector<Pair>();
+ if (this.docModels.getDocuments().size() > 1) {
+ ret.add(new Pair("RIEN", "Sélectionnez un document"));
+ }
+ for (final DocumentModel dm2 : this.docModels.getDocuments()) {
+ // si le doc a au moins un etat exportable
+ for (final 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(final String docID) {
+ final Vector<Pair> ret = new Vector<Pair>();
+ if (this.docModels.getDocumentById(docID).getEtats().size() > 1) {
+ ret.add(new Pair("RIEN", "Sélectionnez un état"));
+ }
+ for (final EtatModel em2 : this.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(final String docID) {
+ if (!"RIEN".equals(docID)) {
+ final Vector<Pair> cbEtatIds = this.getEtatsIds(docID);
+ this.cbEtat.setModel(new DefaultComboBoxModel(cbEtatIds));
+ if (cbEtatIds.size() == 1) {
+ this.cbEtat.setSelectedIndex(0);
+ this.bRechercherActionPerformed(null);
+ this.activateNewRechButton(true);
+ }
+ } else {
+ this.cbEtat.setModel(new DefaultComboBoxModel());
+ }
+ }
+
+ private class ConfigTableModel extends AbstractTableModel {
+ private final String[] columnNames = new String[] { /* "Code", */"Libellé", "Créateur", "Date création" };
+ private final Vector<String[]> data = new Vector<String[]>();
+
+ public ConfigTableModel(final Vector<ConfigModel> d) {
+ final int row = 0;
+ int column = 0;
+ for (final ConfigModel cm : d) {
+ column = 0;
+ final String[] tmp = new String[4];
+ tmp[column++] = cm.getCode();
+ tmp[column++] = cm.getLibelle();
+ tmp[column++] = cm.getOwner();
+ tmp[column++] = cm.getDateCreation();
+ this.data.add(tmp);
+ }
+ }
+
+ @Override
+ public String getColumnName(final int column) {
+ return this.columnNames[column];
+ }
+
+ @Override
+ public boolean isCellEditable(final int rowIndex, final int columnIndex) {
+ return false;
+ }
+
+ @Override
+ public int getColumnCount() {
+ return this.columnNames.length;
+ }
+
+ @Override
+ public int getRowCount() {
+ return (this.data != null ? this.data.size() : 0);
+ }
+
+ @Override
+ public Object getValueAt(final int rowIndex, final int columnIndex) {
+ return (this.data != null ? this.data.get(rowIndex)[columnIndex + 1] : "");
+ }
+ }
+
+ @Override
+ protected JRootPane createRootPane() {
+ final KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
+ final JRootPane rp = new JRootPane();
+ this.escapeAction = new AbstractAction("Fermer") {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ DlgSearchConfig.this.setVisible(false);
+ }
+ };
+ rp.registerKeyboardAction(this.escapeAction, "TOTOTOTO", ks, JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
+ }
+
+ public int getMode() {
+ return this.mode;
+ }
+
+ public void setMode(final int mode) {
+ this.mode = mode;
+ }
+
+ public ConfigModel getConfigSelected() {
+ return this.listeConfigs.get(this.jTable1.getSelectedRow());
+ }
+
+ public EtatResultTableModel getErtm() {
+ return this.ertm;
+ }
+
+ public void setErtm(final EtatResultTableModel ertm) {
+ this.ertm = ertm;
+ }
+
+ public ElementModel getEm() {
+ return this.em;
+ }
+
+ public void setEm(final ElementModel em) {
+ this.em = em;
+ }
+
+ public DocumentModel getDm() {
+ return this.dm;
+ }
+
+ public void setDm(final DocumentModel dm) {
+ this.dm = dm;
+ }
+
+ /**
+ * teste si le documentModel contient au moins un étatModel exportable
+ */
+ public static boolean docHasEtatToExport(final DocumentsModel dms) {
+ if (dms.getDocuments().size() < 1) {
+ return false;
+ }
+
+ for (final DocumentModel dm : dms.getDocuments()) {
+ for (final EtatModel em : dm.getEtats()) {
+ if (em.isExportable()) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ public Pair getBudg() {
+ return this.budg;
+ }
+
+ public void setBudg(final Pair budg) {
+ this.budg = budg;
+ }
+
+ public Pair getColl() {
+ return this.coll;
+ }
+
+ public void setColl(final Pair coll) {
+ this.coll = coll;
+ }
+
+ public void setWhatToExport(final int whatToExport) {
+ this.whatToExport = whatToExport;
+ }
+
+ public void setFic(final String fic) {
+ this.fic = fic;
+ }
+
+ public Pair getSK1() {
+ return this.SK1;
+ }
+
+ public void setSK1(final Pair sk1) {
+ this.SK1 = sk1;
+ }
+
+ public Pair getSK2() {
+ return this.SK2;
+ }
+
+ public void setSK2(final Pair sk2) {
+ this.SK2 = sk2;
+ }
}
import java.awt.event.KeyEvent;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
+import java.io.OutputStreamWriter;
+import java.util.UUID;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
+import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import org.apache.log4j.Logger;
import org.jdesktop.swingx.JXTreeTable;
+import org.jdesktop.swingx.treetable.AbstractTreeTableModel;
import fr.gouv.finances.cp.utils.xml.marshal.XmlOutputter;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
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.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 java.util.UUID;
-import javax.swing.JOptionPane;
-import org.jdesktop.swingx.treetable.AbstractTreeTableModel;
/**
- *
- * @author nicolas.lecorre
+ *
+ * @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");
- jLabel1.setEnabled(false);
-
- jLabel2.setText("Libellé");
-
- tCode.setEnabled(false);
-
- 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(417, Short.MAX_VALUE)
- .add(bSelectAll)
- .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
- .add(bSelectNone))
- .add(jPanel2Layout.createSequentialGroup()
- .add(liste, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 659, 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
- if(tLibelle.getText()==null || tLibelle.getText().length()==0) {
- JOptionPane.showMessageDialog(this, "Le libellé de la configuration d'export est obligatoire");
- tLibelle.requestFocus();
- return;
- }
- boolean needInsert = false;
- if (cm == null) {
- cm = new ConfigModel(ConfigModel.QN);
- tCode.setText(UUID.randomUUID().toString());
- 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;
- }
+ private static final long serialVersionUID = 5669669876743219771L;
+ private static Logger logger = Logger.getLogger(EditConfig.class);
+ private final DocumentModel dm;
+ private ConfigModel cm;
+ private final 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 final XemeliosUser user;
+
+ /** Creates new form EditConfig */
+ public EditConfig(final JDialog parent, final DocumentModel d, final ConfigModel c, final XemeliosUser user) {
+ super(parent);
+ this.dm = d;
+ this.docID = this.dm.getId();
+ this.cm = c;
+ this.etatID = this.cm.getEtatID();
+ this.user = user;
+ try {
+ final ConfigParser cp = new ConfigParser();
+ cp.parse(new ByteArrayInputStream(c.getConfigLines()));
+ this.dataToBeModified = (ExportModel) cp.getMarshallable();
+ } catch (final Exception e) {
+ logger.error("Erreur lors de la lecture de la configuration à modifier", e);
+ }
+ this.initComponents();
+ this.tCode.setText(c.getCode());
+ this.tLibelle.setText(c.getLibelle());
+ this.setLocationRelativeTo(this.getParent());
+ this.treeTable.setTreeTableModel(this.createModel(this.dm, this.cm.getEtatID()));
+ this.updateModel();
+ this.treeTable.addTreeExpansionListener(new TreeExpansionListener() {
+
+ @Override
+ public void treeCollapsed(final TreeExpansionEvent event) {
+ }
+
+ @Override
+ public void treeExpanded(final TreeExpansionEvent event) {
+ EditConfig.this.treeTable.packAll();
+ }
+ });
+ this.treeTable.getColumnModel().getColumn(1).setMaxWidth(25);
+ this.treeTable.expandAll();
+ }
+
+ public EditConfig(final JDialog parent, final DocumentModel d, final String etatID, final XemeliosUser user) {
+ super(parent);
+ this.dm = d;
+ this.docID = this.dm.getId();
+ this.etatID = etatID;
+ this.user = user;
+ this.initComponents();
+ this.setLocationRelativeTo(this.getParent());
+ this.treeTable.setTreeTableModel(this.createModel(this.dm, etatID));
+ this.treeTable.addTreeExpansionListener(new TreeExpansionListener() {
+
+ @Override
+ public void treeCollapsed(final TreeExpansionEvent event) {
+ }
+
+ @Override
+ public void treeExpanded(final TreeExpansionEvent event) {
+ EditConfig.this.treeTable.packAll();
+ }
+ });
+ this.treeTable.getColumnModel().getColumn(1).setMaxWidth(25);
+ this.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 (this.dataToBeModified != null) {
+ for (final ExportElementModel eemDest : this.data.getEnfants()) {
+ final String eID = eemDest.getId();
+ for (final ExportElementModel eemRef : this.dataToBeModified.getEnfants()) {
+ if (eemRef.getId().equals(eID)) {
+ this.updateEEM(eemRef, eemDest);
+ }
+ }
+ }
+ }
+ }
+
+ private void updateEEM(final ExportElementModel reference, final ExportElementModel destination) {
+ for (final ExportChampModel ecmDest : destination.getChamps()) {
+ final String cID = ecmDest.getId();
+ for (final ExportChampModel ecmRef : reference.getChamps()) {
+ if (ecmRef.getId().equals(cID)) {
+ ecmDest.setSelectionne(ecmRef.isSelectionne());
+ }
+ }
+ }
+ for (final ExportElementModel eemDest : destination.getEnfants()) {
+ final String eID = eemDest.getId();
+ for (final ExportElementModel eemRef : reference.getEnfants()) {
+ if (eemRef.getId().equals(eID)) {
+ this.updateEEM(eemRef, eemDest);
+ }
+ }
+ }
+ }
+
+ private ConfigTreeTableModel createModel(final DocumentModel dm, final String etatID) {
+ final ConfigTreeTableModel ret = new ConfigTreeTableModel(this.data);
+ final EtatModel em = dm.getEtatById(etatID);
+ ElementModel emROOT = null;
+ for (final String k : em.getElements().keySet()) {
+ final 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 {
+ final ExportModel exm = new ExportModel(ExportModel.QN);
+ exm.setId((this.cm != null ? this.cm.getId() : ""));
+ exm.setCode((this.cm != null ? this.cm.getCode() : ""));
+ exm.setLibelle((this.cm != null ? this.cm.getLibelle() : ""));
+ // les champs de l'élément ROOT
+ final ExportElementModel eem = this.buildEEM(emROOT, null);
+ if (emROOT.getEnfant() != null) {
+ eem.setEnfants(this.readChildren(emROOT, em, eem));
+ // les fils
+ }
+ exm.addEnfant(eem);
+ this.data = exm;
+ ret.setData(exm);
+ } catch (final 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(final ElementModel p, final EtatModel em, final ExportElementModel parent) throws Exception {
+ final Vector<ExportElementModel> ret = new Vector<ExportElementModel>();
+ for (final String k : p.getEnfant().getEnfants().keySet()) {
+ final ElementModel child = em.getElementById(k);
+ final ExportElementModel eem = this.buildEEM(child, parent);
+ if (child.getEnfant() != null && child.getEnfant().getEnfants().size() > 0) {
+ eem.setEnfants(this.readChildren(child, em, eem));
+ }
+ ret.add(eem);
+ }
+ return ret;
+ }
+
+ private ExportElementModel buildEEM(final ElementModel em, final ExportElementModel parent) throws Exception {
+ final 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 (this.dataToBeModified != null) {
+ eemRef = this.findCorrespondingEEM(ret, this.dataToBeModified.getEnfants());
+ }
+
+ // champs de l'élément ROOT
+ for (final ChampModel tmpC : em.getListeResultat().getListeChamps()) {
+ if (tmpC.isExportable()) {
+ final 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) {
+ final ExportChampModel ecmRef = this.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(final ExportChampModel ecm, final ExportElementModel eem) {
+ for (final ExportChampModel e : eem.getChamps()) {
+ if (e.getId().equals(ecm.getId())) {
+ return ecm;
+ }
+ }
+ return null;
+ }
+
+ private ExportElementModel findCorrespondingEEM(final ExportElementModel eem, final Vector<ExportElementModel> liste) {
+ ExportElementModel ret = null;
+ for (final ExportElementModel e : liste) {
+ if (e.getId().equals(eem.getId())) {
+ ret = e;
+ break;
+ } else if (e.getEnfants().size() > 0) {
+ ret = this.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() {
+
+ this.jPanel1 = new javax.swing.JPanel();
+ this.jLabel1 = new javax.swing.JLabel();
+ this.jLabel2 = new javax.swing.JLabel();
+ this.tCode = new javax.swing.JTextField();
+ this.tLibelle = new javax.swing.JTextField();
+ this.jPanel2 = new javax.swing.JPanel();
+ this.bSelectNone = new javax.swing.JButton();
+ this.bSelectAll = new javax.swing.JButton();
+ this.liste = new javax.swing.JScrollPane();
+ this.treeTable = new JXTreeTablePropertyEditor();
+ this.bEnregistrer = new javax.swing.JButton();
+ this.bAnnuler = new javax.swing.JButton();
+
+ this.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+ this.setTitle("Configuration d'export");
+
+ this.jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Identification"));
+
+ this.jLabel1.setText("Code");
+ this.jLabel1.setEnabled(false);
+
+ this.jLabel2.setText("Libellé");
+
+ this.tCode.setEnabled(false);
+
+ final org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(this.jPanel1);
+ this.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(this.jLabel1).add(this.jLabel2)).add(26, 26, 26)
+ .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(this.tLibelle, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 581, Short.MAX_VALUE).add(this.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(this.jLabel1).add(this.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(this.tLibelle, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE).add(this.jLabel2))
+ .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
+
+ this.jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Configuration"));
+
+ this.bSelectNone.setText("Tout désélectionner");
+ this.bSelectNone.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ EditConfig.this.bSelectNoneActionPerformed(evt);
+ }
+ });
+
+ this.bSelectAll.setText("Tout sélectionner");
+ this.bSelectAll.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ EditConfig.this.bSelectAllActionPerformed(evt);
+ }
+ });
+
+ this.treeTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_LAST_COLUMN);
+ this.liste.setViewportView(this.treeTable);
+
+ final org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(this.jPanel2);
+ this.jPanel2.setLayout(jPanel2Layout);
+ jPanel2Layout.setHorizontalGroup(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2Layout.createSequentialGroup().addContainerGap(417, Short.MAX_VALUE).add(this.bSelectAll).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.bSelectNone))
+ .add(jPanel2Layout.createSequentialGroup().add(this.liste, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 659, 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(this.bSelectNone).add(this.bSelectAll)).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 12, Short.MAX_VALUE)
+ .add(this.liste, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE).addContainerGap()));
+
+ this.bEnregistrer.setText("Enregistrer");
+ this.bEnregistrer.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ EditConfig.this.bEnregistrerActionPerformed(evt);
+ }
+ });
+
+ this.bAnnuler.setText("Annuler");
+ this.bAnnuler.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ EditConfig.this.bAnnulerActionPerformed(evt);
+ }
+ });
+
+ final org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this.getContentPane());
+ this.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(this.jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .add(this.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(this.bAnnuler).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.bEnregistrer))).addContainerGap()));
+ layout.setVerticalGroup(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(
+ layout.createSequentialGroup().add(this.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(this.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(this.bEnregistrer).add(this.bAnnuler)).addContainerGap()));
+
+ this.pack();
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void bEnregistrerActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_bEnregistrerActionPerformed
+ if (this.tLibelle.getText() == null || this.tLibelle.getText().length() == 0) {
+ JOptionPane.showMessageDialog(this, "Le libellé de la configuration d'export est obligatoire");
+ this.tLibelle.requestFocus();
+ return;
+ }
+ boolean needInsert = false;
+ if (this.cm == null) {
+ this.cm = new ConfigModel(ConfigModel.QN);
+ this.tCode.setText(UUID.randomUUID().toString());
+ needInsert = true;
+ }
+ try {
+ this.cm.setCode(this.tCode.getText());
+ this.cm.setLibelle(this.tLibelle.getText());
+ this.data.setId(this.cm.getCode());
+ this.data.setLibelle(this.cm.getLibelle());
+ this.cm.setDocID(this.docID);
+ this.cm.setEtatID(this.etatID);
+ this.cm.setOwner(MainWindow.getInstance().getConnectedUser().getId());
+ this.ensureKeysSelected();
+ final ByteArrayOutputStream sos = new ByteArrayOutputStream();
+ final OutputStreamWriter os = new OutputStreamWriter(sos, "ISO-8859-1");
+ final XmlOutputter xo = new XmlOutputter(os, "ISO-8859-1");
+ this.data.marshall(xo);
+ os.flush();
+ this.cm.setConfigLines(sos.toByteArray());
+ if (needInsert) {
+ DataLayerManager.getImplementation().insertConfigExport(this.cm, this.user);
+ } else {
+ DataLayerManager.getImplementation().updateConfigExport(this.cm, this.user);
+ }
+ ((DlgSearchConfig) this.getParent()).bRechercherActionPerformed(null);
+ } catch (final 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
+ final Vector<ExportElementModel> toSelect = new Vector<ExportElementModel>();
+ for (final ExportElementModel ecm : this.data.getEnfants()) {
+ this.browseChildrenToSelect(ecm, toSelect);
+ }
+
+ // sélection de la clef de chaque élément identifié
+ for (final ExportElementModel e : toSelect) {
+ e.selectChampsKey();
+ e.selectParentChampsKey();
+ }
+
+ }
+
+ private void browseChildrenToSelect(final ExportElementModel parent, final Vector<ExportElementModel> toSelect) {
+ if (parent.hasChampSelected()) {
+ toSelect.add(parent);
+ }
+
+ for (final ExportElementModel ecm : parent.getEnfants()) {
+ this.browseChildrenToSelect(ecm, toSelect);
+ }
+
+ }
+
+ private void bAnnulerActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_bAnnulerActionPerformed
+ this.dispose();
+ }// GEN-LAST:event_bAnnulerActionPerformed
+
+ private void bSelectNoneActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_bSelectNoneActionPerformed
+ this.toggleAll(false);
+ this.treeTable.repaint();
+ }// GEN-LAST:event_bSelectNoneActionPerformed
+
+ private void bSelectAllActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_bSelectAllActionPerformed
+ this.toggleAll(true);
+ this.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(final boolean select) {
+ for (final ExportElementModel eem : this.data.getEnfants()) {
+ this.toggle(eem, select);
+ }
+
+ }
+
+ private void toggle(final ExportElementModel e, final boolean select) {
+ for (final ExportChampModel ecm : e.getChamps()) {
+ ecm.setSelectionne(select);
+ }
+
+ for (final ExportElementModel eem : e.getEnfants()) {
+ this.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();
+ this.booleanRenderer = new DefaultTableCellRenderer() {
+
+ private final JCheckBox chk = new JCheckBox();
+
+ @Override
+ public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) {
+ final JLabel lbl = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
+ this.chk.setSelected(((Boolean) value).booleanValue());
+ this.chk.setBackground(lbl.getBackground());
+ this.chk.setBorder(lbl.getBorder());
+ return this.chk;
+ }
+ };
+ this.booleanDisabledRenderer = new DefaultTableCellRenderer() {
+
+ private final JCheckBox chk = new JCheckBox();
+
+ @Override
+ public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) {
+ final JLabel lbl = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
+ this.chk.setSelected(((Boolean) value).booleanValue());
+ this.chk.setBackground(lbl.getBackground());
+ this.chk.setBorder(lbl.getBorder());
+ this.chk.setEnabled(false);
+ return this.chk;
+ }
+ };
+ this.blankRenderer = new DefaultTableCellRenderer() {
+
+ @Override
+ public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) {
+ final JLabel lbl = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
+ lbl.setText("");
+ return lbl;
+ }
+ };
+ }
+
+ @Override
+ public TableCellRenderer getCellRenderer(final int row, final int column) {
+ if (column == 1 && this.getTreeTableModel() instanceof ConfigTreeTableModel) {
+ final ConfigTreeTableModel model = (ConfigTreeTableModel) this.getTreeTableModel();
+ final Object node = this.getPathForRow(row).getLastPathComponent();
+ if (node instanceof ExportChampModel) {
+ // ExportChampModel ecm = (ExportChampModel)node;
+ // if(!ecm.isEditable()) {
+ // return booleanDisabledRenderer;
+ // } else {
+ return this.booleanRenderer;
+ // }
+ } else if (node instanceof ExportElementModel) {
+ return this.blankRenderer;
+ }
+ return super.getCellRenderer(row, column);
+ } else {
+ return super.getCellRenderer(row, column);
+ }
+ }
+ }
+
+ private static class ConfigTreeTableModel extends AbstractTreeTableModel {
+
+ private final String[] columnNames = new String[] { "", "" };
+ private ExportModel _data;
+
+ public ConfigTreeTableModel(final ExportModel data) {
+ this._data = data;
+ }
+
+ @Override
+ public boolean isLeaf(final 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(final 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(final Object object, final 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(final Object value, final Object node, final int column) {
+ final ExportChampModel ecm = (ExportChampModel) node;
+ if (column == 1) {
+ ecm.setSelectionne((Boolean) value);
+ }
+ }
+
+ @Override
+ public int getChildCount(final Object parent) {
+ if (parent instanceof ExportElementModel) {
+ final 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(final Object parent, final int index) {
+ if (parent instanceof ExportElementModel) {
+ final 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(final Object object, final int i) {
+ if (object instanceof ExportChampModel) {
+ return true;
+ }// (i==1 && ((ExportChampModel)object).isEditable());
+ else {
+ return false;
+ }
+ }
+
+ @Override
+ public int getIndexOfChild(final Object parent, final Object child) {
+ if (parent instanceof ExportElementModel) {
+ final ExportElementModel p = (ExportElementModel) parent;
+ if (child instanceof ExportChampModel) {
+ final ExportChampModel c = (ExportChampModel) child;
+ int i = 0;
+ for (; i < p.getChamps().size(); i++) {
+ final ExportChampModel t = p.getChamps().get(i);
+ if (t.getId().equals(c.getId())) {
+ return i;
+ }
+ }
+ } else {
+ final ExportElementModel c = (ExportElementModel) child;
+ int i = 0;
+ for (; i < p.getEnfants().size(); i++) {
+ final ExportElementModel t = p.getEnfants().get(i);
+ if (t.getId().equals(c.getId())) {
+ return (i + p.getChamps().size());
+ }
+ }
+ }
+ }
+ return -1;
+ }
+
+ @Override
+ public Object getRoot() {
+ return this._data.getEnfants().get(0);
+ }
+
+ @Override
+ public int getColumnCount() {
+ return this.columnNames.length;
+ }
+
+ public int getRowCount2() {
+ int ret = this.getChampsCount(this._data);
+ if (this._data.getEnfants().size() > 0) {
+ ret += this.getChildsCount(this._data);
+ }
+ return ret;
+ }
+
+ public int getChampsCount(final Object parent) {
+ return ((ExportElementModel) parent).getChamps().size();
+ }
+
+ public int getChildsCount(final Object parent) {
+ int ret = this.getChampsCount(parent);
+ for (final ExportElementModel eem : ((ExportElementModel) parent).getEnfants()) {
+ ret += this.getChildsCount(eem);
+ }
+ return ret;
+ }
+
+ @Override
+ public String getColumnName(final int arg0) {
+ return this.columnNames[arg0];
+ }
+
+ public ExportModel getData() {
+ return this._data;
+ }
+
+ public void setData(final ExportModel data) {
+ this._data = data;
+ }
+ }
+
+ @Override
+ protected JRootPane createRootPane() {
+ final KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
+ final JRootPane rp = new JRootPane();
+ this.escapeAction = new AbstractAction("Fermer") {
+
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ EditConfig.this.setVisible(false);
+ }
+ };
+ rp.registerKeyboardAction(this.escapeAction, "TOTOTOTO", ks, JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
+ }
}
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.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;
+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;
+
/**
- *
+ *
* @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;
- }
-
- }
+ 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 {
+ this.loadInstalled();
+ // profils = ProfilsModel.loadModel(MainWindow.getInstance().getEnvProperties().getProperty(Constants.SYS_PROP_MAJ_PROFILS_URL),
+ // PnlFirstConfigProxy.client);
+ this.tm = new ProfilsTableModel(null, this.im);
+ } catch (final Exception ex) {
+ logger.error("<init>", ex);
+ }
+ this.initComponents();
+ this.tblProfils.setDefaultRenderer(String.class, new DescCellRenderer(this.tm));
+ this.loadProfils();
+ }
+
+ public void testProfilsLoaded() {
+ if (!this.profilsLoaded) {
+ this.loadProfils();
+ }
+ }
+
+ private void loadProfils() {
+ final Runnable runner = new Runnable() {
+ @Override
+ public void run() {
+ PnlFirstAbo.this.setBusy(true);
+ try {
+ PnlFirstAbo.this.profils = ProfilsModel.loadModel(MainWindow.getInstance().getEnvProperties().getProperty(Constants.SYS_PROP_MAJ_PROFILS_URL), PnlFirstConfigProxy.client);
+ PnlFirstAbo.this.tm.profils = PnlFirstAbo.this.profils.getProfils();
+ PnlFirstAbo.this.tm.fireTableDataChanged();
+ PnlFirstAbo.this.profilsLoaded = true;
+ } catch (final 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 {
+ PnlFirstAbo.this.setBusy(false);
+ }
+ }
+ };
+ SwingUtilities.invokeLater(runner);
+ }
+
+ public static String getDescription() {
+ return "Configuration de l'usage de Xemelios";
+ }
+
+ private void loadInstalled() throws Exception {
+ this.im = InstalledModel.readFromFile(MainWindow.getInstance().getEnvProperties().getProperty(Constants.SYS_PROP_INSTALLED_FILENAME));
+ this.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() {
+
+ this.jLabel1 = new javax.swing.JLabel();
+ this.jScrollPane1 = new javax.swing.JScrollPane();
+ this.tblProfils = new javax.swing.JTable();
+ this.jLabel2 = new javax.swing.JLabel();
+
+ this.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>");
+
+ this.tblProfils.setModel(this.tm);
+ this.jScrollPane1.setViewportView(this.tblProfils);
+
+ this.jLabel2.setText("Liste des profils");
+
+ final 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(this.jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)
+ .addComponent(this.jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE).addComponent(this.jLabel2, javax.swing.GroupLayout.Alignment.LEADING)).addContainerGap()));
+ layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
+ layout.createSequentialGroup().addContainerGap().addComponent(this.jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(this.jLabel2).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(this.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 final InstalledModel im;
+ private ArrayList<ProfilModel> profils;
+
+ @Override
+ public void setValueAt(final Object aValue, final int rowIndex, final int columnIndex) {
+ // super.setValueAt(aValue, rowIndex, columnIndex);
+ // logger.debug("rowIndex=" + rowIndex + "/columnIndex=" + columnIndex + "/aValue=" + aValue.toString());
+ switch (columnIndex) {
+ case 0:
+ final ProfilModel pm = this.profils.get(rowIndex);
+ final int idxFound = this.im.getProfilIdx(pm.getId());
+ if (idxFound != InstalledModel.NOT_FOUND) { // profil trouvé
+ if (aValue.equals(false)) { // case doit être décochée
+ this.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
+ final ProfilModel npm = new ProfilModel(pm.getId(), pm.getDescription());
+ this.im.getProfils().add(npm); // on ajoute le profil à la liste des profils installés
+ }
+ }
+ for (final ProfilModel pml : this.im.getProfils()) {
+ logger.debug("p id=" + pml.getId() + " / desc=" + pml.getDescription());
+ }
+ break;
+ default:
+ break;
+ }
+ }
+
+ @Override
+ public void fireTableCellUpdated(final int row, final int column) {
+ super.fireTableCellUpdated(row, column);
+ }
+
+ public ProfilsTableModel(final ArrayList<ProfilModel> profils, final InstalledModel im) {
+ super();
+ this.profils = profils;
+ this.im = im;
+ }
+
+ @Override
+ public int getRowCount() {
+ if (this.profils != null) {
+ return this.profils.size();
+ } else {
+ return 0;
+ }
+ }
+
+ @Override
+ public int getColumnCount() {
+ return 2;
+ }
+
+ @Override
+ public Object getValueAt(final int rowIndex, final int columnIndex) {
+ final ProfilModel pm = this.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 (this.im == null) {
+ return false; // pas d'entrée profil dans installed.xml
+ } else {
+ for (final ProfilModel ipm : this.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(final int rowIndex, final int columnIndex) {
+ switch (columnIndex) {
+ case 0:
+ // profil obligatoire, donc la selection n'est pas modifiable
+ if (this.profils.get(rowIndex).isRequired()) {
+ return false;
+ } else {
+ return true;
+ }
+ case 1:
+ return false;
+ default:
+ return false;
+ }
+ }
+
+ @Override
+ public Class<?> getColumnClass(final int columnIndex) {
+ switch (columnIndex) {
+ case 0:
+ return Boolean.class;
+ case 1:
+ return String.class;
+ default:
+ return super.getColumnClass(columnIndex);
+ }
+ }
+
+ @Override
+ public String getColumnName(final int column) {
+ switch (column) {
+ case 0:
+ return "abonnement";
+ case 1:
+ return "description";
+ default:
+ return "unknow column";
+ }
+ }
+
+ @Override
+ public void tableChanged(final TableModelEvent e) {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ ArrayList<ProfilModel> getProfils() {
+ return this.profils;
+ }
+
+ }
+
+ @Override
+ public WizardPanelNavResult allowNext(final String stepName, final Map settings, final Wizard wizard) {
+ try {
+ this.setBusy(true);
+ this.im.saveInstalledModel();
+ } catch (final Exception ex) {
+ logger.error("writing installed-components.xml", ex);
+ } finally {
+ this.setBusy(false);
+ }
+ return WizardPanelNavResult.PROCEED;
+ }
+
+ @Override
+ public WizardPanelNavResult allowFinish(final String stepName, final Map settings, final Wizard wizard) {
+ return this.allowNext(stepName, settings, wizard);
+ }
+
+ private class DescCellRenderer extends DefaultTableCellRenderer {
+ private final ProfilsTableModel model;
+
+ public DescCellRenderer(final ProfilsTableModel model) {
+ super();
+ this.model = model;
+ }
+
+ @Override
+ public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) {
+ final Component parentComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
+ final Component renderer = parentComponent;
+ if (column == 1) {
+ final ProfilModel pm = this.model.getProfils().get(row);
+ if (pm.isRequired()) {
+ final Font oldFont = renderer.getFont();
+ final Font newFont = oldFont.deriveFont(Font.ITALIC | Font.BOLD); // oldFont.getStyle() |
+ renderer.setFont(newFont);
+ }
+
+ }
+ return renderer;
+ }
+
+ }
}
*
*/
-
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.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
+ 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 final ButtonGroup bgInTresor;
+ static HttpClient client;
+
+ /** Creates new form PnlFirstConfigProxy */
+ public PnlFirstConfigProxy() {
+ this.initComponents();
+ this.bgInTresor = new ButtonGroup();
+ this.bgInTresor.add(this.rbInTresor);
+ this.bgInTresor.add(this.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() {
+
+ this.cbxUseProxy = new javax.swing.JCheckBox();
+ this.jLabel1 = new javax.swing.JLabel();
+ this.rbInTresor = new javax.swing.JRadioButton();
+ this.rbOutTresor = new javax.swing.JRadioButton();
+ this.jLabel2 = new javax.swing.JLabel();
+ this.dfProxyServer = new javax.swing.JTextField();
+ this.jLabel3 = new javax.swing.JLabel();
+ this.dfProxyPort = new javax.swing.JTextField();
+ this.chkAuthenticationRequired = new javax.swing.JCheckBox();
+ this.lblUser = new javax.swing.JLabel();
+ this.dfProxyUser = new javax.swing.JTextField();
+ this.dfProxyPassword = new javax.swing.JPasswordField();
+ this.lblPassword = new javax.swing.JLabel();
+ this.lblDomain = new javax.swing.JLabel();
+ this.dfDomainName = new javax.swing.JTextField();
+ this.pbTest = new javax.swing.JButton();
+
+ this.cbxUseProxy.setText("J'utilise un proxy pour accéder à internet*");
+ this.cbxUseProxy.setEnabled(false);
+ this.cbxUseProxy.setName("is.use.proxy"); // NOI18N
+ this.cbxUseProxy.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PnlFirstConfigProxy.this.cbxUseProxyActionPerformed(evt);
+ }
+ });
+
+ this.jLabel1.setText(AVAILABILITY);
+
+ this.rbInTresor.setSelected(true);
+ this.rbInTresor.setText("Je fais partie du réseau du trésor");
+ this.rbInTresor.setName("in.tresor"); // NOI18N
+ this.rbInTresor.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PnlFirstConfigProxy.this.rbInTresorActionPerformed(evt);
+ }
+ });
+
+ this.rbOutTresor.setText("Je suis en dehors du réseau du trésor");
+ this.rbOutTresor.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PnlFirstConfigProxy.this.rbOutTresorActionPerformed(evt);
+ }
+ });
+
+ this.jLabel2.setLabelFor(this.dfProxyServer);
+ this.jLabel2.setText("Serveur");
+ this.jLabel2.setEnabled(false);
+
+ this.dfProxyServer.setEnabled(false);
+ this.dfProxyServer.setName("proxy.server"); // NOI18N
+
+ this.jLabel3.setLabelFor(this.dfProxyPort);
+ this.jLabel3.setText("Port");
+ this.jLabel3.setEnabled(false);
+
+ this.dfProxyPort.setEnabled(false);
+ this.dfProxyPort.setName("proxy.port"); // NOI18N
+
+ this.chkAuthenticationRequired.setText("Mon serveur proxy requiert une authentification");
+ this.chkAuthenticationRequired.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
+ this.chkAuthenticationRequired.setEnabled(false);
+ this.chkAuthenticationRequired.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PnlFirstConfigProxy.this.chkAuthenticationRequiredActionPerformed(evt);
+ }
+ });
+
+ this.lblUser.setLabelFor(this.dfProxyUser);
+ this.lblUser.setText("Utilisateur");
+ this.lblUser.setEnabled(false);
+
+ this.dfProxyUser.setEnabled(false);
+ this.dfProxyUser.setName("proxy.user"); // NOI18N
+
+ this.dfProxyPassword.setEnabled(false);
+ this.dfProxyPassword.setName("proxy.password"); // NOI18N
+
+ this.lblPassword.setLabelFor(this.dfProxyPassword);
+ this.lblPassword.setText("Mot de passe");
+ this.lblPassword.setEnabled(false);
+
+ this.lblDomain.setLabelFor(this.dfDomainName);
+ this.lblDomain.setText("Domaine Windows");
+ this.lblDomain.setEnabled(false);
+
+ this.dfDomainName.setEnabled(false);
+ this.dfDomainName.setName("proxy.domain"); // NOI18N
+
+ this.pbTest.setText("Tester");
+ this.pbTest.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PnlFirstConfigProxy.this.pbTestActionPerformed(evt);
+ }
+ });
+
+ final 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(this.cbxUseProxy)
+ .addGroup(layout.createSequentialGroup().addComponent(this.rbInTresor).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(this.rbOutTresor))
+ .addComponent(this.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(this.lblUser).addComponent(this.lblPassword).addComponent(this.lblDomain))
+ .addGap(12, 12, 12)
+ .addGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(this.dfProxyUser, javax.swing.GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE)
+ .addComponent(this.dfProxyPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE).addComponent(this.dfDomainName, javax.swing.GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE)))
+ .addComponent(this.chkAuthenticationRequired)
+ .addGroup(
+ layout.createSequentialGroup().addComponent(this.jLabel2).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(this.dfProxyServer, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(this.jLabel3).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(this.dfProxyPort, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)))).addComponent(this.pbTest)).addContainerGap()));
+ layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
+ layout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(this.rbInTresor).addComponent(this.rbOutTresor))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(this.cbxUseProxy)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(this.jLabel2).addComponent(this.dfProxyServer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addComponent(this.dfProxyPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(this.jLabel3)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(this.chkAuthenticationRequired).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(this.lblUser).addComponent(this.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(this.lblPassword).addComponent(this.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(this.lblDomain).addComponent(this.dfDomainName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(this.pbTest).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(this.jLabel1).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void cbxUseProxyActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_cbxUseProxyActionPerformed
+ this.enableProxyControls(this.cbxUseProxy.isSelected());
+ }// GEN-LAST:event_cbxUseProxyActionPerformed
+
+ private void chkAuthenticationRequiredActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_chkAuthenticationRequiredActionPerformed
+ final boolean selected = this.chkAuthenticationRequired.isSelected();
+ this.enableAuthenticationControls(selected);
+ }// GEN-LAST:event_chkAuthenticationRequiredActionPerformed
+
+ private void pbTestActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbTestActionPerformed
+ this.runTest();
+ }// GEN-LAST:event_pbTestActionPerformed
+
+ private void rbInTresorActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_rbInTresorActionPerformed
+ this.enableTresor(true);
+ }// GEN-LAST:event_rbInTresorActionPerformed
+
+ private void rbOutTresorActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_rbOutTresorActionPerformed
+ this.enableTresor(false);
+ }// GEN-LAST:event_rbOutTresorActionPerformed
+
+ private void enableProxyControls(final boolean selected) {
+ this.dfProxyServer.setEnabled(selected);
+ this.dfProxyPort.setEnabled(selected);
+ this.chkAuthenticationRequired.setEnabled(selected);
+ // enableAuthenticationControls(selected);
+ // if(!selected) rbInTresor.doClick();
+ // rbInTresor.setEnabled(selected);
+ // rbOutTresor.setEnabled(selected);
+ }
+
+ private void enableTresor(final boolean selected) {
+ if (selected) {
+ // dfProxyServer.setText("proxy.bercy.cp");
+ // dfProxyPort.setText("3128");
+ this.chkAuthenticationRequired.setSelected(false);
+ this.chkAuthenticationRequiredActionPerformed(null);
+ }
+ // dfProxyServer.setEnabled(!selected);
+ // dfProxyPort.setEnabled(!selected);
+ this.cbxUseProxy.setEnabled(!selected);
+ // chkAuthenticationRequired.setEnabled(!selected);
+ }
+
+ private void enableAuthenticationControls(final boolean selected) {
+ this.dfProxyUser.setEnabled(selected);
+ this.dfProxyPassword.setEnabled(selected);
+ this.dfDomainName.setEnabled(selected);
+ if (!selected) {
+ this.dfProxyUser.setText("");
+ this.dfProxyPassword.setText("");
+ this.dfDomainName.setText("");
+ }
+ }
+
+ private void runTest() {
+ String proxyHost = null;
+ String proxyPort = null;
+ String proxyUser = null;
+ String proxyPasswd = null;
+ String domainName = null;
+ int intProxyPort = 0;
+
+ if (this.rbInTresor.isSelected()) {
+ proxyHost = "proxy.bercy.cp";
+ proxyPort = "3128";
+ } else {
+ if (this.dfProxyServer.getText() != null && this.dfProxyServer.getText().length() > 0) {
+ proxyHost = this.dfProxyServer.getText();
+ }
+ if (this.dfProxyPort.getText() != null && this.dfProxyPort.getText().length() > 0) {
+ proxyPort = this.dfProxyPort.getText();
+ }
+ if (this.dfProxyUser.getText() != null && this.dfProxyUser.getText().length() > 0) {
+ proxyUser = this.dfProxyUser.getText();
+ }
+ if (this.dfProxyPassword.getPassword().length > 0) {
+ proxyPasswd = new String(this.dfProxyPassword.getPassword());
+ }
+ }
+ if (proxyPort != null) {
+ try {
+ intProxyPort = Integer.parseInt(proxyPort);
+ } catch (final NumberFormatException nfEx) {
+ JOptionPane.showMessageDialog(this, proxyPort + " n'est pas un numéro de port valide.", "ERREUR", JOptionPane.ERROR_MESSAGE);
+ return;
+ }
+ }
+ if (this.dfDomainName.getText() != null && this.dfDomainName.getText().length() > 0) {
+ domainName = this.dfDomainName.getText();
+ }
+ URL url = null;
+ try {
+ url = new URL(URL_TO_REACH);
+ } catch (final MalformedURLException muEx) {
+ JOptionPane.showMessageDialog(this, "URL non valide : " + URL_TO_REACH, "ERROR", JOptionPane.ERROR_MESSAGE);
+ return;
+ }
+
+ // METHOD WITH APACHE COMMONS-HTTPCLIENT
+ final HttpClient localClient = new HttpClient();
+ final 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 {
+ final InetAddress ip = InetAddress.getByName("127.0.0.1");
+ hostName = ip.getHostName();
+ } catch (final Exception ex) {
+ logger.error("", ex);
+ }
+ creds = new NTCredentials(proxyUser, proxyPasswd, hostName, domainName);
+ } else {
+ creds = new UsernamePasswordCredentials(proxyUser, proxyPasswd);
+ }
+ localClient.getState().setProxyCredentials(AuthScope.ANY, creds);
+ }
+ final HttpMethod meth = new GetMethod(URL_TO_REACH);
+ int ret = 0;
+ try {
+ this.setBusy(true);
+ ret = localClient.executeMethod(meth);
+ if (ret > 300) {
+ // an error occured
+ JOptionPane.showMessageDialog(this, " " + ret + " : " + meth.getStatusText(), "ERREUR", JOptionPane.ERROR_MESSAGE);
+ return;
+ } else {
+ final String resp = meth.getResponseBodyAsString();
+ JOptionPane.showMessageDialog(this, "Connexion réussie !", "Proxy correctement configuré...", JOptionPane.INFORMATION_MESSAGE);
+ }
+ } catch (final Throwable t) {
+ JOptionPane.showMessageDialog(this, t.getMessage(), t.getClass().getName(), JOptionPane.ERROR_MESSAGE);
+ } finally {
+ this.setBusy(false);
+ }
+ }
+
+ @Override
+ public WizardPanelNavResult allowNext(final String stepName, final Map settings, final 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 (this.rbInTresor.isSelected()) {
+ proxyHost = "proxy.bercy.cp";
+ proxyPort = "3128";
+ this.getWizardDataMap().put("in.tresor", Boolean.TRUE);
+ } else {
+ if (this.dfProxyServer.getText() != null && this.dfProxyServer.getText().length() > 0) {
+ proxyHost = this.dfProxyServer.getText();
+ this.getWizardDataMap().put("proxy.server", this.dfProxyServer.getText());
+ this.getWizardDataMap().put("is.use.proxy", Boolean.TRUE);
+ } else {
+ this.getWizardDataMap().remove("proxy.server");
+ }
+ if (this.dfProxyPort.getText() != null && this.dfProxyPort.getText().length() > 0) {
+ proxyPort = this.dfProxyPort.getText();
+ this.getWizardDataMap().put("proxy.port", this.dfProxyPort.getText());
+ } else {
+ this.getWizardDataMap().remove("proxy.port");
+ }
+ if (this.dfProxyUser.getText() != null && this.dfProxyUser.getText().length() > 0) {
+ proxyUser = this.dfProxyUser.getText();
+ this.getWizardDataMap().put("proxy.user", this.dfProxyUser.getText());
+ } else {
+ this.getWizardDataMap().remove("proxy.user");
+ }
+ if (this.dfProxyPassword.getPassword().length > 0) {
+ proxyPasswd = new String(this.dfProxyPassword.getPassword());
+ this.getWizardDataMap().put("proxy.password", proxyPasswd);
+ }
+ }
+ if (proxyPort != null) {
+ try {
+ intProxyPort = Integer.parseInt(proxyPort);
+ } catch (final NumberFormatException nfEx) {
+ this.setProblem(proxyPort + " n'est pas un numéro de port valide.");
+ return WizardPanelNavResult.REMAIN_ON_PAGE;
+ }
+ }
+ if (this.dfDomainName.getText() != null && this.dfDomainName.getText().length() > 0) {
+ domainName = this.dfDomainName.getText();
+ this.getWizardDataMap().put("proxy.domain", this.dfDomainName.getText());
+ } else {
+ this.getWizardDataMap().remove("proxy.domain");
+ }
+
+ // METHOD WITH APACHE COMMONS-HTTPCLIENT
+ final HttpClient httpClient = new HttpClient();
+ final 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 {
+ final InetAddress ip = InetAddress.getByName("127.0.0.1");
+ hostName = ip.getHostName();
+ } catch (final Exception ex) {
+ logger.error("", ex);
+ }
+ creds = new NTCredentials(proxyUser, proxyPasswd, hostName, domainName);
+ } else {
+ creds = new UsernamePasswordCredentials(proxyUser, proxyPasswd);
+ }
+ httpClient.getState().setProxyCredentials(AuthScope.ANY, creds);
+ }
+ this.getWizardDataMap().put("http.client", httpClient);
+ client = httpClient;
+ if (PnlFirstAbo.instance != null) {
+ PnlFirstAbo.instance.testProfilsLoaded();
+ }
+ return WizardPanelNavResult.PROCEED;
+ }
+
+ @Override
+ public WizardPanelNavResult allowFinish(final String stepName, final Map settings, final Wizard wizard) {
+ return this.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
}
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>";
+ 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";
- }
+ /** Creates new form PnlPresentation */
+ public PnlPresentation() {
+ this.initComponents();
+ }
- @Override
- public WizardPanelNavResult allowFinish(String stepName, Map settings, Wizard wizard) {
- return WizardPanelNavResult.REMAIN_ON_PAGE;
- }
+ public static String getDescription() {
+ return "Présentation de la configuration";
+ }
- /** 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() {
+ @Override
+ public WizardPanelNavResult allowFinish(final String stepName, final Map settings, final Wizard wizard) {
+ return WizardPanelNavResult.REMAIN_ON_PAGE;
+ }
- jLabel1 = new javax.swing.JLabel();
+ /**
+ * 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.setText(MSG);
+ this.jLabel1 = new javax.swing.JLabel();
- 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
+ this.jLabel1.setText(MSG);
+ final 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(this.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(this.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
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JLabel jLabel1;
+ // End of variables declaration//GEN-END:variables
}
*/
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);
- }
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 3256725091285872945L;
+
+ private final Grille laGrille;
+
+ private final Font laFont = new Font("Arial", Font.BOLD, 16);
+
+ private final FontMetrics fm = this.getFontMetrics(this.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(final Grille pGrille) {
+ super();
+ this.setBackground(Color.black);
+ this.laGrille = pGrille;
+ this.laGrille.ds = this;
+ this.setPreferredSize(pGrille.getPreferredSize());
+ }
+
+ @Override
+ public void update(final Graphics g) {
+ this.paint(g);
+ }
+
+ @Override
+ public void paint(final Graphics g) {
+ if (this.laGrille == null) {
+ return;
+ }
+
+ if (this.offscreenImg == null) {
+ this.offscreenImg = this.createImage(this.getSize().width, this.getSize().height);
+ this.offscreenG = this.offscreenImg.getGraphics();
+ }
+
+ String s;
+
+ this.offscreenG.setColor(Color.black);
+ this.offscreenG.fillRect(0, 0, this.getSize().width, this.getSize().height);
+
+ this.offscreenG.setFont(this.laFont);
+
+ // Affichage des Points
+ this.offscreenG.setColor(new Color(0, 128, 224));
+ this.offscreenG.drawString(POINTS, (this.getSize().width - this.fm.stringWidth(POINTS)) / 2, 15);
+ s = "" + this.laGrille.cptPoints;
+ this.offscreenG.drawString(s, (this.getSize().width - this.fm.stringWidth(s)) / 2, 30);
+
+ // Affichage des Lignes
+ this.offscreenG.setColor(new Color(0, 192, 0));
+ this.offscreenG.drawString(LINES, (this.getSize().width - this.fm.stringWidth(LINES)) / 2, 50);
+ s = "" + this.laGrille.cptLines;
+ this.offscreenG.drawString(s, (this.getSize().width - this.fm.stringWidth(s)) / 2, 65);
+
+ // Affichage du niveau
+ this.offscreenG.setColor(Color.yellow);
+ this.offscreenG.drawString(LEVEL, (this.getSize().width - this.fm.stringWidth(LEVEL)) / 2, 85);
+ s = "" + this.laGrille.level;
+ this.offscreenG.drawString(s, (this.getSize().width - this.fm.stringWidth(s)) / 2, 100);
+
+ if (this.laGrille.gameFinished) {
+ final ImageIcon ii = IhmFactory.getIconFromResource(ImageResources.EDITEUR);
+ this.offscreenG.drawImage(ii.getImage(), (this.getWidth() - ii.getIconWidth()) / 2, this.getHeight() - ii.getIconHeight() - 5, ii.getIconWidth(), ii.getIconHeight(), this);
+ } else {
+ // Affichage de la prochaine pièce
+ this.offscreenG.setColor(Color.white);
+ this.offscreenG.drawString(NEXT, (this.getSize().width - this.fm.stringWidth(NEXT)) / 2, 140);
+ // La pièce est créée et centrée
+ final Piece p = new Piece(this.laGrille.nextOne);
+ p.firstRotation();
+ p.reset((this.getSize().width - p.getWidth() * Piece.SQUARE_SIZE) / 2, 155);
+ p.display(this.offscreenG);
+ }
+
+ // Transfert du buffer vers l'écran
+ g.drawImage(this.offscreenImg, 0, 0, this);
+ }
}
* 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;
-
- }
-
+
+ /**
+ * 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 final Color[][] grids;
+ private final Color backColor;
+ private final Piece[] pieces; // pieces that can move down
+ private Piece currentPiece;
+ public Piece nextOne;
+ private int posX, posY; // position of currentPiece
+ private final 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(final Piece[] lp) {
+ this(lp, DEFAULT_WIDTH, DEFAULT_HEIGHT);
+ }
+
+ /**
+ * Creates a new Grid
+ *
+ * @param lp
+ * @param w
+ * grid width
+ * @param h
+ * grid height
+ */
+ public Grille(final Piece[] lp, final int w, final int h) {
+ super();
+ this.gridWidth = w;
+ this.gridHeight = h;
+ this.direction = DIRECTION_DOWN;
+ this.grids = new Color[this.gridHeight][this.gridWidth];
+ this.pieces = lp;
+ this.selectPiece();
+ this.gameRunning = false;
+ this.gameFinished = false;
+ this.paintAll = false;
+ this.cptLines = this.cptPoints = 0;
+ this.level = 1;
+ this.backColor = Color.darkGray;
+ this.gameOverPainted = false;
+ this.initListeners();
+ }
+
+ /**
+ * Selects next piece
+ */
+ private void selectPiece() {
+ if (this.nextOne == null) {
+ // creates 2 new pieces
+ this.idCurrent = (int) (Math.random() * this.pieces.length);
+ this.idNextOne = (int) (Math.random() * this.pieces.length);
+ this.currentPiece = new Piece(this.pieces[this.idCurrent]);
+ this.nextOne = new Piece(this.pieces[this.idNextOne]);
+ } else {
+ // switches next to current
+ this.currentPiece = this.nextOne;
+ this.idCurrent = this.idNextOne;
+ // creates the next one
+ this.idNextOne = (int) (Math.random() * this.pieces.length);
+ this.nextOne = new Piece(this.pieces[this.idNextOne]);
+ }
+ this.resetPiece();
+ this.bonus = 20;
+ this.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(final int x, final int y, final Piece p) {
+ if (y < 0 || y + p.getHeight() > this.gridHeight) {
+ return false;
+ }
+ if (x < 0 || x + p.getWidth() > this.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) && this.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>
+ * 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
- }
+ private boolean canDisplayAt(final int x, final int y) {
+ return this.canDisplayAt(x, y, this.currentPiece);
+ }
+
+ /**
+ * Reverses game direction
+ */
+ private void reverseGame() {
+ Color buffer;
+ int i, j;
+
+ for (i = 0; i < this.gridHeight / 2; i++) {
+ for (j = 0; j < this.gridWidth; j++) {
+ buffer = this.grids[i][j];
+ this.grids[i][j] = this.grids[this.gridHeight - 1 - i][j];
+ this.grids[this.gridHeight - 1 - i][j] = buffer;
+ }
+ }
+ }
+
+ private void resetPiece() {
+ this.posX = (this.gridWidth / 2) - (this.currentPiece.getWidth() / 2);
+ if (this.direction == 1) {
+ this.posY = 0;
+ } else {
+ this.posY = this.gridHeight - this.currentPiece.getHeight();
+ }
+ this.currentPiece.reset(this.posX * Piece.SQUARE_SIZE, this.posY * Piece.SQUARE_SIZE);
+ }
+
+ /**
+ * Drops filled lines, computes score, etc...
+ */
+ private void pieceStop() {
+ int i, j, mask = 0x8000;
+ int scr_i, scr_j;
+ final int oldCptLines = this.cptLines;
+
+ // update grid
+ for (i = 0; i < this.currentPiece.getHeight(); i++) {
+ for (j = 0; j < this.currentPiece.getWidth(); j++, mask >>= 1) {
+ if ((this.currentPiece.getVal() & mask) != 0) {
+ this.grids[this.posY + i][this.posX + j] = this.pieces[this.idCurrent].getColor();
+ }
+ }
+ // move mask to next line
+ mask >>= 4 - this.currentPiece.getWidth();
+ }
+
+ // incs score
+ this.cptPoints += 5;
+
+ if (this.direction == DIRECTION_DOWN) {
+ // check lines
+ for (i = this.posY; i < this.posY + this.currentPiece.getHeight(); i++) {
+ for (j = 0; j < this.gridWidth; j++) {
+ if (this.grids[i][j] == null) {
+ break;
+ }
+ }
+ // line is filled
+ if (j == this.gridWidth) {
+ // scrolls down
+ for (scr_i = i; scr_i > 0; scr_i--) {
+ for (scr_j = 0; scr_j < this.gridWidth; scr_j++) {
+ this.grids[scr_i][scr_j] = this.grids[scr_i - 1][scr_j];
+ }
+ }
+ for (scr_j = 0; scr_j < this.gridWidth; scr_j++) {
+ this.grids[0][scr_j] = null;
+ }
+ this.cptLines++;
+ }
+ }
+ } else {
+ for (i = this.posY + this.currentPiece.getHeight() - 1; i >= this.posY; i--) {
+ for (j = 0; j < this.gridWidth; j++) {
+ if (this.grids[i][j] == null) {
+ break;
+ }
+ }
+ if (j == this.gridWidth) {
+ for (scr_i = i; scr_i < this.gridHeight - 1; scr_i++) {
+ for (scr_j = 0; scr_j < this.gridWidth; scr_j++) {
+ this.grids[scr_i][scr_j] = this.grids[scr_i + 1][scr_j];
+ }
+ }
+ for (scr_j = 0; scr_j < this.gridWidth; scr_j++) {
+ this.grids[this.gridHeight - 1][scr_j] = null;
+ }
+ this.cptLines++;
+ }
+ }
+ }
+ if (oldCptLines != this.cptLines) {
+ // 10 points a line
+ this.cptPoints += (this.cptLines - oldCptLines) * 10;
+ // 100 points a four
+ if (this.cptLines - oldCptLines == 4) {
+ this.cptPoints += 100;
+ }
+ }
+
+ // max level = 12
+ if (this.level < 12 && this.cptPoints >= 1000 * this.level) {
+ this.level++;
+ }
+
+ this.paintAll = true;
+ this.paintPiece = false;
+ this.repaint();
+ }
+
+ @Override
+ public Dimension getMinimumSize() {
+ return this.getPreferredSize();
+ }
+
+ @Override
+ public Dimension getPreferredSize() {
+ return new Dimension(Piece.SQUARE_SIZE * this.gridWidth, Piece.SQUARE_SIZE * this.gridHeight);
+ }
+
+ public void restartGame() {
+ this.selectPiece();
+ this.gameRunning = true;
+ this.gameFinished = false;
+ this.paintAll = true;
+ this.cptLines = this.cptPoints = 0;
+ this.level = 1;
+ this.gameOverPainted = false;
+ int i, j;
+ for (i = 0; i < this.gridHeight; i++) {
+ for (j = 0; j < this.gridWidth; j++) {
+ this.grids[i][j] = null;
+ }
+ }
+ }
+
+ public void start() {
+ if (this.m_Grille == null) {
+ this.m_Grille = new Thread(this);
+ this.finished = false;
+ this.m_Grille.start();
+ }
+ }
+
+ public void stop() {
+ if (this.m_Grille != null) {
+ this.finished = true;
+ this.m_Grille = null;
+ }
+ }
+
+ @Override
+ public synchronized void update(final Graphics g) {
+ this.paint(g);
+ }
+
+ public synchronized void paintPiece(final boolean effPiece) {
+ if (this.offscreenImg == null) {
+ return;
+ }
+
+ if (effPiece) {
+ this.currentPiece.erase(this.offscreenG, this.backColor);
+ }
+ this.currentPiece.display(this.offscreenG);
+ }
+
+ private synchronized void paintGameOver() {
+ Font laFont = new Font("Arial", Font.BOLD, 20);
+ FontMetrics fm = this.getFontMetrics(laFont);
+ final Color c = new Color(0, 128, 224);
+
+ for (int i = 0; i < this.gridHeight; i++) {
+ for (int j = 0; j < this.gridWidth; j++) {
+ this.offscreenG.setColor(c);
+ this.offscreenG.fill3DRect(j * Piece.SQUARE_SIZE, i * Piece.SQUARE_SIZE, Piece.SQUARE_SIZE, Piece.SQUARE_SIZE, true);
+ }
+ }
+
+ this.offscreenG.setColor(Color.yellow);
+ this.offscreenG.setFont(laFont);
+ this.offscreenG.drawString("Partie", (this.getSize().width - fm.stringWidth("Partie")) / 2, 32);
+ this.offscreenG.drawString("terminée", (this.getSize().width - fm.stringWidth("terminée")) / 2, 64);
+
+ String s;
+ laFont = new Font("Arial", Font.BOLD, 14);
+ fm = this.getFontMetrics(laFont);
+ this.offscreenG.setColor(Color.white);
+ this.offscreenG.setFont(laFont);
+ s = "cliquez pour rejouer";
+ this.offscreenG.drawString(s, (this.getSize().width - fm.stringWidth(s)) / 2, 220);
+
+ this.gameOverPainted = true;
+ }
+
+ @Override
+ public void paint(final Graphics g) {
+ if (this.offscreenImg == null) {
+ this.offscreenImg = this.createImage(this.gridWidth * Piece.SQUARE_SIZE, this.gridHeight * Piece.SQUARE_SIZE);
+ this.backImg = this.createImage(this.gridWidth * Piece.SQUARE_SIZE, this.gridHeight * Piece.SQUARE_SIZE);
+ this.offscreenG = this.backImg.getGraphics();
+ this.offscreenG.setColor(this.backColor);
+ for (int i = 0; i < this.gridHeight; i++) {
+ for (int j = 0; j < this.gridWidth; j++) {
+ this.offscreenG.fill3DRect(j * Piece.SQUARE_SIZE, i * Piece.SQUARE_SIZE, Piece.SQUARE_SIZE, Piece.SQUARE_SIZE, true);
+ }
+ }
+ this.offscreenG = this.offscreenImg.getGraphics();
+ this.offscreenG.drawImage(this.backImg, 0, 0, this);
+ }
+
+ if (!this.gameFinished) {
+ // do we need to paint everything ?
+ if (this.paintAll) {
+ this.offscreenG.drawImage(this.backImg, 0, 0, this);
+ for (int i = 0; i < this.gridHeight; i++) {
+ for (int j = 0; j < this.gridWidth; j++) {
+ if (this.grids[i][j] != null) {
+ this.offscreenG.setColor(this.grids[i][j]);
+ this.offscreenG.fill3DRect(j * Piece.SQUARE_SIZE, i * Piece.SQUARE_SIZE, Piece.SQUARE_SIZE, Piece.SQUARE_SIZE, true);
+ }
+ }
+ }
+ this.paintAll = false;
+
+ if (this.paintPiece) {
+ this.paintPiece(false);
+ }
+ } else {
+ this.paintPiece(true);
+ }
+ } else if (!this.gameOverPainted) {
+ this.paintGameOver();
+ this.paintAll = false; // do not erase the gameOver screen
+ }
+
+ // paint double-buffer
+ g.drawImage(this.offscreenImg, 0, 0, this);
+ this.ds.repaint();
+ }
+
+ /**
+ * Moves current piece to its lowest position
+ */
+ public synchronized void goDown() {
+ int cpt = 1;
+
+ this.posY++;
+
+ while (true) {
+ // outside ?
+ if (this.posY < 0 || this.posY + this.currentPiece.getHeight() > this.gridHeight) {
+ this.posY--;
+ this.currentPiece.goDown(cpt - 1);
+ return;
+ }
+
+ int mask = 0x8000;
+
+ // try to move down one line
+ for (int i = 0; i < this.currentPiece.getHeight(); i++) {
+ for (int j = 0; j < this.currentPiece.getWidth(); j++, mask >>= 1) {
+ if (((this.currentPiece.getVal() & mask) != 0) && this.grids[this.posY + i][this.posX + j] != null) {
+ this.posY--;
+ this.currentPiece.goDown(cpt - 1);
+ return;
+ }
+ }
+ // ok, moves it
+ mask >>= 4 - this.currentPiece.getWidth();
+ }
+ cpt++;
+ this.posY++;
+ }
+ }
+
+ /**
+ * Moves piece up to its highest position
+ *
+ */
+ public synchronized void goUp() {
+ int cpt = 1;
+ this.posY--;
+
+ while (true) {
+ if (this.posY < 0 || this.posY + this.currentPiece.getHeight() > this.gridHeight) {
+ this.posY++;
+ this.currentPiece.goUp(cpt - 1);
+ return;
+ }
+ int mask = 0x8000;
+ for (int i = 0; i < this.currentPiece.getHeight(); i++) {
+ for (int j = 0; j < this.currentPiece.getWidth(); j++, mask >>= 1) {
+ if (((this.currentPiece.getVal() & mask) != 0) && this.grids[this.posY + i][this.posX + j] != null) {
+ this.posY++;
+ this.currentPiece.goUp(cpt - 1);
+ return;
+ }
+ }
+ mask >>= 4 - this.currentPiece.getWidth();
+ }
+ cpt++;
+ this.posY--;
+ }
+ }
+
+ /**
+ * plays the animation
+ */
+ @Override
+ public void run() {
+ while (!this.finished) {
+ if (!this.gameOverPainted) {
+ this.repaint();
+
+ if (this.gameRunning && !this.gameFinished) {
+ this.bonus--;
+
+ if (this.direction == DIRECTION_DOWN) {
+ if (this.canDisplayAt(this.posX, this.posY + 1)) {
+ this.posY++;
+ this.currentPiece.goDown();
+ } else {
+ this.pieceStop();
+ this.selectPiece();
+ if (!this.canDisplayAt(this.posX, this.posY)) {
+ this.gameFinished = true;
+ }
+ }
+ } else {
+ if (this.canDisplayAt(this.posX, this.posY - 1)) {
+ this.posY--;
+ this.currentPiece.goUp();
+ } else {
+ this.pieceStop();
+ this.selectPiece();
+ if (!this.canDisplayAt(this.posX, this.posY)) {
+ this.gameFinished = true;
+ }
+ }
+ }
+ }
+ }
+
+ try {
+ Thread.sleep(300 - ((this.level - 1) * 20));
+ } catch (final InterruptedException e) {
+ this.stop();
+ }
+ }
+ }
+
+ @Override
+ public void keyPressed(final KeyEvent e) {
+ final int key = e.getKeyCode();
+
+ if (key == 'p' || key == 'P') {
+ this.gameRunning = !this.gameRunning;
+ } else if (this.gameRunning) {
+ switch (key) {
+ case KeyEvent.VK_LEFT:
+ if (this.canDisplayAt(this.posX - 1, this.posY)) {
+ this.posX--;
+ this.currentPiece.goLeft();
+ }
+ break;
+ case KeyEvent.VK_RIGHT:
+ if (this.canDisplayAt(this.posX + 1, this.posY)) {
+ this.posX++;
+ this.currentPiece.goRight();
+ }
+ break;
+ case KeyEvent.VK_UP:
+ if (this.canDisplayAt(this.posX, this.posY, this.currentPiece.getNextPiece())) {
+ this.currentPiece.rotate();
+ }
+ break;
+ case KeyEvent.VK_DOWN:
+ if (this.bonus > 0) {
+ this.cptPoints += this.bonus;
+ }
+ if (this.direction == 1) {
+ this.goDown();
+ } else {
+ this.goUp();
+ }
+ break;
+ case 'i':
+ case 'I':
+ this.reverseGame();
+ this.direction = -this.direction;
+ this.resetPiece();
+ this.bonus = 0;
+ this.paintAll = true;
+ break;
+ default:
+ return;
+ }
+ }
+ this.repaint();
+ }
+
+ @Override
+ public void keyTyped(final KeyEvent e) {
+ }
+
+ @Override
+ public void keyReleased(final KeyEvent e) {
+ }
+
+ @Override
+ public void focusLost(final FocusEvent e) {
+ this.gameRunning = false;
+ }
+
+ @Override
+ public void focusGained(final FocusEvent e) {
+ }
+
+ public boolean mouseDown() {
+ this.gameRunning = true;
+ if (this.gameFinished) {
+ this.restartGame();
+ this.repaint();
+ }
+ return true;
+ }
+
+ private void initListeners() {
+ this.addMouseListener(new MouseListener() {
+ @Override
+ public void mouseClicked(final MouseEvent e) {
+ Grille.this.mouseDown();
+ }
+
+ @Override
+ public void mousePressed(final MouseEvent e) {
+ }
+
+ @Override
+ public void mouseReleased(final MouseEvent e) {
+ }
+
+ @Override
+ public void mouseEntered(final MouseEvent e) {
+ }
+
+ @Override
+ public void mouseExited(final MouseEvent e) {
+ }
+ });
+ // listeners moves to JTRIS
+ }
}
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);
- }
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 3256721801408099890L;
+ private Grille laGrille;
+ private DisplayScore dspScore;
+ private final Piece[] listePieces;
+ private boolean finished = false;
+
+ public JTRIS(final JFrame parent) {
+ super(parent);
+ this.listePieces = new Piece[7];
+ this.listePieces[0] = new Piece(0x88C0, 0x2E00, 0xC440, 0xE800, new Color(0, 192, 192)); // cyan
+ this.listePieces[1] = new Piece(0x44C0, 0xE200, 0xC880, 0x8E00, new Color(255, 230, 0)); // jaune
+ this.listePieces[2] = new Piece(0xCC00, 0xCC00, 0xCC00, 0xCC00, new Color(0, 192, 0)); // vert
+ this.listePieces[3] = new Piece(0x8888, 0xF000, 0x8888, 0xF000, new Color(230, 0, 0)); // rouge
+ this.listePieces[4] = new Piece(0x8C40, 0x6C00, 0x8C40, 0x6C00, new Color(0, 128, 224)); // bleu
+ this.listePieces[5] = new Piece(0x4C80, 0xC600, 0x4C80, 0xC600, Color.orange);
+ this.listePieces[6] = new Piece(0x8C80, 0x4E00, 0x4C40, 0xE400, Color.lightGray);
+ this.init();
+ }
+
+ public void init() {
+ final JPanel mainPane = new JPanel(new GridLayout(1, 2, 10, 0));
+
+ this.laGrille = new Grille(this.listePieces);
+ this.laGrille.setBackground(Color.black);
+ mainPane.add(this.laGrille);
+
+ this.dspScore = new DisplayScore(this.laGrille);
+ mainPane.add(this.dspScore);
+
+ this.setContentPane(mainPane);
+ this.addKeyListener(this);
+ this.pack();
+ }
+
+ @Override
+ public void setVisible(final boolean b) {
+ super.setVisible(b);
+ if (b) {
+ this.laGrille.start();
+ this.start();
+ } else {
+ this.stop();
+ this.laGrille.stop();
+ }
+ }
+
+ @Override
+ public void paint(final Graphics g) {
+ g.setColor(Color.orange);
+ g.fill3DRect(0, 0, this.getSize().width, this.getSize().height, true);
+
+ if (this.dspScore != null) {
+ this.dspScore.repaint();
+ }
+ }
+
+ public void start() {
+ this.finished = false;
+ }
+
+ public void stop() {
+ this.finished = true;
+ }
+
+ @Override
+ public void run() {
+ while (!this.finished) {
+ this.repaint();
+ try {
+ Thread.sleep(300);
+ } catch (final InterruptedException e) {
+ }
+ }
+ }
+
+ @Override
+ public void keyPressed(final KeyEvent e) {
+ this.laGrille.keyPressed(e);
+ }
+
+ @Override
+ public void keyReleased(final KeyEvent e) {
+ this.laGrille.keyReleased(e);
+ }
+
+ @Override
+ public void keyTyped(final KeyEvent e) {
+ this.laGrille.keyTyped(e);
+ }
}
\ No newline at end of file
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");
-// }
+ 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 final int rep[][] = new int[10][10];
+ private final int val[][] = new int[10][10];
+
+ private final String marque;
+ private final Icon icon;
+
+ public Joueur(final String s, final Icon icon) {
+ super();
+ this.marque = s;
+ this.icon = icon;
+ }
+
+ public void joue(final JPanel jPanelJeu) {
+ this.modelise(jPanelJeu);
+ this.decide(jPanelJeu);
+ }
+
+ public int sgn(final int i) {
+ return i == 0 ? 0 : i < 0 ? -1 : 1;
+ }
+
+ public int compte_pion(int dx, int dy, final int fx, final int fy, final int v) {
+ boolean cnt = true;
+ int cpt = 0;
+ while (((dx != fx) || (dy != fy)) && cnt) {
+ dx += this.sgn(fx - dx);
+ dy += this.sgn(fy - dy);
+ if ((dx >= 0) && (dx <= 9) && (dy >= 0) && (dy <= 9) && (this.rep[dx][dy] == v)) {
+ cpt++;
+ } else {
+ cnt = false;
+ }
+ }
+ return cpt;
+ }
+
+ public int compte_case(int dx, int dy, final int fx, final int fy) {
+ // boolean cnt = true;
+ int cpt = 0;
+ if ((dx >= 0) && (dx <= 9) && (dy >= 0) && (dy <= 9)) {
+ cpt++;
+ }
+ while ((dx != fx) || (dy != fy)) {
+ dx += this.sgn(fx - dx);
+ dy += this.sgn(fy - dy);
+ if ((dx >= 0) && (dx <= 9) && (dy >= 0) && (dy <= 9)) {
+ cpt++;
+ }
+ }
+ return cpt;
+ }
+
+ public int evalue(int dx, int dy, final int fx, final int fy, final int v) {
+ boolean cnt = true;
+ int cpt = 0, ind = 0;
+ while (((dx != fx) || (dy != fy)) && cnt) {
+ dx += this.sgn(fx - dx);
+ dy += this.sgn(fy - dy);
+ ind++;
+ if ((dx >= 0) && (dx <= 9) && (dy >= 0) && (dy <= 9) && (this.rep[dx][dy] == v)) {
+ cpt += this.rep[dx][dy] * (5 - ind);
+ } else if ((dx >= 0) && (dx <= 9) && (dy >= 0) && (dy <= 9)) {
+ cnt = (this.rep[dx][dy] == 0);
+ cpt += this.rep[dx][dy] * (5 - ind);
+ } else {
+ cnt = false;
+ }
+ }
+ return cpt;
+ }
+
+ public void valorise(final int x, final int y) {
+ int cpt;
+
+ for (int i = 0; i < 4; i++) {
+ cpt = 1;
+ cpt += this.compte_pion(x, y, vrx[i % 3][i / 3] + x, vry[i % 3][i / 3] + y, this.rep[x][y]);
+ cpt += this.compte_pion(x, y, vrx[(8 - i) % 3][(8 - i) / 3] + x, vry[(8 - i) % 3][(8 - i) / 3] + y, this.rep[x][y]);
+ if (cpt > Math.abs(this.val[x][y])) {
+ this.val[x][y] = cpt;
+ }
+ }
+ }
+
+ public void modelise(final 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);
+ this.rep[i % 10][i / 10] = ((JButton) jp.getComponent(i)).getActionCommand() == "" ? 0 : ((JButton) jp.getComponent(i)).getActionCommand() == this.marque ? 1 : -1;
+ }
+
+ for (int i = 0; i < 10; i++) {
+ java.util.Arrays.fill(this.val[i], 0);
+ }
+ }
+
+ public void projete(final int x, final int y) {
+ int pls, mns;
+ for (int i = 0; i < 4; i++) {
+ pls = 0;
+ mns = 0;
+ if (this.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 += this.evalue(x, y, vrx[i % 3][i / 3] + x, vry[i % 3][i / 3] + y, -1);
+ mns += this.evalue(x, y, vrx[(8 - i) % 3][(8 - i) / 3] + x, vry[(8 - i) % 3][(8 - i) / 3] + y, -1);
+ pls += this.evalue(x, y, vrx[i % 3][i / 3] + x, vry[i % 3][i / 3] + y, 1);
+ pls += this.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(this.val[x][y])) {
+ this.val[x][y] = mns;
+ }
+ if (Math.abs(pls) > Math.abs(this.val[x][y])) {
+ this.val[x][y] = pls;
+ }
+ }
+ }
+
+ public void decide(final JPanel jPanelJeu) {
+ int scr = 0, scp = 50;
+
+ for (int i = 0; i < 10; i++) {
+ for (int j = 0; j < 10; j++) {
+ if (this.rep[j][i] == 0) {
+ this.projete(j, i);
+ }
+ }
+ }
+
+ for (int i = 0; i < 10; i++) {
+ for (int j = 0; j < 10; j++) {
+ if (this.rep[j][i] == 0) {
+ if (Math.abs(this.val[j][i]) > scr) {
+ scr = Math.abs(this.val[j][i]);
+ scp = j + i * 10;
+ } else {
+ if (Math.abs(this.rep[j][i]) == scr) {
+ if (this.val[j][i] >= this.val[scp % 10][scp / 10]) {
+ scp = j + i * 10;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ this.rep[scp % 10][scp / 10] = 1;
+ ((JButton) jPanelJeu.getComponent(scp)).setActionCommand(this.marque);
+ ((JButton) jPanelJeu.getComponent(scp)).setIcon(this.icon);
+ ((JButton) jPanelJeu.getComponent(scp)).setForeground(java.awt.Color.red);
+ ((JButton) jPanelJeu.getComponent(scp)).setBackground(java.awt.Color.white);
+ }
+
+ public boolean victoire(final JPanel jp) {
+ boolean cnt = false;
+
+ for (int i = 0; i < jp.getComponentCount(); i++) {
+ this.rep[i % 10][i / 10] = ((JButton) jp.getComponent(i)).getActionCommand() == "" ? 0 : ((JButton) jp.getComponent(i)).getActionCommand() == this.marque ? 1 : -1;
+ }
+
+ for (int i = 0; i < 10; i++) {
+ java.util.Arrays.fill(this.val[i], 0);
+ }
+
+ for (int i = 0; i < 10; i++) {
+ for (int j = 0; j < 10; j++) {
+ if (this.rep[j][i] != 0) {
+ this.valorise(j, i);
+ }
+ }
+ }
+
+ for (int i = 0; i < 10; i++) {
+ for (int j = 0; j < 10; j++) {
+ if (Math.abs(this.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;
- }
+ return this.marque;
+ }
+
public Icon getIcon() {
- return icon;
+ return this.icon;
}
}
\ No newline at end of file
/**
* 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);
- }
+ // contains a representation of the 4 rotations
+ private final int[] images = new int[4];
+ // contains the height 4 rotations
+ private final int[] heights = new int[4];
+ // contains the width des 4 rotations
+ private final int[] widths = new int[4];
+ // Position
+ private int x, y;
+ // last state
+ private int lastX, lastY, lastRotation;
+ private final Color color;
+ // current rotation
+ private int idRotation;
+ // unitary size of a square
+ public final static int SQUARE_SIZE = 15;
+
+ // Constructors
+ public Piece(final int r1, final int r2, final int r3, final int r4, final Color color) {
+ this.images[0] = r1;
+ this.images[1] = r2;
+ this.images[2] = r3;
+ this.images[3] = r4;
+ this.color = color;
+ this.x = this.y = this.idRotation = 0;
+ this.lastX = this.lastY = -1;
+ this.computesWH();
+ }
+
+ public Piece(final int r1, final int r2, final int r3, final int r4, final Color color, final int p_x, final int p_y) {
+ this(r1, r2, r3, r4, color);
+ this.x = p_x;
+ this.y = p_y;
+ }
+
+ public Piece(final int[] r, final Color color) {
+ System.arraycopy(r, 0, this.images, 0, 4);
+ this.x = this.y = this.idRotation = 0;
+ this.lastX = this.lastY = -1;
+ this.color = color;
+ this.computesWH();
+ }
+
+ public Piece(final int[] r, final Color color, final int p_x, final int p_y) {
+ this(r, color);
+ this.x = p_x;
+ this.y = p_y;
+ }
+
+ public Piece(final Piece src) {
+ System.arraycopy(src.images, 0, this.images, 0, 4);
+ System.arraycopy(src.widths, 0, this.widths, 0, 4);
+ System.arraycopy(src.heights, 0, this.heights, 0, 4);
+ this.idRotation = src.idRotation;
+ this.lastX = src.lastX;
+ this.lastY = src.lastY;
+ this.lastRotation = src.lastRotation;
+ this.x = src.x;
+ this.y = src.y;
+ this.color = src.color;
+ }
+
+ public void reset() {
+ this.reset(0, 0);
+ }
+
+ public void reset(final int p_x, final int p_y) {
+ this.x = p_x;
+ this.y = p_y;
+ this.idRotation = 0;
+ this.lastX = this.lastY = -1;
+ }
+
+ public void firstRotation() {
+ this.idRotation = 0;
+ }
+
+ private void computesWH() {
+ Arrays.fill(this.widths, 0);
+ Arrays.fill(this.heights, 0);
+
+ for (int cptRotations = 0; cptRotations < this.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 & this.images[cptRotations]) != 0) {
+ if (!lineOK) {
+ lineOK = true;
+ this.heights[cptRotations]++;
+ }
+ if (this.widths[cptRotations] < j + 1) {
+ this.widths[cptRotations] = j + 1;
+ }
+ }
+ }
+ }
+ }
+
+ }
+
+ public void rotate() {
+ // if (idRotation >= 3) idRotation = 0;
+ // else idRotation++;
+ this.idRotation = ((this.idRotation + 1) % 4);
+ }
+
+ public void goDown() {
+ this.y += SQUARE_SIZE;
+ }
+
+ public void goDown(final int lines) {
+ this.y += (SQUARE_SIZE * lines);
+ }
+
+ public void goLeft() {
+ this.x -= SQUARE_SIZE;
+ }
+
+ public void goRight() {
+ this.x += SQUARE_SIZE;
+ }
+
+ public void goUp() {
+ this.y -= SQUARE_SIZE;
+ }
+
+ public void goUp(final int lines) {
+ this.y -= (SQUARE_SIZE * lines);
+ }
+
+ public int getX() {
+ return this.x;
+ }
+
+ public int getY() {
+ return this.y;
+ }
+
+ public int paintx() {
+ return this.lastX;
+ }
+
+ public int painty() {
+ return this.lastY;
+ }
+
+ public Color getColor() {
+ return this.color;
+ }
+
+ public int getHeight() {
+ return this.heights[this.idRotation];
+ }
+
+ public int getHeight(final int id) {
+ return id >= 0 && id < 4 ? this.heights[id] : 0;
+ }
+
+ public int nextHeight() {
+ return this.heights[this.idRotation >= 3 ? 0 : this.idRotation + 1];
+ }
+
+ public int getWidth() {
+ return this.widths[this.idRotation];
+ }
+
+ public int getWidth(final int id) {
+ return id >= 0 && id < 4 ? this.widths[id] : 0;
+ }
+
+ public int nextWidth() {
+ return this.widths[this.idRotation >= 3 ? 0 : this.idRotation + 1];
+ }
+
+ public int getVal() {
+ return this.images[this.idRotation];
+ }
+
+ public int getVal(final int id) {
+ return id >= 0 && id < 4 ? this.images[id] : 0;
+ }
+
+ public int getNextVal() {
+ return this.images[this.idRotation >= 3 ? 0 : this.idRotation + 1];
+ }
+
+ public Piece getNextPiece() {
+ final Piece np = new Piece(this);
+ np.rotate();
+ return np;
+ }
+
+ public synchronized void display(final Graphics g) {
+ int mask = 0x8000, i, j;
+
+ this.lastX = this.x;
+ this.lastY = this.y;
+ this.lastRotation = this.idRotation;
+ g.setColor(this.color);
+ for (i = 0; i < 4; i++) {
+ for (j = 0; j < 4; j++, mask >>= 1) {
+ if ((mask & this.images[this.idRotation]) != 0) {
+ g.fill3DRect(this.x + (j * SQUARE_SIZE), this.y + (i * SQUARE_SIZE), SQUARE_SIZE, SQUARE_SIZE, true);
+ }
+ }
+ }
+ }
+
+ public synchronized void erase(final Graphics g, final Color fond) {
+ int mask = 0x8000, i, j;
+
+ if (this.lastX == -1 || this.lastY == -1) {
+ return;
+ }
+
+ g.setColor(fond);
+ for (i = 0; i < 4; i++) {
+ for (j = 0; j < 4; j++, mask >>= 1) {
+ if ((mask & this.images[this.lastRotation]) != 0) {
+ g.fill3DRect(this.lastX + (j * SQUARE_SIZE), this.lastY + (i * SQUARE_SIZE), SQUARE_SIZE, SQUARE_SIZE, true);
+ }
+ }
+ }
+ }
}
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());
- }
+ /**
+ * 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 {
+ this.jbInit();
+ for (int i = 0; i < 100; i++) {
+ final JButton jbt = new JButton();
+ jbt.setBackground(BACK_COLOR);
+ jbt.setFont(new java.awt.Font("Dialog", 1, 8));
+ jbt.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ Plateau.this.jButton_actionPerformed(e);
+ }
+ });
+ this.jPanelJeu.add(jbt, null);
+ }
+ final Dimension sSz = Toolkit.getDefaultToolkit().getScreenSize();
+ final Dimension fSz = this.getSize();
+ this.setLocation((sSz.width - fSz.width) / 2, (sSz.height - fSz.height) / 2);
+ this.setVisible(true);
+ } catch (final Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ private void jbInit() throws Exception {
+ this.contentPane = (JPanel) this.getContentPane();
+ this.contentPane.setLayout(new BorderLayout());
+ this.jButtonEffacer = new JButton("Effacer");
+ this.jButtonEffacer.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ Plateau.this.jButtonEffacer_actionPerformed(e);
+ }
+ });
+ this.jPanelJeu.setLayout(new GridLayout(10, 10));
+
+ this.jPanelJeu.setMaximumSize(new Dimension(300, 2147483647));
+ this.jPanelJeu.setMinimumSize(new Dimension(300, 100));
+ this.jPanelJeu.setPreferredSize(new Dimension(300, 300));
+ this.contentPane.add(this.buttonPane, BorderLayout.EAST);
+ this.buttonPane.add(this.jButtonEffacer, null);
+ this.contentPane.add(this.jPanelJeu, BorderLayout.CENTER);
+ this.pack();
+ }
+
+ void jButton_actionPerformed(final ActionEvent e) {
+ final JButton source = ((JButton) e.getSource());
+ if (source.getActionCommand().length() != 0) {
+ JOptionPane.showMessageDialog(this, "Tricheur !");
+ return;
+ }
+ source.setActionCommand(this.joueur.getMarque());
+ source.setIcon(this.joueur.getIcon());
+ this.joueur.modelise(this.jPanelJeu);
+ if (this.joueur.victoire(this.jPanelJeu)) {
+ this.termine(this.joueur.getMarque());
+ } else {
+ // c'est a l'autre de jouer
+ this.ordi.joue(this.jPanelJeu);
+ if (this.ordi.victoire(this.jPanelJeu)) {
+ this.termine(this.ordi.getMarque());
+ }
+ }
+ }
+
+ void jButtonEffacer_actionPerformed(final ActionEvent e) {
+ for (int i = 0; i < this.jPanelJeu.getComponentCount(); i++) {
+ ((JButton) this.jPanelJeu.getComponent(i)).setActionCommand("");
+ ((JButton) this.jPanelJeu.getComponent(i)).setIcon(null);
+ ((JButton) this.jPanelJeu.getComponent(i)).setForeground(Color.black);
+ ((JButton) this.jPanelJeu.getComponent(i)).setBackground(BACK_COLOR);
+ }
+ }
+
+ public void termine(final 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(final ActionEvent e) {
+ this.ordi.joue(this.jPanelJeu);
+ if (this.ordi.victoire(this.jPanelJeu)) {
+ this.termine(this.ordi.getMarque());
+ }
+ }
+
+ void pbJoueur_actionPerformed(final ActionEvent e) {
+ this.joueur.joue(this.jPanelJeu);
+ if (this.joueur.victoire(this.jPanelJeu)) {
+ this.termine(this.joueur.getMarque());
+ }
+ }
}
\ No newline at end of file
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
+ * 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....
+ * </NL>
+ * </BR> until a solution is found....
*
* @author Tchok
*/
// No remove flag
private boolean _noRemove;
- // Current count
- private int _count;
-
// Solve number of ops
private int _opsCount;
// Symetrizer
private Symetrizer _symetrizer;
-
+
/** Get one. */
public Builder() {
// NOP
/**
* @return initial state.
*/
- public State buildOne(Template tpl_p) {
+ public State buildOne(final 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);
+ this._initialPosition = new State(tpl_p);
+ this._maxIndex = this._initialPosition.getTemplate().maxIndex;
+ this._maxValue = this._initialPosition.getTemplate().maxValue;
+ this._symetrizer = tpl_p.symetrical ? new Symetrizer(tpl_p) : new NoSymetrizer(tpl_p);
// Feed it
- initializeState();
+ this.initializeState();
// Clear solution
- _solution = null;
- //
+ this._solution = null;
+ //
// // Say it
// Start it
- Solver solver = new Solver(this);
- while (_solution == null) {
+ final Solver solver = new Solver(this);
+ while (this._solution == null) {
// Look for a solution
- _noRemove = false;
- _opsCount = getMaxOpsCount(tpl_p);
- solver.solve(_initialPosition);
-
+ this._noRemove = false;
+ this._opsCount = this.getMaxOpsCount(tpl_p);
+ solver.solve(this._initialPosition);
+
// If no solution was found, remove one of the original values
- if ((_solution == null) && (!_noRemove)) {
- removeFromInitialPosition();
+ if ((this._solution == null) && (!this._noRemove)) {
+ this.removeFromInitialPosition();
}
- //
+ //
// // Say it
}
// Found a solution, mark it
- State output = new State(_initialPosition);
+ final State output = new State(this._initialPosition);
output.registerOriginalPosition();
// OK
}
/**
- * Get the max operations count allowed according to template.
- * This is because some configurations just takes too much time...
+ * 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) {
+ private int getMaxOpsCount(final Template tpl_p) {
// Get size
- int size = tpl_p.maxValue;
+ final int size = tpl_p.maxValue;
// Fix answer...
- int base = 1000000;
+ final int base = 1000000;
// TODO Get values from resource ?
if (size < 10) {
return base;
}
/**
- * Initialize the starting state.
- * The <code>_initialPosition</code> should be clean.
+ * 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++) {
+
+ // Build two list [0, _maxValue[
+ final ArrayList<Integer> columns = new ArrayList<Integer>();
+ final ArrayList<Integer> rows = new ArrayList<Integer>();
+ for (int i = 0; i < this._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++) {
+ for (int i = 0; i < this._maxValue; i++) {
// Get an index
- int l = random(rows);
- int c = random(columns);
- int index = l * _maxValue + c;
- int symIndex = _symetrizer.getIndex(index);
+ final int l = this.random(rows);
+ final int c = this.random(columns);
+ final int index = l * this._maxValue + c;
+ final int symIndex = this._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)) {
+ int dontRunAllNight = this._maxValue;
+ while (this._initialPosition.isFree(index) && this._initialPosition.isFree(symIndex) && (dontRunAllNight-- > 0)) {
// Try a value
- int value = random(_maxValue);
- if (_initialPosition.isAllowed(index, value)) {
+ int value = this.random(this._maxValue);
+ if (this._initialPosition.isAllowed(index, value)) {
// Play it
- if (_initialPosition.playWhilePossible(index, value)) {
- _count++;
-
+ if (this._initialPosition.playWhilePossible(index, value)) {
// Try for the other one
if (symIndex != index) {
boolean rewind = true;
- for (int maxTry = _maxValue * 2; maxTry > 0; maxTry--) {
- value = random(_maxValue);
+ for (int maxTry = this._maxValue * 2; maxTry > 0; maxTry--) {
+ value = this.random(this._maxValue);
// Try it
- if (_initialPosition.isAllowed(symIndex, value)) {
+ if (this._initialPosition.isAllowed(symIndex, value)) {
// Play it
- if (_initialPosition.playWhilePossible(
- symIndex, value)) {
- _count++;
+ if (this._initialPosition.playWhilePossible(symIndex, value)) {
rewind = false;
break;
} else {
- _initialPosition.clean(symIndex);
+ this._initialPosition.clean(symIndex);
}
}
} // endloop - on maxTry (sym move)
// Rewind ?
if (rewind) {
// Clear it
- _initialPosition.clean(index);
- _initialPosition.clearMarks();
- _count--;
+ this._initialPosition.clean(index);
+ this._initialPosition.clearMarks();
}
} // endif - symIndex != index
} // endif - index was all right
else {
- _initialPosition.clean(index);
+ this._initialPosition.clean(index);
}
} // endif - initial position allowed index
} // endloop - while it's alowed
// System.out.print(" --- " + _count); //$NON-NLS-1$
// Scan for different values
- ArrayList<Integer> candidates = new ArrayList<Integer>();
+ final ArrayList<Integer> candidates = new ArrayList<Integer>();
// Start searchin
- for (int i = 0; i < _maxIndex; i++) {
- if (!_initialPosition.isFree(i)) {
+ for (int i = 0; i < this._maxIndex; i++) {
+ if (!this._initialPosition.isFree(i)) {
// Store it
candidates.add(new Integer(i));
}
}
// Select one
- int index = random(candidates);
+ final int index = this.random(candidates);
- // Remove it
- _count--;
- _initialPosition.clean(index);
+ this._initialPosition.clean(index);
// Remove symetrical
- int symIndex = _symetrizer.getIndex(index);
+ final int symIndex = this._symetrizer.getIndex(index);
if (symIndex != index) {
- _count--;
- _initialPosition.clean(symIndex);
+ this._initialPosition.clean(symIndex);
}
// Clear marks
- _initialPosition.clearMarks();
+ this._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.
+ * 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) {
+ @Override
+ public boolean foundASolution(final State state_p) {
// Is it the first one ?
- if (_solution == null) {
+ if (this._solution == null) {
// Yes it is, store it and look for another one
- _solution = new State(state_p);
+ this._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;
+ this.addAMoveToOriginalPosition(state_p);
+
+ this._solution = null;
+ this._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>.
+ * 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.
+ * @param state_p
+ * another solution to the original position.
*/
- private void addAMoveToOriginalPosition(State state_p) {
+ private void addAMoveToOriginalPosition(final State state_p) {
// Debug
// System.out.print(" +++ " + _count); //$NON-NLS-1$
- //
+ //
// Scan for different values
//
- ArrayList<Integer> candidates = new ArrayList<Integer>();
+ final ArrayList<Integer> candidates = new ArrayList<Integer>();
// Start searching
- for (int i = 0; i < _maxIndex; i++) {
- if (state_p.getValue(i) != _solution.getValue(i)) {
+ for (int i = 0; i < this._maxIndex; i++) {
+ if (state_p.getValue(i) != this._solution.getValue(i)) {
// Store it
candidates.add(new Integer(i));
}
}
// Select one
- int index = random(candidates);
+ final int index = this.random(candidates);
- // Play it
- _count++;
- _initialPosition.play(index, state_p.getValue(index));
+ this._initialPosition.play(index, state_p.getValue(index));
// Play the symetrical one
- int symIndex = _symetrizer.getIndex(index);
+ final int symIndex = this._symetrizer.getIndex(index);
if (symIndex != index) {
- _count++;
- _initialPosition.play(symIndex, state_p.getValue(symIndex));
+ this._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)
+ * (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) {
+ @Override
+ public boolean levelIs(final int level_p, final State state_p) {
// Watch for time limit !
- _opsCount--;
+ this._opsCount--;
// Debug stuff
- if ((_opsCount % 1000000) == 0) {
+ if ((this._opsCount % 1000000) == 0) {
// System.out.print("."); //$NON-NLS-1$
}
// Give up ?
- boolean giveUp = (_opsCount < 0) && (_solution == null);
+ final boolean giveUp = (this._opsCount < 0) && (this._solution == null);
return !giveUp;
}
}
\ No newline at end of file
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.event.ActionEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
+import java.awt.event.InputEvent;
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.JPanel;
import javax.swing.UIManager;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+
/**
- *
- * @author christophe.marchand
+ *
+ * @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);
- }
-
- }
+ 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(final java.awt.Frame parent) {
+ super(parent, false);
+ this.initActions();
+ this.newGame();
+ this.initComponents();
+ }
+
+ protected void initActions() {
+ this.actNew = new AbstractAction() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ DlgCore.this.newGame();
+ }
+ };
+ this.actClose = new AbstractAction() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ DlgCore.this.setVisible(false);
+ }
+ };
+ }
+
+ protected void newGame() {
+ final Builder bd = new Builder();
+ this.grid = new SGrid(new StateModel(bd.buildOne(TemplateFactory.getTemplate(3, 3))));
+ };
+
+ /**
+ * @param args
+ * the command line arguments
+ */
+ public static void main(final String args[]) {
+ java.awt.EventQueue.invokeLater(new Runnable() {
+ @Override
+ public void run() {
+ final DlgCore dialog = new DlgCore(new javax.swing.JFrame());
+ dialog.addWindowListener(new java.awt.event.WindowAdapter() {
+ @Override
+ public void windowClosing(final java.awt.event.WindowEvent e) {
+ System.exit(0);
+ }
+ });
+ dialog.setVisible(true);
+ }
+ });
+ }
+
+ private static boolean isInSameSquare(final int i, final int j, final int row, final 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() {
+
+ this.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+ final StringBuffer sb = new StringBuffer();
+ sb.append(Constants.NOM_APP).append(" S").append("u").append("d").append("o").append("k").append("u");
+ this.setTitle(sb.toString());
+
+ final org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this.getContentPane());
+ this.getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(layout.createSequentialGroup().addContainerGap().add(this.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(this.grid, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 320, Short.MAX_VALUE).addContainerGap()));
+
+ this.pack();
+ }
+
+ /**
+ * @param args
+ * the command line arguments
+ */
+ // Variables declaration - do not modify
+ private class SGrid extends JPanel {
+ SCase grid[][];
+ private final StateModel sm;
+
+ public SGrid(final StateModel sm) {
+ super();
+ this.sm = sm;
+ this.initComponents();
+ }
+
+ @Override
+ public int getHeight() {
+ return super.getWidth();
+ }
+
+ protected void initComponents() {
+ this.setLayout(new GridLayout(9, 9, 0, 0));
+ this.grid = new SCase[9][9];
+ for (int i = 0; i < 9; i++) {
+ for (int j = 0; j < 9; j++) {
+ this.grid[i][j] = new SCase(this.sm, this, i, j);
+ this.add(this.grid[i][j]);
+ }
+ }
+ }
+
+ public void notifyFocusGained(final int row, final int col) {
+ for (int i = 0; i < 9; i++) {
+ for (int j = 0; j < 9; j++) {
+ this.grid[i][j].setSelected(i == row || j == col || isInSameSquare(i, j, row, col));
+ this.grid[i][j].setHadFocus(row == i && col == j);
+ }
+ }
+ this.paintImmediately(new Rectangle(0, 0, this.getWidth(), this.getHeight()));
+ }
+
+ public void checkGridFinished() {
+ boolean gridFilled = true;
+ for (int i = 0; i < 9; i++) {
+ if (!gridFilled) {
+ break;
+ }
+ for (int j = 0; j < 9; j++) {
+ final String s = this.sm.getValueAt(i, j);
+ if (s == null) {
+ gridFilled = false;
+ break;
+ }
+ }
+ }
+ if (gridFilled) {
+ JOptionPane.showMessageDialog(this.getParent(), "Félicitations !");
+ }
+ }
+
+ public void highLight(final String s) {
+ for (int i = 0; i < 9; i++) {
+ for (int j = 0; j < 9; j++) {
+ this.grid[i][j].setSelected(this.sm.getValueAt(i, j) == null);
+ }
+ }
+ for (int i = 0; i < 9; i++) {
+ for (int j = 0; j < 9; j++) {
+ if (s.equals(this.sm.getValueAt(i, j))) {
+ for (int k = 0; k < 9; k++) {
+ this.grid[i][k].setSelected(false);
+ this.grid[k][j].setSelected(false);
+ }
+ final int xStart = (int) Math.floor(i / 3.0f) * 3;
+ final int yStart = (int) Math.floor(j / 3.0f) * 3;
+ final int xEnd = xStart + 3;
+ final int yEnd = yStart + 3;
+ for (int i1 = xStart; i1 < xEnd; i1++) {
+ for (int j1 = yStart; j1 < yEnd; j1++) {
+ this.grid[i1][j1].setSelected(false);
+ }
+ }
+ }
+ }
+ }
+ this.paintImmediately(new Rectangle(0, 0, this.getWidth(), this.getHeight()));
+ }
+ }
+
+ private class SCase extends JComponent {
+ private final StateModel sm;
+ private final int row, col;
+ private boolean selected = false;
+ private final 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;
+ this.addKeyListener(new KeyAdapter() {
+ @Override
+ public void keyTyped(final KeyEvent e) {
+ if ((e.getModifiersEx() & InputEvent.CTRL_DOWN_MASK) > 0) {
+ final 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();
+ SCase.this.repaint();
+ grid.checkGridFinished();
+ } else if (e.getKeyChar() == ' ' || e.getKeyChar() == 127 || e.getKeyChar() == 8) {
+ sm.setValueAt(row, col, " ");
+ e.consume();
+ SCase.this.repaint();
+ }
+ }
+ }
+
+ @Override
+ public void keyPressed(final 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();
+ }
+ }
+ }
+ });
+ this.addMouseListener(new MouseAdapter() {
+
+ @Override
+ public void mouseClicked(final MouseEvent e) {
+ SCase.this.requestFocus();
+ }
+ });
+ this.addFocusListener(new FocusAdapter() {
+ @Override
+ public void focusGained(final FocusEvent e) {
+ grid.notifyFocusGained(row, col);
+ }
+ });
+ }
+
+ @Override
+ public void paint(final Graphics g) {
+ if (this.selected) {
+ g.setColor(UIManager.getColor("TextField.selectionBackground")); //
+ } else {
+ g.setColor(UIManager.getColor("TextField.background")); // UIManager.getColor("background")
+ }
+ g.fillRect(1, 1, this.getWidth() - 1, this.getHeight() - 1);
+ if (this.hasFocus() | this.isTopComponentFocused()) {
+ g.setColor(Color.GRAY);
+ } else {
+ g.setColor(Color.BLACK);
+ }
+ // cadre supérieur
+ g.drawLine(0, 0, this.getWidth() - 1, 0);
+ if (this.hasFocus() | this.isLeftComponentFocused()) {
+ g.setColor(Color.GRAY);
+ } else {
+ g.setColor(Color.BLACK);
+ }
+ // cadre gauche
+ g.drawLine(0, 0, 0, this.getHeight() - 1);
+ if (this.row % 3 == 2) {
+ if (this.isRightComponentFocused()) {
+ g.setColor(Color.GRAY);
+ } else {
+ g.setColor(Color.BLACK);
+ }
+ g.drawLine(0, this.getHeight() - 1, this.getWidth() - 1, this.getHeight() - 1);
+ }
+ if (this.col % 3 == 2) {
+ if (this.isBottomComponentFocused()) {
+ g.setColor(Color.GRAY);
+ } else {
+ g.setColor(Color.BLACK);
+ }
+ g.drawLine(this.getWidth() - 1, 0, this.getWidth() - 1, this.getHeight() - 1);
+ }
+ if (this.sm.getValueAt(this.row, this.col) != null) {
+ final Font originalF = g.getFont();
+ g.setColor(Color.BLACK);
+ final Font ft = g.getFont();
+ Font nf = ft.deriveFont(this.getHeight() * 0.5f);
+ if (this.sm.isWritable(this.row, this.col)) {
+ nf = nf.deriveFont(Font.ITALIC);
+ }
+ g.setFont(nf);
+ final String s = this.sm.getValueAt(this.row, this.col);
+ final Rectangle2D rect = g.getFontMetrics().getStringBounds(s, g);
+ g.drawString(s, (int) ((this.getWidth() - rect.getWidth()) / 2), (int) ((this.getHeight() - rect.getHeight() / 2)));
+ g.setFont(originalF);
+ }
+ }
+
+ public void setSelected(final boolean selected) {
+ this.selected = selected;
+ }
+
+ public void setHadFocus(final boolean hadFocus) {
+ }
+
+ public boolean isBottomComponentFocused() {
+ if (this.row == 8) {
+ return false;
+ }
+ return this.grid.grid[this.row + 1][this.col].hasFocus();
+ }
+
+ public boolean isRightComponentFocused() {
+ if (this.col == 8) {
+ return false;
+ }
+ return this.grid.grid[this.row][this.col + 1].hasFocus();
+ }
+
+ public boolean isLeftComponentFocused() {
+ if (this.col == 0) {
+ return false;
+ }
+ return this.grid.grid[this.row][this.col - 1].hasFocus();
+ }
+
+ public boolean isTopComponentFocused() {
+ if (this.row == 0) {
+ return false;
+ }
+ return this.grid.grid[this.row - 1][this.col].hasFocus();
+ }
+
+ @Override
+ public Dimension getMinimumSize() {
+ return new Dimension(20, 20);
+ }
+
+ }
}
* @author Tchok
*/
public interface ISolverListener {
- /** Called when a solution is found.
- * @param state_p the solution
+ /**
+ * 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.
+
+ /**
+ * Called when level changes. return false to stop scanning.
*/
public boolean levelIs(int level_p, State state_p);
}
/**
* Dummy case, no symetrie at all...
+ *
* @author Tchok
*/
public class NoSymetrizer extends Symetrizer {
- public NoSymetrizer(Template template_p) {
+ public NoSymetrizer(final Template template_p) {
super(template_p);
}
@Override
- public int getIndex(int index_p) {
+ public int getIndex(final int index_p) {
return index_p;
}
}
public class RandomTool {
/**
- * Just select, remove and return a value from a list
- * @param list_p of Integer !
+ * Just select, remove and return a value from a list
+ *
+ * @param list_p
+ * of Integer !
* @return
*/
- int random(ArrayList<Integer> list_p) {
+ int random(final ArrayList<Integer> list_p) {
// Get it
- Integer value = list_p.remove(random(list_p.size()));
+ final Integer value = list_p.remove(this.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);
+ int random(final int max_p) {
+ return (int) (Math.random() * max_p);
}
}
package fr.gouv.finances.cp.xemelios.ui.ia.core;
-
/**
* @author Tchok
*/
public class Solver {
- // All the states
+ // 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;
+ public Solver(final ISolverListener listener_p) {
+ this._listener = listener_p;
}
-
+
/** Do solve it. */
- public void solve(State state_p) {
+ public void solve(final State state_p) {
// get template
- _maxIndex = state_p.getTemplate().maxIndex;
- _maxValue = state_p.getTemplate().maxValue;
-
+ this._maxIndex = state_p.getTemplate().maxIndex;
+ this._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());
+ this._states = new State[this._maxIndex + 1];
+ for (int i = 0; i < this._states.length; i++) {
+ this._states[i] = new State(state_p.getTemplate());
}
-
+
// And get going
- _states[0].loadFrom(state_p);
- study(0);
+ this._states[0].loadFrom(state_p);
+ this.study(0);
}
/**
* Study a specific index
+ *
* @param index_p
* @return true to keep going, false to stop
*/
- private boolean study(int index_p) {
-
+ private boolean study(final int index_p) {
+
// Get it
- State state = _states[index_p];
-
+ final State state = this._states[index_p];
+
// Not too far
- if(index_p == _maxIndex) {
- return _listener.foundASolution(state);
+ if (index_p == this._maxIndex) {
+ return this._listener.foundASolution(state);
}
-
+
// Warn listener
- if(!_listener.levelIs(index_p, state)) {
+ if (!this._listener.levelIs(index_p, state)) {
return false;
}
// is it free ?
- if(state.isFree(index_p)) {
+ if (state.isFree(index_p)) {
// We'll have to study it all
- for(int value=0; value<_maxValue; value++) {
+ for (int value = 0; value < this._maxValue; value++) {
// is it allowed ?
- if(state.isAvailable(index_p, value)) {
+ 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);
-
+ this._states[index_p + 1].loadFrom(state);
+ boolean answer = this._states[index_p + 1].playWhilePossible(index_p, value);
+
// Recurse ?
- if(!answer) {
+ if (!answer) {
continue;
}
-
+
// Recurse
- answer = study(index_p+1);
- if(!_listener.levelIs(index_p, state)) {
+ answer = this.study(index_p + 1);
+ if (!this._listener.levelIs(index_p, state)) {
return false;
}
-
+
// So what ?
- if(!answer) {
+ 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);
+ this._states[index_p + 1].loadFrom(state);
+ return this.study(index_p + 1);
}
}
import java.io.ObjectOutputStream;
import java.io.Serializable;
-
/**
* @author Tchok
*/
*/
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
+ /**
+ * 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.*/
+
+ /** This board's template. */
protected Template _template = Template.T33;
-
- /** Creates an emty board.*/
- public State(Template template_p) {
+
+ /** Creates an emty board. */
+ public State(final Template template_p) {
// Store
- _template = template_p;
-
+ this._template = template_p;
+
// Allocate
- _states = _template.allocate();
-
+ this._states = this._template.allocate();
+
// All clear
- for (int i = 0; i < _template.maxIndex; i++) {
- _states[i] = _template.INITIAL_VALUE;
+ for (int i = 0; i < this._template.maxIndex; i++) {
+ this._states[i] = this._template.INITIAL_VALUE;
}
}
-
- public State(State state_p) {
+
+ public State(final State state_p) {
// Init
- _template = state_p._template;
-
+ this._template = state_p._template;
+
// Allocate
- _states = _template.allocate();
-
+ this._states = this._template.allocate();
+
// And copy
- loadFrom(state_p);
+ this.loadFrom(state_p);
}
-
+
/** Load values. */
- public void loadFrom(State state_p) {
+ public void loadFrom(final State state_p) {
// Just copy it
- System.arraycopy(state_p._states, 0, _states, 0, _states.length);
+ System.arraycopy(state_p._states, 0, this._states, 0, this._states.length);
}
/**
* Play by modifying this state.
+ *
* @param index_p
* @param value_p
*/
- public void play(int index_p, int value_p) {
+ public void play(final int index_p, final 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);
-
+ this.clearBits(index_p, this._template.VALUE_MASK);
+ this.clearBits(index_p, this._template.ALL_AVAILABLE_EXTRACTOR);
+ this.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);
+ final int[][] indexes = this._template.NEIGHBOURGHOODS[index_p];
+ final int extractor = this._template.VALUE_AVAILABLE_EXTRACTOR[value_p];
+ for (int value = 0; value < this._template.maxValue; value++) {
+ for (int cIndex = 0; cIndex < 3; cIndex++) { // LINE/COL/BOXES
+ this.clearBits(indexes[cIndex][value], extractor);
}
}
}
/**
- * Play by modifying this state.
- * Stops when a position without allowed move is detected.
+ * 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) {
+ public boolean playWhilePossible(final int index_p, final 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);
-
+ this.clearBits(index_p, this._template.VALUE_MASK | this._template.ALL_AVAILABLE_EXTRACTOR);
+ this.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);
+ final int[][] indexes = this._template.NEIGHBOURGHOODS[index_p];
+ final int extractor = this._template.VALUE_AVAILABLE_EXTRACTOR[value_p];
+ for (int value = 0; value < this._template.maxValue; value++) {
+ for (int cIndex = 0; cIndex < 3; cIndex++) { // LINE/COL/BOXES
+ final int finalIndex = indexes[cIndex][value];
+ this.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)) {
+ if (this.isFree(finalIndex) && ((this._states[finalIndex] & this._template.ALL_AVAILABLE_EXTRACTOR) == 0)) {
return false;
}
}
}
-
+
// OK
return true;
- }
-
- public void clean(int index_p) {
+ }
+
+ public void clean(final int index_p) {
// Let's get a copy of the current position
- State clean = new State(_template);
-
+ final State clean = new State(this._template);
+
// Let's clean the requested position
- markBits(index_p, _template.FREE_VALUE);
-
+ this.markBits(index_p, this._template.FREE_VALUE);
+
// And start rebuilding
- for(int i = 0; i<_template.maxIndex; i++) {
+ for (int i = 0; i < this._template.maxIndex; i++) {
// Check it
- if(!isFree(i)) {
- clean.play(i, getValue(i));
+ if (!this.isFree(i)) {
+ clean.play(i, this.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);
+ clean.markBits(i, this._states[i] & this._template.ORIGINAL_POSITION);
+ clean.markBits(i + this._template.MARK1_OFFSET, this._states[i + this._template.MARK1_OFFSET] & this._template.MARK_MASK);
+ clean.markBits(i + this._template.MARK2_OFFSET, this._states[i + this._template.MARK2_OFFSET] & this._template.MARK_MASK);
}
-
+
// get new values
- _states = clean._states;
+ this._states = clean._states;
}
-
- /** Check if free.*/
- public boolean isFree(int index_p) {
- return checkBit(index_p, _template.FREE_VALUE);
+
+ /** Check if free. */
+ public boolean isFree(final int index_p) {
+ return this.checkBit(index_p, this._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]);
+ public boolean isAllowed(final int index_p, final int value_p) {
+ return this.checkBit(index_p, this._template.VALUE_AVAILABLE_EXTRACTOR[value_p]);
}
-
- /** Get a value.
+
+ /**
+ * 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;
+ public int getValue(final int index_p) {
+ return this._states[index_p] & this._template.VALUE_MASK;
}
-
+
/**
- * @param index case
- * @param value to scan for
+ * @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) {
+ public int getMark(final int index_p, final int value_p) {
// Output
int output = 0;
-
+
// Read mark 1
- if(checkBit(index_p + _template.MARK1_OFFSET, _template.MARK1_EXTRACTOR[value_p])) {
+ if (this.checkBit(index_p + this._template.MARK1_OFFSET, this._template.MARK1_EXTRACTOR[value_p])) {
output = Template.STRIKE;
}
-
+
// Read mark 2
- if(checkBit(index_p + _template.MARK2_OFFSET, _template.MARK2_EXTRACTOR[value_p])) {
+ if (this.checkBit(index_p + this._template.MARK2_OFFSET, this._template.MARK2_EXTRACTOR[value_p])) {
output += Template.HIGHLIGHT;
}
-
+
// Ok
return output;
}
-
- public void setMark(int index_p, int value_p, int mark_p) {
+
+ public void setMark(final int index_p, final int value_p, final int mark_p) {
// Mark 1
- if((mark_p & 1) != 0) {
- markBits(index_p + _template.MARK1_OFFSET, _template.MARK1_EXTRACTOR[value_p]);
+ if ((mark_p & 1) != 0) {
+ this.markBits(index_p + this._template.MARK1_OFFSET, this._template.MARK1_EXTRACTOR[value_p]);
} else {
- clearBits(index_p + _template.MARK1_OFFSET, _template.MARK1_EXTRACTOR[value_p]);
+ this.clearBits(index_p + this._template.MARK1_OFFSET, this._template.MARK1_EXTRACTOR[value_p]);
}
-
+
// Mark 2
- if((mark_p & 2) != 0) {
- markBits(index_p + _template.MARK2_OFFSET, _template.MARK2_EXTRACTOR[value_p]);
+ if ((mark_p & 2) != 0) {
+ this.markBits(index_p + this._template.MARK2_OFFSET, this._template.MARK2_EXTRACTOR[value_p]);
} else {
- clearBits(index_p + _template.MARK2_OFFSET, _template.MARK2_EXTRACTOR[value_p]);
+ this.clearBits(index_p + this._template.MARK2_OFFSET, this._template.MARK2_EXTRACTOR[value_p]);
}
}
-
- /** Mark this has the original position .*/
+
+ /** Mark this has the original position . */
public void registerOriginalPosition() {
- for(int index=0; index<_template.maxIndex; index++) {
+ for (int index = 0; index < this._template.maxIndex; index++) {
// If free
- if(isFree(index)) {
- clearBits(index, _template.ORIGINAL_POSITION);
+ if (this.isFree(index)) {
+ this.clearBits(index, this._template.ORIGINAL_POSITION);
} else {
- markBits(index, _template.ORIGINAL_POSITION);
+ this.markBits(index, this._template.ORIGINAL_POSITION);
}
}
}
-
- public boolean isOriginalPosition(int index_p) {
- return checkBit(index_p, _template.ORIGINAL_POSITION);
+
+ public boolean isOriginalPosition(final int index_p) {
+ return this.checkBit(index_p, this._template.ORIGINAL_POSITION);
}
public Template getTemplate() {
- return _template;
+ return this._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;
+ private boolean checkBit(final int index_p, final int bit_p) {
+ return (this._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;
+ /** clear bits . */
+ private void clearBits(final int index_p, final int bits_p) {
+ this._states[index_p] = this._states[index_p] & ~bits_p;
}
/** Mark a position. */
- private void markBits(int index, int bits_p) {
- _states[index] = _states[index] | bits_p;
+ private void markBits(final int index, final int bits_p) {
+ this._states[index] = this._states[index] | bits_p;
}
int[] getRaw() {
- return _states;
+ return this._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);
+ public boolean isAvailable(final int index_p, final int value_p) {
+ return this.isFree(index_p) && this.isAllowed(index_p, value_p) && ((this.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);
+ for (int index = 0; index < this._template.maxIndex; index++) {
+ this.clearBits(index + this._template.MARK1_OFFSET, this._template.MARK_MASK);
+ this.clearBits(index + this._template.MARK2_OFFSET, this._template.MARK_MASK);
}
-
+
}
-
+
/**
* This is a custom Serialization (for the fun of it).
- * @param out_p output stream
+ *
+ * @param out_p
+ * output stream
* @throws IOException
*/
- private void writeObject(ObjectOutputStream out_p) throws IOException {
+ private void writeObject(final ObjectOutputStream out_p) throws IOException {
// We'll write template, then states
// Template
- out_p.writeShort(_template.rows);
- out_p.writeShort(_template.columns);
-
+ out_p.writeShort(this._template.rows);
+ out_p.writeShort(this._template.columns);
+
// And states
- for (int i = 0; i < _states.length; i++) {
- int aValue = _states[i];
+ for (final int aValue : this._states) {
out_p.writeInt(aValue);
}
}
-
+
/**
* This is a custom serialization.
- * @param in_p stream to read from.
+ *
+ * @param in_p
+ * stream to read from.
* @throws IOException
* @throws ClassNotFoundException
*/
@SuppressWarnings("unused")
- private void readObject(java.io.ObjectInputStream in_p) throws IOException, ClassNotFoundException {
+ private void readObject(final 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);
-
+ final int rows = in_p.readShort();
+ final int columns = in_p.readShort();
+ this._template = TemplateFactory.getTemplate(rows, columns);
+
// Allocate
- _states = _template.allocate();
-
+ this._states = this._template.allocate();
+
// read state
- for (int i = 0; i < _states.length; i++) {
- _states[i] = in_p.readInt();
+ for (int i = 0; i < this._states.length; i++) {
+ this._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();
-// }
+ // 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();
+ // }
}
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;
- }
- }
- }
+ private final State state;
+ private LocationInformation[][] locations;
+
+ public StateModel(final State state) {
+ super();
+ this.state = state;
+ this.initialize();
+ }
+
+ protected void initialize() {
+ final int size = this.getGridWidth();
+ this.locations = new LocationInformation[size][size];
+ final Template t = this.state.getTemplate();
+ final String[][] array = new String[t.maxValue][t.maxValue];
+ for (int index = 0; index < t.maxIndex; index++) {
+ final int row = t.indexToRow(index);
+ final int col = t.indexToColumn(index);
+ // if(row<)
+ if (!this.state.isFree(index)) {
+ this.locations[row][col] = new LocationInformation(this.state.getValue(index) + 1);
+ // Integer.toString(st.getValue(index)+1);
+ } else {
+ this.locations[row][col] = new LocationInformation(-1);
+ }
+ }
+ }
+
+ public boolean isWritable(final int row, final int col) {
+ return !this.locations[row][col].isOriginal();
+ }
+
+ // public boolean isFree(int row, int col) { return state.isFree(locations[row][col].getIndex()); }
+ public boolean isValueAllowed(final int row, final int col, final String value) {
+ try {
+ // return state.isAllowed(locations[row][col].getIndex(), Integer.valueOf(value));
+ final 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(this.locations[i][col].getValue())) {
+ return false;
+ }
+ if (i != col && value.equals(this.locations[row][i].getValue())) {
+ return false;
+ }
+ }
+ final int sqStartRow = (row / 3) * 3;
+ final 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(this.locations[i][j].getValue())) {
+ return false;
+ }
+ }
+ }
+ return true;
+ } else {
+ return false;
+ }
+ } catch (final Exception ex) {
+ return false;
+ }
+ }
+
+ public void setValueAt(final int row, final int col, final String value) {
+ this.locations[row][col].setValue(value);
+ }
+
+ public String getValueAt(final int row, final int col) {
+ return this.locations[row][col].getValue();
+ }
+
+ public int getGridWidth() {
+ return this.state.getTemplate().maxValue;
+ }
+
+ public int getGridHeight() {
+ return this.getGridWidth();
+ }
+
+ private class LocationInformation {
+ // private int stateIndex;
+ private boolean original = false;
+ private int value = -1;
+
+ public LocationInformation(final int value) {
+ super();
+ this.value = value;
+ this.original = (value != -1);
+ }
+
+ public boolean isOriginal() {
+ return this.original;
+ }
+
+ public boolean isWrittable() {
+ return !this.isOriginal();
+ }
+
+ public String getValue() {
+ if (this.value != -1) {
+ return Integer.toString(this.value);
+ }
+ return null;
+ }
+
+ public void setValue(final String v) {
+ try {
+ this.value = Integer.parseInt(v);
+ } catch (final Exception ex) {
+ this.value = -1;
+ }
+ }
+ }
}
/**
* Given an index, gives back the symetrical index.
+ *
* @author Tchok
*/
public class Symetrizer {
Template _template;
-
- public Symetrizer(Template template_p) {
- _template = template_p;
+
+ public Symetrizer(final Template template_p) {
+ this._template = template_p;
}
-
+
/**
* Computes the symetrical index.
- * @param index_p source index
+ *
+ * @param index_p
+ * source index
* @return target index.
*/
- public int getIndex(int index_p) {
- //return index_p;
- return _template.maxIndex - (index_p + 1);
+ public int getIndex(final int index_p) {
+ // return index_p;
+ return this._template.maxIndex - (index_p + 1);
}
}
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:
+ * 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)
* 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 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 if reducer is allowed. */
public final boolean reducable;
-
+
// Common name
public final String name;
-
+
// Initial value
int INITIAL_VALUE;
// To check if a value is allowed
int VALUE_AVAILABLE_EXTRACTOR[];
-
+
// Available extractor
int ALL_AVAILABLE_EXTRACTOR;
// 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>
- **/
+
+ /**
+ * 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;
-
+ this.VALUE_MASK = 15;
+
// Max value is 9 so we may use 15
- FREE_VALUE = 15;
-
+ this.FREE_VALUE = 15;
+
// Bit 5 is for the 'original position' marker
- ORIGINAL_POSITION = 1 << 4;
-
+ this.ORIGINAL_POSITION = 1 << 4;
+
// Byte offset to reach markers
- MARK1_OFFSET = 0;
- MARK2_OFFSET = 0;
+ this.MARK1_OFFSET = 0;
+ this.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
+ /**
+ * 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) {
+ protected Template(final int row_p, final int column_p, final boolean symetrical_p, final boolean reducable_p) {
// Store shape
- columns = column_p;
- rows = row_p;
- symetrical = symetrical_p;
- reducable = reducable_p;
-
+ this.columns = column_p;
+ this.rows = row_p;
+ this.symetrical = symetrical_p;
+ this.reducable = reducable_p;
+
// Build name
- name = new String(column_p + "x" + row_p); //$NON-NLS-1$
-
+ this.name = new String(column_p + "x" + row_p); //$NON-NLS-1$
+
// Simple extra computation
- maxValue = row_p * column_p;
- maxIndex = maxValue * maxValue;
-
+ this.maxValue = row_p * column_p;
+ this.maxIndex = this.maxValue * this.maxValue;
+
// Fill constants
- fillBaseFields();
+ this.fillBaseFields();
// Fill value extractors
- fillValueExtractors();
-
+ this.fillValueExtractors();
+
// Fill mark extractor
- fillMarkExtractors();
-
+ this.fillMarkExtractors();
+
// Fill neighbourghoods
- fillNeigbourghoods();
+ this.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];
+ this.MARK1_EXTRACTOR = new int[this.maxValue];
+ this.MARK2_EXTRACTOR = new int[this.maxValue];
+ this.MARK_MASK = 0;
+ for (int i = 0; i < this.maxValue; i++) {
+ this.MARK1_EXTRACTOR[i] = 1 << (14 + i);
+ this.MARK2_EXTRACTOR[i] = 1 << (23 + i);
+ this.MARK_MASK |= this.MARK1_EXTRACTOR[i];
+ this.MARK_MASK |= this.MARK2_EXTRACTOR[i];
}
}
-
- protected void fillValueExtractors() {
+
+ 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];
+ this.INITIAL_VALUE = this.FREE_VALUE;
+ this.ALL_AVAILABLE_EXTRACTOR = 0;
+ this.VALUE_AVAILABLE_EXTRACTOR = new int[this.maxValue];
+ for (int i = 0; i < this.VALUE_AVAILABLE_EXTRACTOR.length; i++) {
+ this.VALUE_AVAILABLE_EXTRACTOR[i] = 1 << (i + 5);
+ this.INITIAL_VALUE |= this.VALUE_AVAILABLE_EXTRACTOR[i];
+ this.ALL_AVAILABLE_EXTRACTOR |= this.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;
+ this.LINE_NEIGHBOURGHOOD = new int[this.maxValue][this.maxValue];
+ this.INDEX_TO_LINE = new int[this.maxIndex];
+ for (int line = 0; line < this.maxValue; line++) {
+ for (int col = 0; col < this.maxValue; col++) {
+ final int index = line * this.maxValue + col;
+ this.LINE_NEIGHBOURGHOOD[line][col] = index;
+ this.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;
+ this.COLUMNS_NEIGBOURGHOOD = new int[this.maxValue][this.maxValue];
+ this.INDEX_TO_COLUMN = new int[this.maxIndex];
+ for (int line = 0; line < this.maxValue; line++) {
+ for (int col = 0; col < this.maxValue; col++) {
+ final int index = line * this.maxValue + col;
+ this.COLUMNS_NEIGBOURGHOOD[col][line] = index;
+ this.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++) {
+ this.BOXES_NEIGBOURGHOOD = new int[this.maxValue][this.maxValue];
+ this.INDEX_TO_BOX = new int[this.maxIndex];
+ for (int boxLine = 0; boxLine < this.columns; boxLine++) {
+ for (int boxCol = 0; boxCol < this.rows; boxCol++) {
// Loop in box
- int boxIndex = boxLine * rows + boxCol;
- for(int line=0; line<rows; line++) {
- for(int col=0; col<columns; col++) {
+ final int boxIndex = boxLine * this.rows + boxCol;
+ for (int line = 0; line < this.rows; line++) {
+ for (int col = 0; col < this.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;
+ final int indexInBox = line * this.columns + col;
+ final int index = (boxLine * this.rows + line) * this.maxValue + boxCol * this.columns + col;
+ this.BOXES_NEIGBOURGHOOD[boxIndex][indexInBox] = index;
+ this.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]];
+ this.NEIGHBOURGHOODS = new int[this.maxIndex][3][this.maxValue];
+ for (int index = 0; index < this.maxIndex; index++) {
+ this.NEIGHBOURGHOODS[index][0] = this.LINE_NEIGHBOURGHOOD[this.INDEX_TO_LINE[index]];
+ this.NEIGHBOURGHOODS[index][1] = this.COLUMNS_NEIGBOURGHOOD[this.INDEX_TO_COLUMN[index]];
+ this.NEIGHBOURGHOODS[index][2] = this.BOXES_NEIGBOURGHOOD[this.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;
+ public int indexToRow(final int index_p) {
+ return index_p / this.maxValue;
}
-
+
/**
* Convert index to column
+ *
* @param index_p
* @return
*/
- public int indexToColumn(int index_p) {
- return index_p % maxValue;
+ public int indexToColumn(final int index_p) {
+ return index_p % this.maxValue;
}
-
+
/**
* Convert index to box index.
+ *
* @param index_p
* @return
*/
- public int indexToBox(int index_p) {
+ public int indexToBox(final int index_p) {
// Get basic
- int line = indexToRow(index_p);
- int col = indexToColumn(index_p);
-
+ int line = this.indexToRow(index_p);
+ int col = this.indexToColumn(index_p);
+
// Transform to box indexes
- line = line / rows;
- col = col / columns;
-
+ line = line / this.rows;
+ col = col / this.columns;
+
// Compute box index
- return line * rows + col;
+ return line * this.rows + col;
}
-
+
/**
* @return memory to keep a state.
*/
- public int [] allocate() {
- return new int[maxIndex];
+ public int[] allocate() {
+ return new int[this.maxIndex];
}
}
/**
* handles the available templates
+ *
* @author Tchok
*/
public class TemplateFactory {
- static public final Template TEMPLATES[] = {
- Template.T22,
- Template.T23,
-// Template.T32,
- Template.T33,
- WideTemplate.T34
- };
+ 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
+ *
+ * @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) {
+ public static Template getTemplate(final int row_p, final 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)) {
+ for (final Template template : TEMPLATES) {
+ if ((template.rows == row_p) && (template.columns == column_p)) {
// This is it
return template;
}
}
-
+
// Bad luck !
return null;
}
/**
* 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.
+ * 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)
* 33-58 : mark 1 (stripe 2)
* 96-121: mark 2 (stripe 3)
* </PRE>
-
+ *
* @author Tchok
*/
public class WideTemplate extends Template {
// 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) {
+ public WideTemplate(final int row_p, final 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;
-
+ this.VALUE_MASK = 31;
+
// Max value is 25 so we may use 31
- FREE_VALUE = 31;
-
+ this.FREE_VALUE = 31;
+
// Bit 6 is for the 'original position' marker
- ORIGINAL_POSITION = 1 << 5;
-
+ this.ORIGINAL_POSITION = 1 << 5;
+
// Byte offset to reach markers
- MARK1_OFFSET = maxIndex;
- MARK2_OFFSET = 2 * maxIndex;
+ this.MARK1_OFFSET = this.maxIndex;
+ this.MARK2_OFFSET = 2 * this.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];
+ this.MARK1_EXTRACTOR = new int[this.maxValue];
+ this.MARK2_EXTRACTOR = new int[this.maxValue];
+ this.MARK_MASK = 0;
+ for (int i = 0; i < this.maxValue; i++) {
+ this.MARK1_EXTRACTOR[i] = 1 << i;
+ this.MARK2_EXTRACTOR[i] = 1 << i;
+ this.MARK_MASK |= this.MARK1_EXTRACTOR[i];
+ this.MARK_MASK |= this.MARK2_EXTRACTOR[i];
}
}
-
+
@Override
- protected void fillValueExtractors() {
+ 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];
+ this.INITIAL_VALUE = this.FREE_VALUE;
+ this.ALL_AVAILABLE_EXTRACTOR = 0;
+ this.VALUE_AVAILABLE_EXTRACTOR = new int[this.maxValue];
+ for (int i = 0; i < this.VALUE_AVAILABLE_EXTRACTOR.length; i++) {
+ this.VALUE_AVAILABLE_EXTRACTOR[i] = 1 << (i + 6);
+ this.INITIAL_VALUE |= this.VALUE_AVAILABLE_EXTRACTOR[i];
+ this.ALL_AVAILABLE_EXTRACTOR |= this.VALUE_AVAILABLE_EXTRACTOR[i];
}
}
-
/**
* @return memory to keep a state.
*/
@Override
- public int [] allocate() {
- return new int[maxIndex * 3];
+ public int[] allocate() {
+ return new int[this.maxIndex * 3];
}
}
\ No newline at end of file
package fr.gouv.finances.cp.xemelios.ui.importArchive;
-import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
-import fr.gouv.finances.cp.xemelios.importers.ImportServiceSwingProvider;
-import fr.gouv.finances.cp.xemelios.ui.MainWindow;
-import fr.gouv.finances.dgfip.xemelios.common.Constants;
-import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
-import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
-import fr.gouv.finances.dgfip.xemelios.importers.EtatImporteur;
-import fr.gouv.finances.dgfip.xemelios.importers.archives.ArchiveImporter;
-import fr.gouv.finances.dgfip.xemelios.importers.archives.rules.ActionsModel;
-import fr.gouv.finances.dgfip.xemelios.importers.archives.rules.AttributeModel;
-import fr.gouv.finances.dgfip.xemelios.importers.archives.rules.FilterModel;
-import fr.gouv.finances.dgfip.xemelios.importers.archives.rules.ImportModel;
-import fr.gouv.finances.dgfip.xemelios.importers.archives.rules.PredicatModel;
-import fr.gouv.finances.dgfip.xemelios.importers.archives.rules.RulesModel;
-import fr.gouv.finances.dgfip.xemelios.importers.archives.rules.SectionModel;
-import fr.gouv.finances.dgfip.xemelios.importers.archives.rules.DeleteModel;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
+
import javax.swing.JComponent;
+
import nu.xom.Builder;
import nu.xom.Document;
+
import org.apache.log4j.Logger;
import org.netbeans.api.wizard.WizardDisplayer;
import org.netbeans.spi.wizard.Wizard;
import org.netbeans.spi.wizard.WizardController;
import org.netbeans.spi.wizard.WizardPanelProvider;
+import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
+import fr.gouv.finances.cp.xemelios.importers.ImportServiceSwingProvider;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
+import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
+import fr.gouv.finances.dgfip.xemelios.importers.EtatImporteur;
+import fr.gouv.finances.dgfip.xemelios.importers.archives.ArchiveImporter;
+import fr.gouv.finances.dgfip.xemelios.importers.archives.rules.ActionsModel;
+import fr.gouv.finances.dgfip.xemelios.importers.archives.rules.AttributeModel;
+import fr.gouv.finances.dgfip.xemelios.importers.archives.rules.DeleteModel;
+import fr.gouv.finances.dgfip.xemelios.importers.archives.rules.FilterModel;
+import fr.gouv.finances.dgfip.xemelios.importers.archives.rules.ImportModel;
+import fr.gouv.finances.dgfip.xemelios.importers.archives.rules.PredicatModel;
+import fr.gouv.finances.dgfip.xemelios.importers.archives.rules.RulesModel;
+import fr.gouv.finances.dgfip.xemelios.importers.archives.rules.SectionModel;
+
/**
*
* @author cmarchand
private File archiveFile;
private MainWindow parent;
- public ArchiveWizardDisplayer(MainWindow parent, File archiveFile) {
+ public ArchiveWizardDisplayer(final MainWindow parent, final File archiveFile) {
super();
this.parent = parent;
this.archiveFile = archiveFile;
response.put("choose.action.full.import", Boolean.TRUE);
response.put("unset.overwrite", Boolean.TRUE);
} else {
- wizardProperties = loadInitialProperties();
- WizardBranchController wbc = new MyWizardBranchController(new WizardPanelProvider("Choix de l'action", "initial", "Choix de l'action à effectuer") {
+ wizardProperties = this.loadInitialProperties();
+ final WizardBranchController wbc = new MyWizardBranchController(new WizardPanelProvider("Choix de l'action", "initial", "Choix de l'action à effectuer") {
@Override
- protected JComponent createPanel(WizardController wc, String string, Map map) {
+ protected JComponent createPanel(final WizardController wc, final String string, final Map map) {
return new PnlChooseAction();
}
});
- Wizard wizard = wbc.createWizard();
+ final Wizard wizard = wbc.createWizard();
response = (Map) WizardDisplayer.showWizard(wizard, null, null, wizardProperties);
}
-
+
if (response == null) {
logger.info("import abandonné");
} else {
logger.info("response is " + response.getClass().getName() + " -> " + response);
- RulesModel rules = new RulesModel(RulesModel.QN);
+ final RulesModel rules = new RulesModel(RulesModel.QN);
rules.setId("IHM-generated");
if (Boolean.TRUE.equals(response.get("choose.action.full.import")) || Boolean.TRUE.equals(response.get("choose.action.missing.import"))) {
- SectionModel sm = new SectionModel(SectionModel.QN);
+ final SectionModel sm = new SectionModel(SectionModel.QN);
if (Boolean.TRUE.equals(response.get("choose.action.full.import"))) {
sm.setName("Import complet");
sm.setOverwriteRule(EtatImporteur.OVERWRITE_RULE_NEVER);
}
- if (Boolean.TRUE.equals(response.get("unset.overwrite")))
+ if (Boolean.TRUE.equals(response.get("unset.overwrite"))) {
sm.setOverwriteRule(null);
+ }
- PredicatModel pm = new PredicatModel(PredicatModel.QN);
+ final PredicatModel pm = new PredicatModel(PredicatModel.QN);
sm.addChild(pm, pm.getQName());
pm.addCharacterData("true"); // on passera toujours dedans,
// comme ça...
- ActionsModel am = new ActionsModel(ActionsModel.QN);
- ImportModel im = new ImportModel(ImportModel.QN);
+ final ActionsModel am = new ActionsModel(ActionsModel.QN);
+ final ImportModel im = new ImportModel(ImportModel.QN);
im.setMode(ImportModel.MODE_FULL);
am.addChild(im, im.getQName());
sm.addChild(am, am.getQName());
rules.addChild(sm, sm.getQName());
} else if (Boolean.TRUE.equals(response.get("choose.action.re.import"))) {
- SectionModel sm = new SectionModel(SectionModel.QN);
+ final SectionModel sm = new SectionModel(SectionModel.QN);
sm.setName("Réimport à l'identique");
- PredicatModel pm = new PredicatModel(PredicatModel.QN);
+ final PredicatModel pm = new PredicatModel(PredicatModel.QN);
pm.addCharacterData("true"); // on passera toujours dedans,
// comme ça...
sm.addChild(pm, pm.getQName());
- ActionsModel am = new ActionsModel(ActionsModel.QN);
+ final ActionsModel am = new ActionsModel(ActionsModel.QN);
// on dit juste qu'on réutilise la section du précédent
// import, et cela
// va supprimer les données existantes, puis réappliquer la
sm.addChild(am, am.getQName());
rules.addChild(sm, sm.getQName());
} else {
- SectionModel sm = new SectionModel(SectionModel.QN);
+ final SectionModel sm = new SectionModel(SectionModel.QN);
sm.setName("Import partiel");
- PredicatModel pm = new PredicatModel(PredicatModel.QN);
+ final PredicatModel pm = new PredicatModel(PredicatModel.QN);
pm.addCharacterData("true"); // on passera toujours dedans,
// comme ça...
sm.addChild(pm, pm.getQName());
- ActionsModel am = new ActionsModel(ActionsModel.QN);
+ final ActionsModel am = new ActionsModel(ActionsModel.QN);
// traiter le cas de l'arbre
sm.addChild(am, am.getQName());
if (Boolean.TRUE.equals(response.get("tree.drop.data"))) {
- DeleteModel dm = new DeleteModel(DeleteModel.QN);
+ final DeleteModel dm = new DeleteModel(DeleteModel.QN);
dm.setArchive("archiveName");
am.addChild(dm, dm.getQName());
}
-
- ImportModel im = new ImportModel(ImportModel.QN);
+
+ final ImportModel im = new ImportModel(ImportModel.QN);
im.setMode(ImportModel.MODE_PARTIAL);
- TreeSet<String> documentTypes = (TreeSet<String>) response.get("archive.document.types");
-
- for (String docType : documentTypes) {
+ final TreeSet<String> documentTypes = (TreeSet<String>) response.get("archive.document.types");
+
+ for (final String docType : documentTypes) {
if (Boolean.TRUE.equals(response.get("partial." + docType + ".full"))) {
- FilterModel includeModel = new FilterModel(FilterModel.QN_INCLUDE);
+ final FilterModel includeModel = new FilterModel(FilterModel.QN_INCLUDE);
includeModel.setTypeDoc(docType);
im.addChild(includeModel, includeModel.getQName());
- }else if (Boolean.TRUE.equals(response.get("partial." + docType))) {
- DocumentModel dm = parent.getDocModels().getDocumentById(docType);
-
+ } else if (Boolean.TRUE.equals(response.get("partial." + docType))) {
+ final DocumentModel dm = parent.getDocModels().getDocumentById(docType);
+
if (dm != null && dm.getArchiveVentilationAttrName() != null) {
- TreeSet<String> allAttrValues = (TreeSet<String>) response.get("partial." + docType + ".allAttrValues");
- ArrayList<String> selectedAttributes = (ArrayList<String>) response.get("partial." + docType + ".attrs");
-
- for (String attr : allAttrValues) {
- FilterModel includeModel = new FilterModel(FilterModel.QN_INCLUDE);
+ final TreeSet<String> allAttrValues = (TreeSet<String>) response.get("partial." + docType + ".allAttrValues");
+ final ArrayList<String> selectedAttributes = (ArrayList<String>) response.get("partial." + docType + ".attrs");
+
+ for (final String attr : allAttrValues) {
+ final FilterModel includeModel = new FilterModel(FilterModel.QN_INCLUDE);
includeModel.setTypeDoc(docType);
-
- AttributeModel atm = new AttributeModel(AttributeModel.QN);
+
+ final AttributeModel atm = new AttributeModel(AttributeModel.QN);
atm.setName(dm.getArchiveVentilationAttrName());
atm.setValue(attr);
if (!selectedAttributes.contains(attr)) {
atm.setDiffers(true);
}
includeModel.addChild(atm, atm.getQName());
-
+
im.addChild(includeModel, includeModel.getQName());
}
}
} else {
- FilterModel includeModel = new FilterModel(FilterModel.QN_EXCLUDE);
+ final FilterModel includeModel = new FilterModel(FilterModel.QN_EXCLUDE);
includeModel.setTypeDoc(docType);
im.addChild(includeModel, includeModel.getQName());
}
}
-
+
am.addChild(im, im.getQName());
rules.addChild(sm, sm.getQName());
- }
-
- for (SectionModel sm : rules.getSections()) {
+ }
+
+ for (final SectionModel sm : rules.getSections()) {
logger.debug(sm.getXomDefinition().toXML());
}
-
- ImportServiceSwingProvider isp = new ImportServiceSwingProvider(parent, null, 0);
+
+ final ImportServiceSwingProvider isp = new ImportServiceSwingProvider(parent, null, 0);
isp.setDisplayFeedback(false);
- ArchiveImporter ai = new ArchiveImporter(parent.getDocModels(), archiveFile, isp, parent.getEnvProperties(), rules);
+ final ArchiveImporter ai = new ArchiveImporter(parent.getDocModels(), archiveFile, isp, parent.getEnvProperties(), rules);
ai.setUser(parent.getConnectedUser());
- MainWindow.XemeliosArchiveImporterWorker worker = new MainWindow.XemeliosArchiveImporterWorker(ai);
+ final MainWindow.XemeliosArchiveImporterWorker worker = new MainWindow.XemeliosArchiveImporterWorker(ai);
worker.execute();
}
- } catch (Exception ex) {
+ } catch (final Exception ex) {
// a l'initialisation, on a rencontré une erreur
new DisplayExceptionDlg(parent, ex);
}
}
private HashMap<Object, Object> loadInitialProperties() throws Exception {
- HashMap<Object, Object> properties = new HashMap<Object, Object>();
+ final HashMap<Object, Object> properties = new HashMap<Object, Object>();
try {
- ZipFile zf = new ZipFile(archiveFile);
- ZipEntry ze = zf.getEntry(ArchiveImporter.MANIFESTE_FILE_NAME);
- InputStream is = zf.getInputStream(ze);
- Builder builder = new Builder();
- Document doc = builder.build(is);
+ final ZipFile zf = new ZipFile(this.archiveFile);
+ final ZipEntry ze = zf.getEntry(ArchiveImporter.MANIFESTE_FILE_NAME);
+ final InputStream is = zf.getInputStream(ze);
+ final Builder builder = new Builder();
+ final Document doc = builder.build(is);
properties.put("archive.manifeste", doc);
- Document importedManifesteArchive = DataLayerManager.getImplementation().getManifesteFromArchive(ArchiveImporter.getArchiveName(archiveFile), parent.getConnectedUser());
+ final Document importedManifesteArchive = DataLayerManager.getImplementation().getManifesteFromArchive(ArchiveImporter.getArchiveName(this.archiveFile), this.parent.getConnectedUser());
properties.put("imported.archive.manifeste", importedManifesteArchive);
- } catch (ZipException zEx) {
- throw new Exception(archiveFile.getName() + " n'est pas une archive ZIP valide", zEx);
+ } catch (final ZipException zEx) {
+ throw new Exception(this.archiveFile.getName() + " n'est pas une archive ZIP valide", zEx);
} finally {
return properties;
}
public class MyWizardBranchController extends WizardBranchController {
private WizardPanelProvider _wpp;
- public MyWizardBranchController(WizardPanelProvider wpp) {
+ public MyWizardBranchController(final WizardPanelProvider wpp) {
super(wpp);
- _wpp = new WizardPanelProvider("Choix de l'élément", "tree", "Choix de l'élément") {
+ this._wpp = new WizardPanelProvider("Choix de l'élément", "tree", "Choix de l'élément") {
@Override
- protected JComponent createPanel(WizardController wc, String string, Map map) {
- return new PnlTree(parent.getDocModels());
+ protected JComponent createPanel(final WizardController wc, final String string, final Map map) {
+ return new PnlTree(ArchiveWizardDisplayer.this.parent.getDocModels());
}
};
}
@Override
- protected WizardPanelProvider getPanelProviderForStep(String step, Map settings) {
- if (Boolean.TRUE.equals(settings.get("choose.action.partial.import")))
- return _wpp;
- else
+ protected WizardPanelProvider getPanelProviderForStep(final String step, final Map settings) {
+ if (Boolean.TRUE.equals(settings.get("choose.action.partial.import"))) {
+ return this._wpp;
+ } else {
return null;
+ }
}
}
package fr.gouv.finances.cp.xemelios.ui.importArchive;
-import fr.gouv.finances.dgfip.xemelios.importers.archives.ArchiveImporter;
import java.awt.Component;
import java.util.Map;
+
import nu.xom.Document;
import org.apache.commons.lang.StringUtils;
import org.netbeans.spi.wizard.WizardPage;
import org.netbeans.spi.wizard.WizardPanelNavResult;
+import fr.gouv.finances.dgfip.xemelios.importers.archives.ArchiveImporter;
+
/**
- *
+ *
* @author cmarchand
*/
public class PnlChooseAction extends WizardPage {
- private static final Logger logger = Logger.getLogger(PnlChooseAction.class);
-
- /** Creates new form PnlChooseAction */
- public PnlChooseAction() {
- super("Choix de l'action");
- initComponents();
- setLongDescription("Choix de l'action");
- }
-
- @Override
- public WizardPanelNavResult allowNext(String stepName, Map settings, Wizard wizard) {
- if(rbPartialImport.isSelected()) {
- return WizardPanelNavResult.PROCEED;
- } else return WizardPanelNavResult.REMAIN_ON_PAGE;
- }
-
- @Override
- public WizardPanelNavResult allowFinish(String stepName, Map settings, Wizard wizard) {
- if(rbCompleteImport.isSelected() || rbFullImport.isSelected() || rbPartialImport.isSelected() || rbReImport.isSelected()) {
- return WizardPanelNavResult.PROCEED;
- } else return WizardPanelNavResult.REMAIN_ON_PAGE;
- }
-
- @Override
- public WizardPanelNavResult allowBack(String stepName, Map settings, Wizard wizard) {
- return WizardPanelNavResult.REMAIN_ON_PAGE;
- }
-
- @Override
- protected String validateContents(Component component, Object event) {
- if(rbPartialImport.isSelected()) {
- setForwardNavigationMode(WizardController.MODE_CAN_CONTINUE);
- } else {
- setForwardNavigationMode(WizardController.MODE_CAN_FINISH);
- }
- return null;
- }
-
-
-
- @Override
- protected void renderingPage() {
- Document archiveManifeste = (Document)getWizardData("archive.manifeste");
- Document importedArchiveManifeste = (Document)getWizardData("imported.archive.manifeste");
- boolean isArchiveAlreadyImported = importedArchiveManifeste!=null;
- if(isArchiveAlreadyImported) {
- String archiveVersion = archiveManifeste.getRootElement().getAttributeValue("version");
- String importedArchiveVersion = importedArchiveManifeste.getRootElement().getAttributeValue("version");
-
- if(StringUtils.isEmpty(archiveVersion) || StringUtils.isEmpty(importedArchiveVersion)){
- rbCompleteImport.setEnabled(false);
- rbReImport.setEnabled(false);
- rbFullImport.setSelected(true);
- }else if(importedArchiveManifeste.query("/m:manifeste/m:documents/m:document[@imported='"+ArchiveImporter.NON+"' or @imported='"+ArchiveImporter.NON_DISPONIBLE+"']", ArchiveImporter.getNamespaceCtx()).size()>0) {
- if(archiveVersion.equals(importedArchiveVersion)) {
- rbCompleteImport.setEnabled(true);
- rbCompleteImport.setSelected(true);
- } else
- rbCompleteImport.setEnabled(false);
- rbReImport.setEnabled(true);
- } else {
- rbCompleteImport.setEnabled(true);
- rbReImport.setEnabled(true);
- rbReImport.setSelected(true);
- }
- } else {
- rbCompleteImport.setEnabled(false);
- rbReImport.setEnabled(false);
- rbFullImport.setSelected(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.
- */
- @SuppressWarnings("unchecked")
- // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
- private void initComponents() {
-
- bGroup = new javax.swing.ButtonGroup();
- lblQuestion = new javax.swing.JLabel();
- rbFullImport = new javax.swing.JRadioButton();
- rbPartialImport = new javax.swing.JRadioButton();
- rbCompleteImport = new javax.swing.JRadioButton();
- rbReImport = new javax.swing.JRadioButton();
-
- lblQuestion.setText("Que souhaitez-vous faire avec cette action ?");
-
- bGroup.add(rbFullImport);
- rbFullImport.setText("Tout importer");
- rbFullImport.setName("choose.action.full.import"); // NOI18N
-
- bGroup.add(rbPartialImport);
- rbPartialImport.setText("Importer une partie de l'archive");
- rbPartialImport.setName("choose.action.partial.import"); // NOI18N
-
- bGroup.add(rbCompleteImport);
- rbCompleteImport.setText("Importer les données manquantes");
- rbCompleteImport.setName("choose.action.missing.import"); // NOI18N
-
- bGroup.add(rbReImport);
- rbReImport.setText("Réimporter à l'identique");
- rbReImport.setName("choose.action.re.import"); // NOI18N
-
- 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(lblQuestion)
- .addComponent(rbFullImport)
- .addComponent(rbPartialImport)
- .addComponent(rbCompleteImport)
- .addComponent(rbReImport))
- .addContainerGap(209, Short.MAX_VALUE))
- );
- layout.setVerticalGroup(
- layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGroup(layout.createSequentialGroup()
- .addContainerGap()
- .addComponent(lblQuestion)
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
- .addComponent(rbFullImport)
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
- .addComponent(rbPartialImport)
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
- .addComponent(rbCompleteImport)
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
- .addComponent(rbReImport)
- .addContainerGap(149, Short.MAX_VALUE))
- );
- }// </editor-fold>//GEN-END:initComponents
-
-
- // Variables declaration - do not modify//GEN-BEGIN:variables
- private javax.swing.ButtonGroup bGroup;
- private javax.swing.JLabel lblQuestion;
- private javax.swing.JRadioButton rbCompleteImport;
- private javax.swing.JRadioButton rbFullImport;
- private javax.swing.JRadioButton rbPartialImport;
- private javax.swing.JRadioButton rbReImport;
- // End of variables declaration//GEN-END:variables
-
- public static String getDescription() { return "Choix de l'action"; }
+ private static final Logger logger = Logger.getLogger(PnlChooseAction.class);
+
+ /** Creates new form PnlChooseAction */
+ public PnlChooseAction() {
+ super("Choix de l'action");
+ this.initComponents();
+ this.setLongDescription("Choix de l'action");
+ }
+
+ @Override
+ public WizardPanelNavResult allowNext(final String stepName, final Map settings, final Wizard wizard) {
+ if (this.rbPartialImport.isSelected()) {
+ return WizardPanelNavResult.PROCEED;
+ } else {
+ return WizardPanelNavResult.REMAIN_ON_PAGE;
+ }
+ }
+
+ @Override
+ public WizardPanelNavResult allowFinish(final String stepName, final Map settings, final Wizard wizard) {
+ if (this.rbCompleteImport.isSelected() || this.rbFullImport.isSelected() || this.rbPartialImport.isSelected() || this.rbReImport.isSelected()) {
+ return WizardPanelNavResult.PROCEED;
+ } else {
+ return WizardPanelNavResult.REMAIN_ON_PAGE;
+ }
+ }
+
+ @Override
+ public WizardPanelNavResult allowBack(final String stepName, final Map settings, final Wizard wizard) {
+ return WizardPanelNavResult.REMAIN_ON_PAGE;
+ }
+
+ @Override
+ protected String validateContents(final Component component, final Object event) {
+ if (this.rbPartialImport.isSelected()) {
+ this.setForwardNavigationMode(WizardController.MODE_CAN_CONTINUE);
+ } else {
+ this.setForwardNavigationMode(WizardController.MODE_CAN_FINISH);
+ }
+ return null;
+ }
+
+ @Override
+ protected void renderingPage() {
+ final Document archiveManifeste = (Document) this.getWizardData("archive.manifeste");
+ final Document importedArchiveManifeste = (Document) this.getWizardData("imported.archive.manifeste");
+ final boolean isArchiveAlreadyImported = importedArchiveManifeste != null;
+ if (isArchiveAlreadyImported) {
+ final String archiveVersion = archiveManifeste.getRootElement().getAttributeValue("version");
+ final String importedArchiveVersion = importedArchiveManifeste.getRootElement().getAttributeValue("version");
+
+ if (StringUtils.isEmpty(archiveVersion) || StringUtils.isEmpty(importedArchiveVersion)) {
+ this.rbCompleteImport.setEnabled(false);
+ this.rbReImport.setEnabled(false);
+ this.rbFullImport.setSelected(true);
+ } else if (importedArchiveManifeste.query("/m:manifeste/m:documents/m:document[@imported='" + ArchiveImporter.NON + "' or @imported='" + ArchiveImporter.NON_DISPONIBLE + "']", ArchiveImporter.getNamespaceCtx()).size() > 0) {
+ if (archiveVersion.equals(importedArchiveVersion)) {
+ this.rbCompleteImport.setEnabled(true);
+ this.rbCompleteImport.setSelected(true);
+ } else {
+ this.rbCompleteImport.setEnabled(false);
+ }
+ this.rbReImport.setEnabled(true);
+ } else {
+ this.rbCompleteImport.setEnabled(true);
+ this.rbReImport.setEnabled(true);
+ this.rbReImport.setSelected(true);
+ }
+ } else {
+ this.rbCompleteImport.setEnabled(false);
+ this.rbReImport.setEnabled(false);
+ this.rbFullImport.setSelected(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.
+ */
+ @SuppressWarnings("unchecked")
+ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ this.bGroup = new javax.swing.ButtonGroup();
+ this.lblQuestion = new javax.swing.JLabel();
+ this.rbFullImport = new javax.swing.JRadioButton();
+ this.rbPartialImport = new javax.swing.JRadioButton();
+ this.rbCompleteImport = new javax.swing.JRadioButton();
+ this.rbReImport = new javax.swing.JRadioButton();
+
+ this.lblQuestion.setText("Que souhaitez-vous faire avec cette action ?");
+
+ this.bGroup.add(this.rbFullImport);
+ this.rbFullImport.setText("Tout importer");
+ this.rbFullImport.setName("choose.action.full.import"); // NOI18N
+
+ this.bGroup.add(this.rbPartialImport);
+ this.rbPartialImport.setText("Importer une partie de l'archive");
+ this.rbPartialImport.setName("choose.action.partial.import"); // NOI18N
+
+ this.bGroup.add(this.rbCompleteImport);
+ this.rbCompleteImport.setText("Importer les données manquantes");
+ this.rbCompleteImport.setName("choose.action.missing.import"); // NOI18N
+
+ this.bGroup.add(this.rbReImport);
+ this.rbReImport.setText("Réimporter à l'identique");
+ this.rbReImport.setName("choose.action.re.import"); // NOI18N
+
+ final 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(this.lblQuestion).addComponent(this.rbFullImport).addComponent(this.rbPartialImport).addComponent(this.rbCompleteImport).addComponent(this.rbReImport))
+ .addContainerGap(209, Short.MAX_VALUE)));
+ layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
+ layout.createSequentialGroup().addContainerGap().addComponent(this.lblQuestion).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(this.rbFullImport).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(this.rbPartialImport)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(this.rbCompleteImport).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(this.rbReImport).addContainerGap(149, Short.MAX_VALUE)));
+ }// </editor-fold>//GEN-END:initComponents
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.ButtonGroup bGroup;
+ private javax.swing.JLabel lblQuestion;
+ private javax.swing.JRadioButton rbCompleteImport;
+ private javax.swing.JRadioButton rbFullImport;
+ private javax.swing.JRadioButton rbPartialImport;
+ private javax.swing.JRadioButton rbReImport;
+
+ // End of variables declaration//GEN-END:variables
+
+ public static String getDescription() {
+ return "Choix de l'action";
+ }
}
package fr.gouv.finances.cp.xemelios.ui.importArchive;
-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.importers.archives.ArchiveImporter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
+
import javax.swing.event.TableModelEvent;
import javax.swing.tree.TreePath;
+
import nu.xom.Document;
import nu.xom.Nodes;
+
import org.apache.log4j.Logger;
import org.jdesktop.swingx.treetable.AbstractMutableTreeTableNode;
import org.jdesktop.swingx.treetable.DefaultTreeTableModel;
import org.netbeans.spi.wizard.WizardPage;
import org.netbeans.spi.wizard.WizardPanelNavResult;
+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.importers.archives.ArchiveImporter;
+
/**
*
* @author cmarchand
private static final Logger logger = Logger.getLogger(PnlTree.class);
- private DocumentsModel documentsModel;
+ private final DocumentsModel documentsModel;
/** Creates new form PnlTree */
- public PnlTree(DocumentsModel documentsModels) {
+ public PnlTree(final DocumentsModel documentsModels) {
super();
this.documentsModel = documentsModels;
- initComponents();
- tree.setRootVisible(true);
+ this.initComponents();
+ this.tree.setRootVisible(true);
}
@Override
- public WizardPanelNavResult allowFinish(String stepName, Map settings, Wizard wizard) {
- prepareExit();
+ public WizardPanelNavResult allowFinish(final String stepName, final Map settings, final Wizard wizard) {
+ this.prepareExit();
return WizardPanelNavResult.PROCEED;
}
@Override
- public WizardPanelNavResult allowBack(String stepName, Map settings, Wizard wizard) {
+ public WizardPanelNavResult allowBack(final String stepName, final Map settings, final Wizard wizard) {
return WizardPanelNavResult.PROCEED;
}
@Override
protected void renderingPage() {
- Document doc = (Document) getWizardData("archive.manifeste");
- MyTreeTableNode root = new MyTreeTableNode(null, LEVEL_ROOT);
- Nodes typeDocs = doc.query("/manifeste/documents/document/@type");
- TreeSet<String> ts = new TreeSet<String>();
+ final Document doc = (Document) this.getWizardData("archive.manifeste");
+ final MyTreeTableNode root = new MyTreeTableNode(null, LEVEL_ROOT);
+ final Nodes typeDocs = doc.query("/manifeste/documents/document/@type");
+ final TreeSet<String> ts = new TreeSet<String>();
for (int i = 0; i < typeDocs.size(); i++) {
ts.add(ArchiveImporter.normalizeDocumentType(typeDocs.get(i).getValue()));
}
// on a la liste des types de documents
- putWizardData("archive.document.types", ts);
- for (String typeDoc : ts) {
- DocumentModel dm = documentsModel.getDocumentById(typeDoc);
+ this.putWizardData("archive.document.types", ts);
+ for (final String typeDoc : ts) {
+ final DocumentModel dm = this.documentsModel.getDocumentById(typeDoc);
if (dm == null) {
// c'est un type de document qu'on ne connait pas, il faut un
// traitement d'exception
- Pair p = new Pair(typeDoc, typeDoc);
- MyTreeTableNode ttn = new MyTreeTableNode(p, LEVEL_TYPE_DOC);
+ final Pair p = new Pair(typeDoc, typeDoc);
+ final MyTreeTableNode ttn = new MyTreeTableNode(p, LEVEL_TYPE_DOC);
if (!"PJ".equals(typeDoc)) {
// c'est un type de document non disponible
ttn.selectionable = false;
}
root.add(ttn);
} else {
- Pair p = new Pair(typeDoc, dm.getTitre());
- MyTreeTableNode ttn = new MyTreeTableNode(p, LEVEL_TYPE_DOC);
+ final Pair p = new Pair(typeDoc, dm.getTitre());
+ final MyTreeTableNode ttn = new MyTreeTableNode(p, LEVEL_TYPE_DOC);
// on va chercher maintenant chercher les valeurs des attributs
// fils
if (dm.getArchiveVentilationAttrName() != null) {
- Nodes valuesNodes = doc.query("/manifeste/documents/document[@type='" + p.key + "']/@" + dm.getArchiveVentilationAttrName());
- TreeSet<String> values = new TreeSet<String>();
+ final Nodes valuesNodes = doc.query("/manifeste/documents/document[@type='" + p.key + "']/@" + dm.getArchiveVentilationAttrName());
+ final TreeSet<String> values = new TreeSet<String>();
for (int j = 0; j < valuesNodes.size(); j++) {
values.add(valuesNodes.get(j).getValue());
}
- putWizardData("partial." + typeDoc + ".allAttrValues", values);
- for (String value : values) {
- MyTreeTableNode child = new MyTreeTableNode(value, LEVEL_ATTR);
+ this.putWizardData("partial." + typeDoc + ".allAttrValues", values);
+ for (final String value : values) {
+ final MyTreeTableNode child = new MyTreeTableNode(value, LEVEL_ATTR);
ttn.add(child);
}
}
root.add(ttn);
}
}
- List<String> columnNames = new ArrayList<String>();
+ final List<String> columnNames = new ArrayList<String>();
columnNames.add("Element");
columnNames.add("Importer");
- MyTreeTableModel treeModel = new MyTreeTableModel(root, columnNames);
- tree.setTreeTableModel(treeModel);
- tree.expandAll();
- tree.sizeColumnsToFit(0);
+ final MyTreeTableModel treeModel = new MyTreeTableModel(root, columnNames);
+ this.tree.setTreeTableModel(treeModel);
+ this.tree.expandAll();
+ this.tree.sizeColumnsToFit(0);
}
protected void prepareExit() {
- DefaultTreeTableModel dttm = (DefaultTreeTableModel) tree.getTreeTableModel();
- MyTreeTableNode mttn = (MyTreeTableNode) dttm.getRoot();
+ final DefaultTreeTableModel dttm = (DefaultTreeTableModel) this.tree.getTreeTableModel();
+ final MyTreeTableNode mttn = (MyTreeTableNode) dttm.getRoot();
if (mttn == null) {
return;
// niveau 1 - parcours des documents
for (int docCount = 0; docCount < mttn.getChildCount(); docCount++) {
- MyTreeTableNode doc = (MyTreeTableNode) mttn.getChildAt(docCount);
+ final MyTreeTableNode doc = (MyTreeTableNode) mttn.getChildAt(docCount);
if (doc.selected) {
- putWizardData("partial." + doc.code +".full", Boolean.TRUE);
+ this.putWizardData("partial." + doc.code + ".full", Boolean.TRUE);
} else {
// niveau 2 - on va parcourir les sous-etats
- Enumeration<MyTreeTableNode> docAttrs = (Enumeration<MyTreeTableNode>) doc.children();
- ArrayList<String> attrs = new ArrayList<String>();
+ final Enumeration<MyTreeTableNode> docAttrs = (Enumeration<MyTreeTableNode>) doc.children();
+ final ArrayList<String> attrs = new ArrayList<String>();
while (docAttrs.hasMoreElements()) {
- MyTreeTableNode docAttr = docAttrs.nextElement();
+ final MyTreeTableNode docAttr = docAttrs.nextElement();
- //si on a sélectionné un etat
+ // si on a sélectionné un etat
if (docAttr.selected) {
attrs.add(docAttr.code);
}
}
if (attrs.size() > 0) {
- putWizardData("partial." + doc.code, Boolean.TRUE);
- putWizardData("partial." + doc.code + ".attrs", attrs);
+ this.putWizardData("partial." + doc.code, Boolean.TRUE);
+ this.putWizardData("partial." + doc.code + ".attrs", attrs);
}
}
-
-//
-// if (doc.selected) {
-// logger.debug("setting partial." + doc.code + "=" + Boolean.TRUE);
-// putWizardData("partial." + doc.code, Boolean.TRUE);
-// boolean full = true;
-// ArrayList<String> attrs = new ArrayList<String>();
-// for (int attrCount = 0; attrCount < doc.getChildCount(); attrCount++) {
-// MyTreeTableNode attr = (MyTreeTableNode) doc.getChildAt(attrCount);
-// if (attr.selected) {
-// full = false;
-// attrs.add(attr.code);
-// }
-// }
-//
-// putWizardData("partial." + doc.code + ".full", Boolean.valueOf(full));
-// if (!full) {
-// if (attrs.size() > 0)
-// putWizardData("partial." + doc.code + ".attrs", attrs);
-// else
-// putWizardData("partial." + doc.code + ".attrs", null);
-// }
-// } else {
-//
-// logger.debug("setting partial." + doc.code + "=" + Boolean.FALSE);
-// putWizardData("partial." + doc.code, Boolean.FALSE);
-// }
+
+ //
+ // if (doc.selected) {
+ // logger.debug("setting partial." + doc.code + "=" + Boolean.TRUE);
+ // putWizardData("partial." + doc.code, Boolean.TRUE);
+ // boolean full = true;
+ // ArrayList<String> attrs = new ArrayList<String>();
+ // for (int attrCount = 0; attrCount < doc.getChildCount(); attrCount++) {
+ // MyTreeTableNode attr = (MyTreeTableNode) doc.getChildAt(attrCount);
+ // if (attr.selected) {
+ // full = false;
+ // attrs.add(attr.code);
+ // }
+ // }
+ //
+ // putWizardData("partial." + doc.code + ".full", Boolean.valueOf(full));
+ // if (!full) {
+ // if (attrs.size() > 0)
+ // putWizardData("partial." + doc.code + ".attrs", attrs);
+ // else
+ // putWizardData("partial." + doc.code + ".attrs", null);
+ // }
+ // } else {
+ //
+ // logger.debug("setting partial." + doc.code + "=" + Boolean.FALSE);
+ // putWizardData("partial." + doc.code, Boolean.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
+ * 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")
// desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
- chkDropDataBefore = new javax.swing.JCheckBox();
- jScrollPane1 = new javax.swing.JScrollPane();
- tree = new org.jdesktop.swingx.JXTreeTable();
+ this.chkDropDataBefore = new javax.swing.JCheckBox();
+ this.jScrollPane1 = new javax.swing.JScrollPane();
+ this.tree = new org.jdesktop.swingx.JXTreeTable();
- chkDropDataBefore.setText("Supprimer les données déjà importées");
- chkDropDataBefore.setName("tree.drop.data"); // NOI18N
+ this.chkDropDataBefore.setText("Supprimer les données déjà importées");
+ this.chkDropDataBefore.setName("tree.drop.data"); // NOI18N
- jScrollPane1.setViewportView(tree);
+ this.jScrollPane1.setViewportView(this.tree);
- javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
+ final 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, 376, Short.MAX_VALUE).addComponent(chkDropDataBefore)).addContainerGap()));
+ layout.createSequentialGroup().addContainerGap().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(this.jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE).addComponent(this.chkDropDataBefore)).addContainerGap()));
layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
- layout.createSequentialGroup().addContainerGap().addComponent(chkDropDataBefore).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
- .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
+ layout.createSequentialGroup().addContainerGap().addComponent(this.chkDropDataBefore).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(this.jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
class MyTreeTableModel extends DefaultTreeTableModel {
- public MyTreeTableModel(TreeTableNode rootNode, List<String> columnNames) {
+ public MyTreeTableModel(final TreeTableNode rootNode, final List<String> columnNames) {
super(rootNode, columnNames);
}
@Override
- public Class<?> getColumnClass(int column) {
- if (column == 1)
+ public Class<?> getColumnClass(final int column) {
+ if (column == 1) {
return Boolean.class;
- else
+ } else {
return super.getColumnClass(column);
+ }
}
}
private String code;
private String libelle;
private boolean selected;
- private int level;
+ private final int level;
private boolean selectionable = true;
- public MyTreeTableNode(Object o, int level) {
+ public MyTreeTableNode(final Object o, final int level) {
super();
this.level = level;
switch (level) {
case LEVEL_ROOT: {
- libelle = code = "Archive";
+ this.libelle = this.code = "Archive";
break;
}
case LEVEL_TYPE_DOC: {
- Pair p = (Pair) o;
- code = p.key;
- libelle = p.libelle;
+ final Pair p = (Pair) o;
+ this.code = p.key;
+ this.libelle = p.libelle;
break;
}
default:
- libelle = code = o.toString();
+ this.libelle = this.code = o.toString();
}
}
@Override
- public Object getValueAt(int i) {
- if (i == 0)
- return libelle;
- else
- return selected;
+ public Object getValueAt(final int i) {
+ if (i == 0) {
+ return this.libelle;
+ } else {
+ return this.selected;
+ }
}
@Override
}
@Override
- public void setValueAt(Object aValue, int column) {
- if (!selectionable)
+ public void setValueAt(final Object aValue, final int column) {
+ if (!this.selectionable) {
return;
- selected = (Boolean) aValue;
+ }
+ this.selected = (Boolean) aValue;
// on propage sur les enfants
- for (Enumeration<? extends MutableTreeTableNode> enfants = children(); enfants.hasMoreElements();) {
- MutableTreeTableNode mttn = enfants.nextElement();
- mttn.setValueAt(aValue, level);
+ for (final Enumeration<? extends MutableTreeTableNode> enfants = this.children(); enfants.hasMoreElements();) {
+ final MutableTreeTableNode mttn = enfants.nextElement();
+ mttn.setValueAt(aValue, this.level);
// tree.getTreeTableModel().valueForPathChanged(((MyTreeTableNode)mttn).getTreePath(),
// aValue);
}
-
- if(!selected && (this.getParent() instanceof MyTreeTableNode)){
- MyTreeTableNode myParent = (MyTreeTableNode)this.getParent();
+
+ if (!this.selected && (this.getParent() instanceof MyTreeTableNode)) {
+ final MyTreeTableNode myParent = (MyTreeTableNode) this.getParent();
myParent.selected = false;
}
-
-
- tree.tableChanged(new TableModelEvent(tree.getModel()));
+
+ PnlTree.this.tree.tableChanged(new TableModelEvent(PnlTree.this.tree.getModel()));
}
@Override
- public boolean isEditable(int column) {
- return column == 1 && selectionable;
+ public boolean isEditable(final int column) {
+ return column == 1 && this.selectionable;
}
public TreePath getTreePath() {
Object[] parentPath = null;
- if (getParent() != null)
- getParentNode().getTreePath().getPath();
- else
+ if (this.getParent() != null) {
+ this.getParentNode().getTreePath().getPath();
+ } else {
parentPath = new Object[0];
- Object[] path = Arrays.copyOf(parentPath, parentPath.length + 1);
+ }
+ final Object[] path = Arrays.copyOf(parentPath, parentPath.length + 1);
path[parentPath.length] = this;
return new TreePath(path);
}
private MyTreeTableNode getParentNode() {
- return (MyTreeTableNode) getParent();
+ return (MyTreeTableNode) this.getParent();
}
}
import javax.swing.JScrollPane;
import javax.swing.JToolBar;
import javax.swing.ScrollPaneConstants;
+import javax.swing.SwingConstants;
import javax.swing.table.TableColumn;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.jdesktop.swingx.JXTreeTable;
+import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode;
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.
- *
+ * 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;
- }
- }
+ 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(final JFrame parent, final 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(final File rootDir, final String[] extensions) {
+ final ImportFileTreeTableModel model = this.createImportFileModel(rootDir, extensions);
+ final InnerImportDialog d = new InnerImportDialog(model, this.parent, this.title, true);
+ d.setVisible(true);
+
+ return this.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 final 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(final ImportFileTreeTableModel model, final JFrame parent, final String title, final boolean modal) {
+ super(parent, title, modal);
+ this.importFileTreeTableModel = model;
+ this.treeTable = new JXTreeTable(this.importFileTreeTableModel);
+ final JScrollPane jScrollPane1 = new javax.swing.JScrollPane();
+
+ this.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+ jScrollPane1.setViewportView(this.treeTable);
+ jScrollPane1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
+
+ this.boutonOk = new JButton("Ok");
+ this.boutonOk.addActionListener(this);
+ this.boutonAnnuler = new JButton("Annuler");
+ this.boutonAnnuler.addActionListener(this);
+
+ final JToolBar toolbar = new JToolBar(SwingConstants.HORIZONTAL);
+ toolbar.setFloatable(false);
+ toolbar.setRollover(true);
+ // IhmFactory ihmFactory = IhmFactory.newInstance();
+ this.boutonExpandAll = new JButton(IhmFactory.getIconFromResource(ImageResources.EXPAND_ALL));
+ this.boutonExpandAll.setToolTipText("Déplier l'arborescence");
+ this.boutonExpandAll.addActionListener(this);
+ toolbar.add(this.boutonExpandAll);
+ this.boutonCollapseAll = new JButton(IhmFactory.getIconFromResource(ImageResources.COLLAPSE_ALL));
+ this.boutonCollapseAll.setToolTipText("Replier l'arborescence");
+ this.boutonCollapseAll.addActionListener(this);
+ toolbar.add(this.boutonCollapseAll);
+ this.boutonSelectAll = new JButton(IhmFactory.getIconFromResource(ImageResources.SELECT_ALL));
+ this.boutonSelectAll.setToolTipText("Tout sélectionner");
+ this.boutonSelectAll.addActionListener(this);
+ toolbar.add(this.boutonSelectAll);
+ this.boutonSelectNone = new JButton(IhmFactory.getIconFromResource(ImageResources.SELECT_NONE));
+ this.boutonSelectNone.setToolTipText("Tout désélectionner");
+ this.boutonSelectNone.addActionListener(this);
+ toolbar.add(this.boutonSelectNone);
+
+ final org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this.getContentPane());
+ this.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(this.boutonAnnuler).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.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(this.boutonOk).add(this.boutonAnnuler))
+ .addContainerGap()));
+ this.pack();
+
+ // init for the toolbar
+ this.setSize(500, 400);
+
+ this.setLocationRelativeTo(parent);
+
+ // To beautify things, we specify column widths
+ TableColumn col = this.treeTable.getColumnModel().getColumn(1);
+ col.setPreferredWidth(75);
+ col.setMinWidth(60);
+ col = this.treeTable.getColumnModel().getColumn(0);
+ col.setMinWidth(200);
+ col.setPreferredWidth(380);
+ }
+
+ /**
+ * Called when a button is clicked
+ */
+ @Override
+ public void actionPerformed(final ActionEvent ae) {
+ final Object cmd = ae.getSource();
+ if (cmd.equals(this.boutonExpandAll)) {
+ this.treeTable.expandAll();
+ } else if (cmd.equals(this.boutonCollapseAll)) {
+ this.treeTable.collapseAll();
+ } else if (cmd.equals(this.boutonSelectAll)) {
+ this.importFileTreeTableModel.selectAll();
+ } else if (cmd.equals(this.boutonSelectNone)) {
+ this.importFileTreeTableModel.selectNone();
+ } else if (cmd.equals(this.boutonOk)) {
+ ImportDialog.this.resultList = this.importFileTreeTableModel.getFilesToImportList();
+ this.setVisible(false);
+ } else if (cmd.equals(this.boutonAnnuler)) {
+ this.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(final File rootDir, final String[] extensions) {
+ ImportFileTreeTableModel model = null;
+
+ if (!rootDir.isDirectory()) {
+ // jeter une exception
+ return model;
+ }
+ final ImportFile racineDir = new ImportFile(rootDir);
+ final MyTreeNode racine = this.splitPath(racineDir, racineDir);
+
+ final 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()) {
+ final File fichier = (File) iter.next();
+ fichierImport = new ImportFile(fichier);
+ this.addSorted(racine, this.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(final ImportFile fichierImport, final ImportFile upToDir) {
+ MyTreeNode currentNode = new MyTreeNode(fichierImport);
+ if (upToDir.getFile().equals(fichierImport.getFile())) {
+ return currentNode;
+ }
+ final File upDir = upToDir.getFile();
+ File parentFile;
+ while ((parentFile = ((ImportFile) currentNode.getUserObject()).getFile().getParentFile()) != null) {
+ final ImportFile parentImportFile = new ImportFile(parentFile);
+ final 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(final MyTreeNode racine, final MyTreeNode newNode) {
+ MyTreeNode newNodeBrowser = newNode;
+ MyTreeNode rootBrowser = racine;
+ boolean continuer = true;
+
+ while (continuer) {
+ final ImportFile newNodeBrowserFile = (ImportFile) newNodeBrowser.getUserObject();
+ final ImportFile rootBrowserFile = (ImportFile) rootBrowser.getUserObject();
+
+ if (newNodeBrowserFile.equals(rootBrowserFile)) {
+ newNodeBrowser = (MyTreeNode) newNodeBrowser.getChildAt(0);
+ final MyTreeNode rootSon = this.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(final DefaultMutableTreeTableNode newNodeBrowser, final DefaultMutableTreeTableNode rootBrowser) {
+ MyTreeNode result = null;
+ final ImportFile newNodeBrowserFile = (ImportFile) newNodeBrowser.getUserObject();
+
+ for (final Enumeration enumerator = rootBrowser.children(); enumerator.hasMoreElements() && result == null;) {
+ final MyTreeNode child = (MyTreeNode) enumerator.nextElement();
+ final ImportFile childFile = (ImportFile) child.getUserObject();
+ if (childFile.equals(newNodeBrowserFile)) {
+ result = child;
+ }
+ }
+ return result;
+ }
+
+ public class MyTreeNode extends DefaultMutableTreeTableNode {
+ private final ImportFile importFile;
+
+ public MyTreeNode(final ImportFile iFile) {
+ super(iFile);
+ this.importFile = iFile;
+ }
+
+ @Override
+ public boolean isLeaf() {
+ final boolean ret = !(this.importFile.getFile().isDirectory());
+ // logger.debug("isLeaf("+importFile.getFile().getName()+")->"+ret);
+ // if(ret) logger.debug("\thas "+getChildCount()+" childs");
+ return ret;
+ }
+ }
}
import java.io.File;
-
/**
- * Represents a file that is candidate for import.
- * This class is used in the ImportFileTreeTableModel, in each node.
+ * Represents a file that is candidate for import. This class is used in the ImportFileTreeTableModel, in each node.
*
* @author Yann Laurelut
*/
/** the underlying file */
private File fichier = null;
- public ImportFile(File fic) {
+ public ImportFile(final File fic) {
this.fichier = fic;
}
public boolean isFile() {
- return fichier.isFile();
+ return this.fichier.isFile();
}
+
public String getName() {
- return fichier.getName();
+ return this.fichier.getName();
}
+
public String getPath() {
- return fichier.getPath();
+ return this.fichier.getPath();
}
+
public boolean isToBeImported() {
- return toBeImported;
+ return this.toBeImported;
}
- public void setToBeImported(boolean toBeImported) {
+
+ public void setToBeImported(final boolean toBeImported) {
this.toBeImported = toBeImported;
}
+
public File getFile() {
- return fichier;
+ return this.fichier;
}
- public void setFile(File fic) {
+
+ public void setFile(final File fic) {
this.fichier = fic;
}
-
+
/**
- * Returns the last path element (directory)
- * of this full path
+ * 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()) {
+ final String pathSeparator = System.getProperty("file.separator");
+ if (this.isFile()) {
result = this.getName();
} else {
- String path = this.getPath();
- result = path.substring(path.lastIndexOf(pathSeparator)+1);
+ final String path = this.getPath();
+ result = path.substring(path.lastIndexOf(pathSeparator) + 1);
}
return result;
}
@Override
public String toString() {
- return fichier.getName();
+ return this.fichier.getName();
}
-
+
@Override
- public boolean equals(Object other) {
+ public boolean equals(final Object other) {
boolean result = false;
- if(other instanceof ImportFile) {
- ImportFile otherFile = (ImportFile)other;
- result = getFile().equals(otherFile.getFile());
+ if (other instanceof ImportFile) {
+ final ImportFile otherFile = (ImportFile) other;
+ result = this.getFile().equals(otherFile.getFile());
}
return result;
}
}
-
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;
+//import javax.swing.tree.TreeNode;
/**
* Model for the TreeTable used in the ImportDialog.
*
- * @author Yann Laurelut
+ * @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);
- }
- }
+ 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(final TreeTableNode node) {
+ super(node);
+ }
+
+ @Override
+ public int getColumnCount() {
+ return 2;
+ }
+
+ @Override
+ public Class getColumnClass(final 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(final Object node, final int column) {
+ Object result = null;
+ if (node instanceof DefaultMutableTreeNode) {
+ final DefaultMutableTreeNode defNode = (DefaultMutableTreeNode) node;
+ if (defNode.getUserObject() instanceof ImportFile) {
+ final 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(final 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(final Object node, final int column) {
+ if (column == A_IMPORTER) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * Called when done editing a cell.
+ */
+ @Override
+ public void setValueAt(final Object value, final Object node, final int column) {
+ if (node instanceof DefaultMutableTreeNode) {
+ final DefaultMutableTreeNode defNode = (DefaultMutableTreeNode) node;
+ if (defNode.getUserObject() instanceof ImportFile) {
+ final ImportFile fichier = (ImportFile) defNode.getUserObject();
+ switch (column) {
+ case NOM_FICHIER: // should never happen in our case
+ break;
+ case A_IMPORTER:
+ final 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) {
+ this.propagateCheckValueAbove(valeur, defNode);
+ }
+ // dans le cas d'un répertoire, on propage aussi vers le bas
+ if (!fichier.isFile()) {
+ this.propagateCheckValueBelow(valeur, defNode);
+ }
+ this.nodesChanged((DefaultMutableTreeNode) this.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(final boolean value, final DefaultMutableTreeNode node) {
+ ((ImportFile) node.getUserObject()).setToBeImported(value);
+ if (node.getParent() != null) {
+ this.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(final boolean value, final DefaultMutableTreeNode node) {
+ ((ImportFile) node.getUserObject()).setToBeImported(value);
+ if (node.getChildCount() > 0) {
+ for (final Enumeration enumerator = node.children(); enumerator.hasMoreElements();) {
+ final DefaultMutableTreeNode child = (DefaultMutableTreeNode) enumerator.nextElement();
+ this.propagateCheckValueBelow(value, child);
+ }
+ }
+ }
+
+ /**
+ * Returns the list of the file to export.
+ *
+ * @return A List of files to export
+ */
+ public List<ImportFile> getFilesToImportList() {
+ final List<ImportFile> result = new Vector<ImportFile>();
+
+ final DefaultMutableTreeNode root = (DefaultMutableTreeNode) this.getRoot();
+ for (final Enumeration enumerator = root.depthFirstEnumeration(); enumerator.hasMoreElements();) {
+ final DefaultMutableTreeNode node = (DefaultMutableTreeNode) enumerator.nextElement();
+ final 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() {
+ final DefaultMutableTreeNode root = (DefaultMutableTreeNode) this.getRoot();
+ for (final Enumeration enumerator = root.depthFirstEnumeration(); enumerator.hasMoreElements();) {
+ final DefaultMutableTreeNode node = (DefaultMutableTreeNode) enumerator.nextElement();
+ final ImportFile f = (ImportFile) node.getUserObject();
+ f.setToBeImported(true);
+ }
+ this.nodesChanged(root);
+ }
+
+ /**
+ * Uncheck each entry, removing them from the import list
+ */
+ public void selectNone() {
+ final DefaultMutableTreeNode root = (DefaultMutableTreeNode) this.getRoot();
+ for (final Enumeration enumerator = root.depthFirstEnumeration(); enumerator.hasMoreElements();) {
+ final DefaultMutableTreeNode node = (DefaultMutableTreeNode) enumerator.nextElement();
+ final ImportFile f = (ImportFile) node.getUserObject();
+ f.setToBeImported(false);
+ }
+ this.nodesChanged(root);
+ }
+
+ public boolean isLeaf(final TreeTableNode node) {
+ final boolean ret = super.isLeaf(node);
+ logger.debug("isLeaf(" + node + ") -> " + ret);
+ return ret;
+ }
+
+ protected void nodesChanged(final DefaultMutableTreeNode root) {
+ final TreeModelEvent evt = new TreeModelEvent(this, new TreePath(root));
+ for (final TreeModelListener l : this.getTreeModelListeners()) {
+ l.treeNodesChanged(evt);
+ }
+ }
}
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})
+ * 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();
+ /**
+ * 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();
}
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;
+import fr.gouv.finances.cp.xemelios.updater.AbstractConfigurator;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+
/**
- * Vérifie la présence de xemelios.date.format dans xemelios.properties
- * et l'ajoute si manquant
+ * 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");
- }
- }
+ @Override
+ public void run() throws Exception {
+ if (this.mw.getEnvProperties().getProperty(Constants.SYS_PROP_DATE_FORMAT) == null) {
+ final Properties localProperties = new Properties();
+ final File xemeliosPropertiesFile = new File(new File(this.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);
+ this.mw.getEnvProperties().setProperty(Constants.SYS_PROP_DATE_FORMAT, "dd/MM/yyyy");
+ }
+ }
}
package fr.gouv.finances.cp.xemelios.ui.patches;
-import fr.gouv.finances.cp.xemelios.updater.AbstractConfigurator;
-import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
-import fr.gouv.finances.dgfip.utils.xml.SAXWriter;
-import fr.gouv.finances.dgfip.xemelios.common.Constants;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Properties;
+
import javax.xml.XMLConstants;
import javax.xml.parsers.SAXParser;
+
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.AttributesImpl;
+import fr.gouv.finances.cp.xemelios.updater.AbstractConfigurator;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
+import fr.gouv.finances.dgfip.utils.xml.SAXWriter;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+
/**
- * Vient faire des modifications dans le log4j.xml
- * Ajoute le namespace, ajoute une entrée pour les logs de ToTEM, DSC, print-comp, etc...
+ * Vient faire des modifications dans le log4j.xml Ajoute le namespace, ajoute une entrée pour les logs de ToTEM, DSC, print-comp, etc...
+ *
* @author cmarchand
*/
public class Log4JPatch extends AbstractConfigurator {
- @Override
- public void run() throws Exception {
- if(!"true".equals(props.getProperty(Constants.SYS_PROP_LOG4J_PATCHED))) {
- String log4jConfFile = null;
- if (props.getProperty(Constants.SYS_PROP_LOG4J) != null) {
- log4jConfFile = props.getProperty(Constants.SYS_PROP_LOG4J);
- } else {
- log4jConfFile = "log4j.xml";
- }
- File log4JFile = new File(log4jConfFile);
- if(log4JFile.exists()) {
- File newLog4J = new File(log4JFile.getParentFile(), "log4j-new.xml");
- if(!newLog4J.exists()) {
- FileOutputStream fos = new FileOutputStream(newLog4J);
- SAXWriter saxWriter = new SAXWriter(fos, "UTF-8") {
- private boolean frComptesMissing = true;
- private boolean orgXemeliosMissing = true;
- private ArrayList<String> appenders = new ArrayList<String>();
-
- @Override
- public void startDocument() throws SAXException {
- super.startDocument();
- super.output("<!DOCTYPE log4j:configuration PUBLIC \"-//Apache Software Foundation//DTD log4j Configuration 1.0//EN\" \"log4j.dtd\">\n");
- }
-
- @Override
- public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
- if("configuration".equals(localName)) {
- super.startPrefixMapping("log4j", "http://jakarta.apache.org/log4j/");
- super.startElement("http://jakarta.apache.org/log4j/", localName, qName, atts);
- } else {
- super.startElement(uri, localName, qName, atts);
- }
- if("logger".equals(localName)) {
- String loggerName = atts.getValue("name");
- if(loggerName.equals("org.xemelios"))
- orgXemeliosMissing = false;
- else if("fr.ccomptes".equals(loggerName))
- frComptesMissing = false;
- }
- if("appender".equals(localName)) {
- String appenderName = atts.getValue("name");
- if(!appenderName.equals("console.appender"))
- appenders.add(appenderName);
- }
- }
- @Override
- public void endElement(String uri, String localName, String qName) throws SAXException {
- if("configuration".equals(localName)) {
- AttributesImpl debugAttrs = new AttributesImpl();
- debugAttrs.addAttribute(XMLConstants.NULL_NS_URI, "value", "value", "xs:string", "debug");
- AttributesImpl appenderAttrs = new AttributesImpl();
- appenderAttrs.addAttribute(XMLConstants.NULL_NS_URI, "ref", "ref", "xs:string", appenders.isEmpty() ? "rollingFile" : appenders.get(0));
-
- if(orgXemeliosMissing) {
- AttributesImpl attrs = new AttributesImpl();
- attrs.addAttribute(XMLConstants.NULL_NS_URI, "name", "name", "xs:string", "org.xemelios");
- super.startElement(XMLConstants.NULL_NS_URI, "logger", "logger", attrs);
- super.startElement(XMLConstants.NULL_NS_URI, "level", "level", debugAttrs);
- super.endElement(XMLConstants.NULL_NS_URI, "level", "level");
- super.startElement(XMLConstants.NULL_NS_URI, "appender-ref", "appender-ref", appenderAttrs);
- super.endElement(XMLConstants.NULL_NS_URI, "appender-ref", "appender-ref");
- super.endElement(XMLConstants.NULL_NS_URI, "logger", "logger");
- }
- if(frComptesMissing) {
- AttributesImpl attrs = new AttributesImpl();
- attrs.addAttribute(XMLConstants.NULL_NS_URI, "name", "name", "xs:string", "fr.ccomptes");
- super.startElement(XMLConstants.NULL_NS_URI, "logger", "logger", attrs);
- super.startElement(XMLConstants.NULL_NS_URI, "level", "level", debugAttrs);
- super.endElement(XMLConstants.NULL_NS_URI, "level", "level");
- super.startElement(XMLConstants.NULL_NS_URI, "appender-ref", "appender-ref", appenderAttrs);
- super.endElement(XMLConstants.NULL_NS_URI, "appender-ref", "appender-ref");
- super.endElement(XMLConstants.NULL_NS_URI, "logger", "logger");
- }
-
- super.endElement("http://jakarta.apache.org/log4j/", localName, qName);
- super.endPrefixMapping("log4j");
- } else {
- super.endElement(uri, localName, qName);
- }
- }
-
- @Override
- public void fatalError(SAXParseException e) throws SAXException {
- // super.fatalError(e);
- }
-
- };
- SAXParser parser = FactoryProvider.getSaxParserFactory().newSAXParser();
- parser.parse(log4jConfFile, saxWriter);
- fos.flush(); fos.close();
-
- // pour le moment, on reste là on ne supprime pas
- log4JFile.delete();
- newLog4J.renameTo(log4JFile);
- // on inscrit maintenant la modification pour ne plus repatcher le fichier
- try {
- 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_LOG4J_PATCHED, "true");
- localProperties.store(new FileOutputStream(xemeliosPropertiesFile), null);
- } catch(Exception ex) {
- // ici, ca peut planter si il n'y a pas de xemelios.properties
- }
- }
- }
- }
- setPreviousConfigurator(new DateFormatPatch());
- }
+ @Override
+ public void run() throws Exception {
+ if (!"true".equals(this.props.getProperty(Constants.SYS_PROP_LOG4J_PATCHED))) {
+ String log4jConfFile = null;
+ if (this.props.getProperty(Constants.SYS_PROP_LOG4J) != null) {
+ log4jConfFile = this.props.getProperty(Constants.SYS_PROP_LOG4J);
+ } else {
+ log4jConfFile = "log4j.xml";
+ }
+ final File log4JFile = new File(log4jConfFile);
+ if (log4JFile.exists()) {
+ final File newLog4J = new File(log4JFile.getParentFile(), "log4j-new.xml");
+ if (!newLog4J.exists()) {
+ final FileOutputStream fos = new FileOutputStream(newLog4J);
+ final SAXWriter saxWriter = new SAXWriter(fos, "UTF-8") {
+ private boolean frComptesMissing = true;
+ private boolean orgXemeliosMissing = true;
+ private final ArrayList<String> appenders = new ArrayList<String>();
+
+ @Override
+ public void startDocument() throws SAXException {
+ super.startDocument();
+ super.output("<!DOCTYPE log4j:configuration PUBLIC \"-//Apache Software Foundation//DTD log4j Configuration 1.0//EN\" \"log4j.dtd\">\n");
+ }
+
+ @Override
+ public void startElement(final String uri, final String localName, final String qName, final Attributes atts) throws SAXException {
+ if ("configuration".equals(localName)) {
+ super.startPrefixMapping("log4j", "http://jakarta.apache.org/log4j/");
+ super.startElement("http://jakarta.apache.org/log4j/", localName, qName, atts);
+ } else {
+ super.startElement(uri, localName, qName, atts);
+ }
+ if ("logger".equals(localName)) {
+ final String loggerName = atts.getValue("name");
+ if (loggerName.equals("org.xemelios")) {
+ this.orgXemeliosMissing = false;
+ } else if ("fr.ccomptes".equals(loggerName)) {
+ this.frComptesMissing = false;
+ }
+ }
+ if ("appender".equals(localName)) {
+ final String appenderName = atts.getValue("name");
+ if (!appenderName.equals("console.appender")) {
+ this.appenders.add(appenderName);
+ }
+ }
+ }
+
+ @Override
+ public void endElement(final String uri, final String localName, final String qName) throws SAXException {
+ if ("configuration".equals(localName)) {
+ final AttributesImpl debugAttrs = new AttributesImpl();
+ debugAttrs.addAttribute(XMLConstants.NULL_NS_URI, "value", "value", "xs:string", "debug");
+ final AttributesImpl appenderAttrs = new AttributesImpl();
+ appenderAttrs.addAttribute(XMLConstants.NULL_NS_URI, "ref", "ref", "xs:string", this.appenders.isEmpty() ? "rollingFile" : this.appenders.get(0));
+
+ if (this.orgXemeliosMissing) {
+ final AttributesImpl attrs = new AttributesImpl();
+ attrs.addAttribute(XMLConstants.NULL_NS_URI, "name", "name", "xs:string", "org.xemelios");
+ super.startElement(XMLConstants.NULL_NS_URI, "logger", "logger", attrs);
+ super.startElement(XMLConstants.NULL_NS_URI, "level", "level", debugAttrs);
+ super.endElement(XMLConstants.NULL_NS_URI, "level", "level");
+ super.startElement(XMLConstants.NULL_NS_URI, "appender-ref", "appender-ref", appenderAttrs);
+ super.endElement(XMLConstants.NULL_NS_URI, "appender-ref", "appender-ref");
+ super.endElement(XMLConstants.NULL_NS_URI, "logger", "logger");
+ }
+ if (this.frComptesMissing) {
+ final AttributesImpl attrs = new AttributesImpl();
+ attrs.addAttribute(XMLConstants.NULL_NS_URI, "name", "name", "xs:string", "fr.ccomptes");
+ super.startElement(XMLConstants.NULL_NS_URI, "logger", "logger", attrs);
+ super.startElement(XMLConstants.NULL_NS_URI, "level", "level", debugAttrs);
+ super.endElement(XMLConstants.NULL_NS_URI, "level", "level");
+ super.startElement(XMLConstants.NULL_NS_URI, "appender-ref", "appender-ref", appenderAttrs);
+ super.endElement(XMLConstants.NULL_NS_URI, "appender-ref", "appender-ref");
+ super.endElement(XMLConstants.NULL_NS_URI, "logger", "logger");
+ }
+
+ super.endElement("http://jakarta.apache.org/log4j/", localName, qName);
+ super.endPrefixMapping("log4j");
+ } else {
+ super.endElement(uri, localName, qName);
+ }
+ }
+
+ @Override
+ public void fatalError(final SAXParseException e) throws SAXException {
+ // super.fatalError(e);
+ }
+ };
+ final SAXParser parser = FactoryProvider.getSaxParserFactory().newSAXParser();
+ parser.parse(log4jConfFile, saxWriter);
+ fos.flush();
+ fos.close();
+ // pour le moment, on reste là on ne supprime pas
+ log4JFile.delete();
+ newLog4J.renameTo(log4JFile);
+ // on inscrit maintenant la modification pour ne plus repatcher le fichier
+ try {
+ final Properties localProperties = new Properties();
+ final File xemeliosPropertiesFile = new File(new File(this.mw.getEnvProperties().getProperty("xemelios.root")), "xemelios.properties");
+ localProperties.load(new FileInputStream(xemeliosPropertiesFile));
+ localProperties.setProperty(Constants.SYS_PROP_LOG4J_PATCHED, "true");
+ localProperties.store(new FileOutputStream(xemeliosPropertiesFile), null);
+ } catch (final Exception ex) {
+ // ici, ca peut planter si il n'y a pas de xemelios.properties
+ }
+ }
+ }
+ }
+ this.setPreviousConfigurator(new DateFormatPatch());
+ }
}
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.common.config.PjRefHandler;
import fr.gouv.finances.dgfip.xemelios.data.DataHandler;
+import fr.gouv.finances.dgfip.xemelios.data.DataResultSet;
/**
* 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();
- }
+ 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(final ListeResultatModel lrm, final TreeSet<DataHandler> input, final DataResultSet rs) {
+ super();
+ this.lrm = lrm;
+ this.data = new ArrayList<DataHandler>();
+ this.rs = rs;
+ for (final DataHandler dh : input) {
+ for (int i = 0; i < lrm.getListeChamps().size(); i++) {
+ try {
+ dh.getValueAtColumn(i);
+ } catch (final Throwable t) {
+ }
+ }
+ this.data.add(dh);
+ }
+ if (this.data.size() > 0) {
+ final DataHandler dh = this.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(final ListeResultatModel lrm, final Vector<DataHandler> input) {
+ super();
+ this.lrm = lrm;
+ this.data = new ArrayList<DataHandler>();
+ for (final DataHandler dh : input) {
+ for (int i = 0; i < lrm.getListeChamps().size(); i++) {
+ try {
+ dh.getValueAtColumn(i);
+ } catch (final Throwable t) {
+ }
+ }
+ this.data.add(dh);
+ }
+ if (this.data.size() > 0) {
+ final DataHandler dh = this.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 (this.data == null) {
+ return 0;
+ }
+ final int ret = this.data.size();
+ return ret;
+ }
+
+ @Override
+ public int getColumnCount() {
+ return this.lrm.getListeChamps().size();
+ }
+
+ @Override
+ public String getColumnName(final int col) {
+ final ChampModel cm = this.lrm.getListeChamps().elementAt(col);
+ return cm.getLibelle();
+ }
+
+ @Override
+ public Class<?> getColumnClass(final int col) {
+ if (this.datatypes == null) {
+ this.datatypes = new Class[this.getColumnCount()];
+ }
+ if (this.datatypes[col] == null) {
+ final ChampModel cm = this.lrm.getListeChamps().elementAt(col);
+ this.datatypes[col] = cm.getDataClass();
+ }
+ return this.datatypes[col];
+ }
+
+ @Override
+ public boolean isCellEditable(final int row, final int column) {
+ return this.getColumnClass(column).equals(PjRefHandler.class);
+ }
+
+ @Override
+ public Object getValueAt(final int row, final int col) {
+ // try {
+ final Object o = this.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(final int row, final int col) {
+ final Object ret = this.getRowAt(row, col).getInnerDataAt(col);
+ return (ret == null ? "" : ret);
+ }
+
+ public DataHandler getRowAt(final int row, final int col) {
+ final DataHandler dh = this.data.get(row);
+ return dh;
+ }
+
+ @Override
+ public void setValueAt(final Object arg0, final int arg1, final int arg2) {
+ }
+
+ // @Override
+ // public void addTableModelListener(TableModelListener arg0) {
+ // }
+ // @Override
+ // public void removeTableModelListener(TableModelListener arg0) {
+ // }
+
+ public void setData(final TreeSet<DataHandler> input) {
+ this.data = new ArrayList<DataHandler>();
+ for (final DataHandler dh : input) {
+ for (int i = 0; i < this.lrm.getListeChamps().size(); i++) {
+ try {
+ dh.getValueAtColumn(i);
+ } catch (final Throwable t) {
+ }
+ }
+ this.data.add(dh);
+ }
+ if (this.data.size() > 0) {
+ final DataHandler dh = this.data.get(0);
+ this.orderByCol = dh.getOrderByColumn();
+ this.sortOrder = dh.getSortOrder();
+ } else {
+ this.orderByCol = 0;
+ this.sortOrder = DataHandler.ORDER_ASC;
+ }
+ }
+
+ public int sortRequired(final int col) {
+ logger.debug("sort required: " + col);
+ if (this.data == null || this.data.size() == 0) {
+ return 0;
+ }
+ int locOrderByCol = 0;
+ int locSortOrder = 0;
+ final DataHandler dh = this.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;
+ final TreeSet<DataHandler> ts = new TreeSet<DataHandler>();
+ for (final DataHandler dh2 : this.data) {
+ dh2.setOrderByColumn(locOrderByCol, locSortOrder);
+ ts.add(dh2);
+ }
+ this.setData(ts);
+ this.fireTableStructureChanged();
+ return locSortOrder;
+ }
+
+ /**
+ * @return Returns the orderByCol.
+ */
+ public int getOrderByCol() {
+ return this.orderByCol;
+ }
+
+ /**
+ * @return Returns the sortOrder.
+ */
+ public int getSortOrder() {
+ return this.sortOrder;
+ }
+
+ public String getCsvBuffer(final String fieldSeparator, final boolean exportAll, final int[] selectedRows) {
+ final String lineSeparator = System.getProperty("line.separator");
+ final DecimalFormat df = new DecimalFormat("#0.00");
+ final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
+ final StringBuffer buff = new StringBuffer();
+ for (final ChampModel cm : this.lrm.getListeChamps()) {
+ buff.append(cm.getLibelle()).append(fieldSeparator);
+ }
+ buff.append(lineSeparator);
+ for (int row = 0; row < this.getRowCount(); row++) {
+ if (exportAll || Arrays.binarySearch(selectedRows, row) >= 0) {
+ for (int col = 0; col < this.getColumnCount(); col++) {
+ final Object value = this.getValueAt(row, col);
+ String strVal = null;
+ if (value instanceof Float) {
+ // double d = ((Float)value).doubleValue();
+ strVal = df.format(value);
+ strVal = strVal.replaceAll("\\.", ",");
+ logger.debug("double: " + strVal);
+ } else if (value instanceof Amount) {
+ // double d = ((Amount)value).doubleValue();
+ strVal = df.format(value);
+ strVal = strVal.replaceAll("\\.", ",");
+ logger.debug("amount: " + strVal);
+ } else if (value instanceof Date) {
+ strVal = sdf.format((Date) value);
+ } else {
+ strVal = value == null ? "" : value.toString();
+ final 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(final String fieldSeparator, final String lineHeader) {
+ final String lineSeparator = System.getProperty("line.separator");
+ final DecimalFormat df = new DecimalFormat("#0.00");
+ final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
+ final StringBuffer buff = new StringBuffer();
+ for (int row = 0; row < this.getRowCount(); row++) {
+ buff.append(lineHeader);
+ for (int col = 0; col < this.getColumnCount(); col++) {
+ final Object value = this.getValueAt(row, col);
+ String strVal = null;
+ if (value instanceof Float) {
+ // double d = ((Float)value).doubleValue();
+ strVal = df.format(value);
+ strVal = strVal.replaceAll("\\.", ",");
+ logger.debug("double: " + strVal);
+ } else if (value instanceof Amount) {
+ // double d = ((Amount)value).doubleValue();
+ strVal = df.format(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() {
+ this.lrm = null;
+ this.data.clear();
+ this.data = null;
+ if (this.datatypes != null) {
+ for (int i = 0; i < this.datatypes.length; i++) {
+ this.datatypes[i] = null;
+ }
+ }
+ }
+
+ public DataResultSet getResultSet() {
+ return this.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(final int columnIndex) {
+ boolean result = false;
+ final Vector<ChampModel> listeChamps = this.lrm.getListeChamps();
+ if (columnIndex <= listeChamps.size()) {
+ final 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(final int columnIndex) {
+ String result = "";
+ final Vector<ChampModel> listeChamps = this.lrm.getListeChamps();
+ if (columnIndex <= listeChamps.size()) {
+ final 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(final int columnIndex) {
+ String result = "";
+ final Vector<ChampModel> listeChamps = this.lrm.getListeChamps();
+ if (columnIndex <= listeChamps.size()) {
+ final ChampModel cm = listeChamps.get(columnIndex);
+ result = this.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(final int columnIndex) {
+ String result = "";
+ final Vector<ChampModel> listeChamps = this.lrm.getListeChamps();
+ if (columnIndex <= listeChamps.size()) {
+ final ChampModel cm = listeChamps.get(columnIndex);
+ result = cm.getLibelle();
+ }
+ return result;
+ }
+
+ public Vector<ChampModel> getListeChamps() {
+ return this.lrm.getListeChamps();
+ }
+
+ public Vector<HiddenModel> getHiddens() {
+ return this.lrm.getHiddens();
+ }
+
+ public ListeResultatModel getListeResultat() {
+ return this.lrm;
+ }
+
+ public Pair getCollectivite() {
+ return this.rs.getCollectivite();
+ }
+
+ public Pair getBudget() {
+ return this.rs.getBudget();
+ }
}
import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
import fr.gouv.finances.cp.utils.ui.IhmFactory;
+import fr.gouv.finances.cp.xemelios.ui.search.PnlSearch;
+import fr.gouv.finances.cp.xemelios.ui.search.ResultDisplayerThread;
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.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);
+ 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(final PnlSearch parent) {
+ super();
+ this.pnlSearch = parent;
+ this.initComponents();
+ }
+
+ protected void initComponents() {
+ final IhmFactory iF = IhmFactory.newInstance();
+ final FlowLayout fl = new FlowLayout(FlowLayout.LEFT);
+ fl.setHgap(0);
+ fl.setVgap(0);
+ this.setLayout(fl);
+ this.pbFirstPage = new JButton(IhmFactory.getIconFromResource(ImageResources.PAGE_FIRST));
+ this.pbFirstPage.setPreferredSize(buttonDim);
+ this.pbFirstPage.setToolTipText("première page");
+ this.add(this.pbFirstPage);
+
+ this.pbPreviousPage = new JButton(IhmFactory.getIconFromResource(ImageResources.PAGE_PREVIOUS));
+ this.pbPreviousPage.setPreferredSize(buttonDim);
+ this.add(this.pbPreviousPage);
+ this.pbPreviousPage.setToolTipText("page précédente");
+
+ this.cbxPages = new JComboBox();
+ this.cbxPages.setEditable(false);
+ this.cbxPages.setPreferredSize(new Dimension(50, (int) buttonDim.getHeight()));
+ this.cbxPages.setPrototypeDisplayValue("0000");
+ this.cbxPages.addItem("");
+ this.add(this.cbxPages);
+
+ this.label = new JLabel("/ ");
+ this.add(this.label);
+
+ this.pbNextPage = new JButton(IhmFactory.getIconFromResource(ImageResources.PAGE_NEXT));
+ this.pbNextPage.setPreferredSize(buttonDim);
+ this.pbNextPage.setToolTipText("page suivante");
+ this.add(this.pbNextPage);
+
+ this.pbLastPage = new JButton(IhmFactory.getIconFromResource(ImageResources.PAGE_LAST));
+ this.pbLastPage.setPreferredSize(buttonDim);
+ this.pbLastPage.setToolTipText("dernière page");
+ this.add(this.pbLastPage);
+
+ this.reset();
+ }
+
+ public void updateData(final DataResultSet rs) {
+ this.reset();
+ this.pageCount = rs.getEstimatedPageCount();
+ this.cbxPages.removeAllItems();
+ for (int i = 1; i <= this.pageCount; i++) {
+ this.cbxPages.addItem(new Integer(i));
+ }
+ this.currentPage = rs.getCurrentPage();
+ this.cbxPages.setSelectedItem(new Integer(this.currentPage + 1));
+ final StringBuilder sb = new StringBuilder();
+ sb.append("/ ").append(this.pageCount);
+ while (sb.length() < 6) {
+ sb.append(" ");
+ }
+ this.label.setText(sb.toString());
+ if (rs.hasPreviousPage()) {
+ this.pbPreviousPage.setEnabled(true);
+ this.pbPreviousPage.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ PageSeeker.this.pnlSearch.setCursor(new Cursor(Cursor.WAIT_CURSOR));
+ PageSeeker.this.pnlSearch.setSearchEnabled(false);
+ // MainWindow.getInstance().startWaiter();
+ final EtatResultTableModel etrm = (EtatResultTableModel) PageSeeker.this.pnlSearch.getTable().getModel();
+ final DataResultSet rs = etrm.getResultSet();
+ final OtherPageSeeker ops = new OtherPageSeeker(rs, rs.getListeResultatModel(), PageSeeker.this.pnlSearch.getElementModel(), PageSeeker.this.pnlSearch, OtherPageSeeker.PREVIOUS_PAGE);
+ if (SwingUtilities.isEventDispatchThread()) {
+ ops.run();
+ } else {
+ SwingUtilities.invokeLater(ops);
+ }
+ }
+ });
+ this.pbFirstPage.setEnabled(true);
+ this.pbFirstPage.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ PageSeeker.this.pnlSearch.setCursor(new Cursor(Cursor.WAIT_CURSOR));
+ PageSeeker.this.pnlSearch.setSearchEnabled(false);
+ // MainWindow.getInstance().startWaiter();
+ final EtatResultTableModel etrm = (EtatResultTableModel) PageSeeker.this.pnlSearch.getTable().getModel();
+ final DataResultSet rs = etrm.getResultSet();
+ final OtherPageSeeker ops = new OtherPageSeeker(rs, rs.getListeResultatModel(), PageSeeker.this.pnlSearch.getElementModel(), PageSeeker.this.pnlSearch, OtherPageSeeker.FIRST_PAGE);
+ if (SwingUtilities.isEventDispatchThread()) {
+ ops.run();
+ } else {
+ SwingUtilities.invokeLater(ops);
+ }
+ }
+ });
+ } else {
+ this.pbPreviousPage.setEnabled(false);
+ this.pbFirstPage.setEnabled(false);
+ }
+ if (rs.hasNextPage()) {
+ this.pbNextPage.setEnabled(true);
+ this.pbNextPage.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ PageSeeker.this.pnlSearch.setCursor(new Cursor(Cursor.WAIT_CURSOR));
+ PageSeeker.this.pnlSearch.setSearchEnabled(false);
+ // MainWindow.getInstance().startWaiter();
+ final EtatResultTableModel etrm = (EtatResultTableModel) PageSeeker.this.pnlSearch.getTable().getModel();
+ final DataResultSet rs = etrm.getResultSet();
+ final OtherPageSeeker ops = new OtherPageSeeker(rs, rs.getListeResultatModel(), PageSeeker.this.pnlSearch.getElementModel(), PageSeeker.this.pnlSearch, OtherPageSeeker.NEXT_PAGE);
+ if (SwingUtilities.isEventDispatchThread()) {
+ ops.run();
+ } else {
+ SwingUtilities.invokeLater(ops);
+ }
+ }
+ });
+ this.pbLastPage.setEnabled(true);
+ this.pbLastPage.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ PageSeeker.this.pnlSearch.setCursor(new Cursor(Cursor.WAIT_CURSOR));
+ PageSeeker.this.pnlSearch.setSearchEnabled(false);
+ // MainWindow.getInstance().startWaiter();
+ final EtatResultTableModel etrm = (EtatResultTableModel) PageSeeker.this.pnlSearch.getTable().getModel();
+ final DataResultSet rs = etrm.getResultSet();
+ final OtherPageSeeker ops = new OtherPageSeeker(rs, rs.getListeResultatModel(), PageSeeker.this.pnlSearch.getElementModel(), PageSeeker.this.pnlSearch, OtherPageSeeker.LAST_PAGE);
+ if (SwingUtilities.isEventDispatchThread()) {
+ ops.run();
+ } else {
+ SwingUtilities.invokeLater(ops);
+ }
+ }
+ });
+ } else {
+ this.pbNextPage.setEnabled(false);
+ this.pbLastPage.setEnabled(false);
+ }
+ if (this.pageCount > 0) {
+ this.cbxPages.setEnabled(true);
+ this.cbxPages.addItemListener(new ItemListener() {
+ @Override
+ public void itemStateChanged(final ItemEvent e) {
+ if (e.getStateChange() == ItemEvent.SELECTED) {
+ logger.debug("ITEM SELECTED");
+ final Integer i = (Integer) e.getItem();
+ PageSeeker.this.pnlSearch.setCursor(new Cursor(Cursor.WAIT_CURSOR));
+ PageSeeker.this.pnlSearch.setSearchEnabled(false);
+ // MainWindow.getInstance().startWaiter();
+ final EtatResultTableModel etrm = (EtatResultTableModel) PageSeeker.this.pnlSearch.getTable().getModel();
+ final DataResultSet rs = etrm.getResultSet();
+ final OtherPageSeeker ops = new OtherPageSeeker(rs, rs.getListeResultatModel(), PageSeeker.this.pnlSearch.getElementModel(), PageSeeker.this.pnlSearch, OtherPageSeeker.SET_PAGE, i.intValue() - 1);
+ if (SwingUtilities.isEventDispatchThread()) {
+ ops.run();
+ } else {
+ SwingUtilities.invokeLater(ops);
+ }
+ }
+ }
+ });
+ } else {
+ this.cbxPages.setEnabled(false);
+ }
+ }
+
+ public void reset() {
+ this.pbFirstPage.setEnabled(false);
+ this.pbPreviousPage.setEnabled(false);
+ this.pbLastPage.setEnabled(false);
+ this.pbNextPage.setEnabled(false);
+ this.cbxPages.setEnabled(false);
+ this.cbxPages.removeAllItems();
+ for (final ActionListener al : this.pbFirstPage.getActionListeners()) {
+ this.pbFirstPage.removeActionListener(al);
+ }
+ for (final ActionListener al : this.pbPreviousPage.getActionListeners()) {
+ this.pbPreviousPage.removeActionListener(al);
+ }
+ for (final ActionListener al : this.pbNextPage.getActionListeners()) {
+ this.pbNextPage.removeActionListener(al);
+ }
+ for (final ActionListener al : this.pbLastPage.getActionListeners()) {
+ this.pbLastPage.removeActionListener(al);
+ }
+ for (final ItemListener il : this.cbxPages.getItemListeners()) {
+ this.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(final DataResultSet rs, final ListeResultatModel lrm, final ElementModel em, final PnlSearch sw, final int way) {
+ super();
+ this.rs = rs;
+ this.lrm = lrm;
+ this.em = em;
+ this.sw = sw;
+ this.way = way;
+ }
- 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() {
- @Override
- 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() {
- @Override
- 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() {
- @Override
- 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() {
- @Override
- 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() {
- @Override
- 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);
- }
+ public OtherPageSeeker(final DataResultSet rs, final ListeResultatModel lrm, final ElementModel em, final PnlSearch sw, final int way, final int page) {
+ super();
+ this.rs = rs;
+ this.lrm = lrm;
+ this.em = em;
+ this.sw = sw;
+ this.way = way;
+ this.page = page;
+ }
- 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;
- }
- @Override
- 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);
- }
- }
- }
+ @Override
+ public void run() {
+ final long start = System.currentTimeMillis();
+ this.sw.getPageSeeker().reset();
+ try {
+ switch (this.way) {
+ case FIRST_PAGE:
+ this.rs.firstPage();
+ break;
+ case PREVIOUS_PAGE:
+ this.rs.previousPage();
+ break;
+ case NEXT_PAGE:
+ this.rs.nextPage();
+ break;
+ case LAST_PAGE:
+ this.rs.lastPage();
+ break;
+ case SET_PAGE:
+ this.rs.setPage(this.page);
+ }
+ final ResultDisplayerThread rdt = new ResultDisplayerThread(this.rs, this.lrm, start, this.em, this.sw);
+ SwingUtilities.invokeLater(rdt);
+ } catch (final DataAccessException daEx) {
+ new DisplayExceptionDlg(SwingUtilities.getWindowAncestor(this.sw), daEx);
+ } catch (final DataConfigurationException dcEx) {
+ new DisplayExceptionDlg(SwingUtilities.getWindowAncestor(this.sw), dcEx);
+ }
+ }
+ }
}
package fr.gouv.finances.cp.xemelios.ui.resulttable;
-import fr.gouv.finances.cp.utils.PropertiesExpansion;
+import java.awt.Color;
import java.awt.Component;
import java.awt.Point;
import java.awt.Rectangle;
import org.apache.log4j.Logger;
import org.jdesktop.swingx.JXTable;
+import org.jdesktop.swingx.decorator.ColorHighlighter;
+import org.jdesktop.swingx.decorator.HighlightPredicate;
-import fr.gouv.finances.dgfip.utils.Amount;
-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.IhmFactory;
+import fr.gouv.finances.cp.xemelios.ui.search.PnlSearch;
+import fr.gouv.finances.dgfip.utils.Amount;
+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.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.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.PJRefInfo;
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;
+import fr.gouv.finances.dgfip.xemelios.utils.XmlUtils;
/**
* 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.");
- }
-
-
- }
+ 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 final ElementModel em;
+ private final PnlSearch searchWindow;
+ private DataImpl impl = null;
+ protected XemeliosUser user;
+ private final PropertiesExpansion applicationProperties;
+
+ @SuppressWarnings("serial")
+ public ResultTable(final TableModel model, final PnlSearch sw, final ElementModel em, final XemeliosUser user, final PropertiesExpansion applicationProperties) {
+ super(model);
+ this.em = em;
+ this.searchWindow = sw;
+ this.user = user;
+ this.applicationProperties = applicationProperties;
+ final AmountRenderer amrenderer = new AmountRenderer();
+ this.setDefaultRenderer(Amount.class, amrenderer);
+ final DateRenderer drenderer = new DateRenderer();
+ this.setDefaultRenderer(Date.class, drenderer);
+ final PjRenderer renderer = new PjRenderer();
+ this.setDefaultRenderer(PjRefHandler.class, renderer);
+ this.setDefaultEditor(PjRefHandler.class, new PjEditor(sw.getCurrentCollectivite(), sw.getCurrentBudget()));
+ this.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
+ this.setColumnControlVisible(true);
+ this.setRolloverEnabled(true);
+ if (!"remove".equals(applicationProperties.getProperty("xemelios.jxtable.highlighter"))) {
+ final Color selectedColor = new Color(0xB8, 0xCF, 0xE5);
+ final ColorHighlighter whiteOne = new ColorHighlighter(HighlightPredicate.EVEN, Color.WHITE, Color.BLACK, selectedColor, Color.BLACK);
+ final ColorHighlighter greyOne = new ColorHighlighter(HighlightPredicate.ODD, new Color(0xF0, 0xF0, 0xE0), Color.BLACK, new Color(0xBF, 0xCF, 0xE5), Color.BLACK);
+ this.setHighlighters(whiteOne, greyOne);
+ }
+ final InputMap im = this.getInputMap();
+ final KeyStroke ks = KeyStroke.getKeyStroke("control P");
+ im.put(ks, "print");
+ // pour le menu contextuel
+ final MouseListener popupListener = new PopupListener();
+ this.getTableHeader().addMouseListener(popupListener);
+
+ // double-click sur une ligne pour visualisation dans navigateur
+ this.addMouseListener(new MouseAdapter() {
+ @Override
+ public void mouseClicked(final MouseEvent evt) {
+ final Point p = evt.getPoint();
+ final 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 {
+ this.impl = DataLayerManager.getImplementation();
+ } catch (final 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(final MouseEvent e) {
+ if (!e.isConsumed()) {
+ this.maybeShowPopup(e);
+ }
+ }
+
+ @Override
+ public void mousePressed(final MouseEvent e) {
+ if (!e.isConsumed()) {
+ this.maybeShowPopup(e);
+ }
+ }
+
+ /**
+ * Décide s'il faut afficher le menu contextuel des opérations sur les colonnes
+ */
+ private void maybeShowPopup(final MouseEvent e) {
+ final Point p = e.getPoint();
+ JPopupMenu popup;
+
+ if (e.isPopupTrigger()) {
+ e.consume();
+ final EtatResultTableModel etrm = (EtatResultTableModel) ResultTable.this.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
+ */
+ this.columnIndex = ResultTable.this.convertColumnIndexToModel(ResultTable.this.columnAtPoint(p));
+ boolean showPopup = etrm.isSumOperationPermittedOnColumn(this.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, ...)
+ final PluginModel pm = ResultTable.this.searchWindow.getPluginModel();
+ if (pm != null) {
+ showPopup = showPopup && pm.isSumPossible();
+ }
+ try {
+ if (showPopup) {
+ final DataImpl impl = DataLayerManager.getImplementation();
+ this.operators = impl.getAggregateOperators(etrm.getColumnDatatype(this.columnIndex));
+ if (this.operators.length > 0) {
+ popup = new JPopupMenu();
+ JMenuItem menuItem;
+ for (final Pair ope : this.operators) {
+ menuItem = new JMenuItem(ope.libelle);
+ menuItem.addActionListener(this);
+ popup.add(menuItem);
+ this.operatorList.put(ope.libelle, ope.key);
+ }
+ popup.show(e.getComponent(), e.getX(), e.getY());
+ }
+ }
+ } catch (final 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(final ActionEvent ae) {
+ final JMenuItem item = (JMenuItem) ae.getSource();
+
+ try {
+ final EtatResultTableModel etrm = (EtatResultTableModel) ResultTable.this.searchWindow.getTable().getModel();
+ final DocumentModel dm = ResultTable.this.em.getParent().getParent();
+ String xpath = etrm.getColumnXPath(this.columnIndex);
+ xpath = XmlUtils.normalizeNS(xpath, dm.getNamespaces());
+ logger.debug(xpath);
+ final String resultat = DataLayerManager.getImplementation().calculateAggregate(ResultTable.this.searchWindow.getDocumentModel(), ResultTable.this.em.getParent(), xpath, this.operatorList.get(item.getText()), etrm.getListeChamps().get(this.columnIndex), etrm.getResultSet(),
+ ResultTable.this.user);
+
+ // now we display the result
+ final JDialog dialog = new JDialog();
+ dialog.setTitle(ResultTable.this.searchWindow.getTitle());
+ final JLabel texte = new JLabel(item.getText() + " de " + etrm.getColumnHeader(this.columnIndex) + " : " + resultat);
+ final JButton boutonFermer = new JButton("Fermer");
+ final JButton boutonCopier = new JButton("Copier");
+ boutonCopier.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ final Clipboard system = Toolkit.getDefaultToolkit().getSystemClipboard();
+ final StringSelection ss = new StringSelection(resultat);
+ system.setContents(ss, ss);
+ }
+ });
+ boutonFermer.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ dialog.setVisible(false);
+ dialog.dispose();
+ }
+ });
+
+ final Box haut = Box.createVerticalBox();
+ final 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 (final UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(ResultTable.this.getParent(), ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (final DataConfigurationException dce) {
+ dce.printStackTrace();
+ } catch (final DataAccessException dae) {
+ }
+ }
+ }
+
+ @SuppressWarnings("serial")
+ class PjRenderer extends JButton implements TableCellRenderer {
+
+ public PjRenderer() {
+ this.setOpaque(true);
+ this.setText("...");
+ }
+
+ @Override
+ public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) {
+ this.setForeground(table.getSelectionForeground());
+ this.setBackground(table.getSelectionBackground());
+ if (value != null && value instanceof PjRefHandler) {
+ final PjRefHandler h = (PjRefHandler) value;
+ this.setToolTipText(Integer.toString(h.getPjCount()) + " PJ");
+ } else {
+ this.setToolTipText(null);
+ }
+ return this;
+ }
+ }
+
+ @SuppressWarnings("serial")
+ class AmountRenderer extends DefaultTableCellRenderer {
+ public AmountRenderer() {
+ super();
+ }
+
+ @Override
+ public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) {
+ final Component parent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
+ final JLabel lbl = (JLabel) parent;
+ if (value != null && value instanceof Amount) {
+ final 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(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) {
+ final Component parent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
+ // on cherche le ChampModel associé
+ final int modelColumn = ResultTable.this.convertColumnIndexToModel(column);
+ final EtatResultTableModel etrm = (EtatResultTableModel) table.getModel();
+ final ChampModel cm = etrm.getListeChamps().get(modelColumn);
+ // logger.debug("column="+column+" modelColumn="+modelColumn+" id="+cm.getId());
+ final JLabel lbl = (JLabel) parent;
+ if (value != null && value instanceof Date) {
+ final Date d = (Date) value;
+ String date_format = cm.getDateFormat();
+ if (date_format == null) {
+ date_format = ResultTable.this.applicationProperties.getProperty(Constants.SYS_PROP_DATE_FORMAT);
+ }
+ if (date_format == null) {
+ date_format = "yyyy-MM-dd";
+ }
+ final 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 final 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;
+ this.button = new JButton("...");
+ this.button.setOpaque(true);
+ this.button.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ PjEditor.this.fireEditingStopped();
+ }
+ });
+ }
+
+ @Override
+ public Component getTableCellEditorComponent(final JTable table, final Object value, final boolean isSelected, final int row, final int column) {
+ this.button.setForeground(table.getSelectionForeground());
+ this.button.setBackground(table.getSelectionBackground());
+ this.data = value;
+ final Rectangle rect = table.getCellRect(row, column, false);
+ this.point = rect.getLocation();
+ this.table = table;
+ this.isPushed = true;
+ return this.button;
+ }
+
+ @Override
+ public Object getCellEditorValue() {
+ if (this.isPushed) {
+ final JPopupMenu popup = new JPopupMenu("Pièces jointes");
+ if (this.data instanceof PjRefHandler) {
+ final PjRefHandler pjs = (PjRefHandler) this.data;
+ int count = 0;
+ for (final 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 = ResultTable.this.impl.isPjAvailable(this.collectivite, pj.getNom(), ResultTable.this.user);
+ } catch (final Throwable t) {
+ }
+ if (available) {
+ icon = iconAvailable;
+ } else {
+ icon = iconUnavailable;
+ }
+ }
+ final JMenuItem mnu = new JMenuItem(pj.getNom(), icon);
+ if (available) {
+ mnu.addActionListener(new PjDisplayAction(this.collectivite, this.budget, pj));
+ }
+ // fin modifs
+ popup.add(mnu);
+ }
+ } else {
+ logger.debug(this.data.getClass().getName() + " --> " + this.data.toString());
+ }
+ popup.show(this.table, this.point.x, this.point.y);
+ }
+ this.isPushed = false;
+ return "...";
+ }
+
+ @Override
+ public boolean stopCellEditing() {
+ this.isPushed = false;
+ return super.stopCellEditing();
+ }
+
+ @Override
+ protected void fireEditingStopped() {
+ super.fireEditingStopped();
+ }
+
+ }
+
+ private class PjDisplayAction implements ActionListener {
+ private final Pair collectivite;
+ private final PJRefInfo pj;
+
+ public PjDisplayAction(final Pair collectivite, final Pair budget, final PJRefInfo pj) {
+ super();
+ this.collectivite = collectivite;
+ this.pj = pj;
+ }
+
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ try {
+ final DataImpl impl = DataLayerManager.getImplementation();
+ final PJRef pjRef = impl.getPj(this.collectivite, this.pj.getNom(), ResultTable.this.user);
+ if (pjRef != null) {
+ final File tmpFile = File.createTempFile("tmp-", pjRef.getFileName(), FileUtils.getTempDir());
+ final 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 (final UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(ResultTable.this.getParent(), ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (final DataConfigurationException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (final DataAccessException daEx) {
+ // TODO
+ daEx.printStackTrace();
+ } catch (final IOException ioEx) {
+ // TODO
+ ioEx.printStackTrace();
+ } catch (final 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;
+
+ @Override
+ public String getNamespaceURI(final 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(final 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(final String namespaceURI) {
+ return new StringIterator(this.getPrefix(namespaceURI));
+ }
+ }
+
+ private static class StringIterator<String> implements Iterator<String> {
+ private final String s;
+ private boolean get = false;
+
+ public StringIterator(final String s) {
+ super();
+ this.s = s;
+ }
+
+ @Override
+ public boolean hasNext() {
+ return !this.get;
+ }
+
+ @Override
+ public String next() {
+ this.get = true;
+ return this.s;
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ }
}
package fr.gouv.finances.cp.xemelios.ui.search;
+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;
+
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.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.SourceTargetModel;
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);
- }
+ private static final Logger logger = Logger.getLogger(DlgSearchHelper.class);
+
+ private SearchHelperModel shm;
+ private PnlSearch pnl;
+ private Object returnValue;
+ private InputData inputField;
+ private DocumentModel documentModel;
+ private EtatModel etatModel;
+ private ElementModel elementModel;
+
+ public DlgSearchHelper(final Window parent, final InputData inputField, final SearchHelperModel shm, final SearchContext sCtx) {
+ super(parent, ModalityType.APPLICATION_MODAL);
+ this.shm = shm;
+ this.inputField = inputField;
+ try {
+ this.documentModel = Loader.getDocumentsInfos(null).getDocumentById(shm.getDocumentId());
+ this.etatModel = this.documentModel.getEtatById(shm.getEtatId());
+ this.elementModel = this.etatModel.getElementById(shm.getElementId());
+
+ final 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());
+ }
+
+ this.pnl = new PnlSearch(this.documentModel, this.etatModel, this.elementModel, dp, sCtx.getUser(), MainWindow.getInstance().getEnvProperties()) {
+ @Override
+ public void resizeParent(final 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(final boolean iconified) {
+ // on ne fait rien
+ }
+
+ @Override
+ public void setTitle(final String newTitle) {
+ // rien
+ }
+
+ @Override
+ public void redisplayTitle() {
+ // on ne fait rien
+ }
+
+ @Override
+ public void startWaiter() {
+ DlgSearchHelper.this.getGlassPane().setVisible(true);
+ }
+
+ @Override
+ public void stopWaiter() {
+ DlgSearchHelper.this.getGlassPane().setVisible(false);
+ }
+
+ @Override
+ public boolean canExport() {
+ return false;
+ }
+
+ @Override
+ public void actionOnRowPerformed(final MouseEvent evt, int row) {
+ final String columnId = DlgSearchHelper.this.shm.getReturnValueColumnId();
+ row = ((JXTable) this.getTable()).convertRowIndexToModel(row);
+ final EtatResultTableModel etrm = (EtatResultTableModel) this.getTable().getModel();
+ final DataHandler dh = etrm.getRowAt(row, 0);
+ for (int pos = 0; pos < etrm.getHiddens().size(); pos++) {
+ final HiddenModel hm = etrm.getHiddens().get(pos);
+ if (hm.getName().equals(columnId)) {
+ final Object paramValue = dh.getValueAtColumn(etrm.getListeChamps().size() + pos);
+ if (paramValue != null) {
+ DlgSearchHelper.this.returnValue = paramValue;
+ }
+ }
+ }
+ if (DlgSearchHelper.this.returnValue != null) {
+ DlgSearchHelper.this.setReturnedValue();
+ } else {
+ logger.error("", new DataConfigurationException(this.getDocumentModel().getId() + "." + this.getElementModel().getParent().getId() + "." + this.getElementModel().getId() + "." + columnId + " is not a hidden !"));
+ }
+ }
+
+ };
+ } catch (final SAXException saxEx) {
+ // ça peut même pas arriver ici
+ } catch (final ParserConfigurationException pcEx) {
+ // encore moins !
+ } catch (final IOException ioEx) {
+ // ça, pourquoi pas !
+ logger.error("<init>", ioEx);
+ } catch (final ToolException tEx) {
+ // ça, c'est probable
+ logger.error("<init>", tEx);
+ }
+ this.setGlassPane(new InfiniteGlassPane());
+ if (shm.getCollectivite() != null) {
+ Pair collectivite = null;
+ final String value = shm.getCollectivite().getValue();
+ if (SearchHelperParameterModel.CURRENT_COLLECTIVITE.equals(value)) {
+ collectivite = sCtx.getCollectivite();
+ } else {
+ collectivite = new Pair(value, value);
+ }
+ this.pnl.setCollectivite(collectivite);
+ }
+ if (shm.getBudget() != null) {
+ Pair budget = null;
+ final String value = shm.getBudget().getValue();
+ if (SearchHelperParameterModel.CURRENT_BUDGET.equals(value)) {
+ budget = sCtx.getBudget();
+ } else {
+ budget = new Pair(value, value);
+ }
+ this.pnl.setBudget(budget);
+ }
+
+ if (sCtx.getCriteres().size() > 0) {
+ this.pnl.clearAll();
+ }
+ for (final RequiredCritereModel rcm : shm.getRequiredCriteres()) {
+ // TODO
+ final CriteriaViewer cv = this.pnl.addLineNoCriteria();
+ final CritereModel cm = this.elementModel.getCritere(rcm.getRefId());
+ cv.changeCritereModel(cm);
+ for (final ValueModel vm : rcm.getValues().values()) {
+ cv.setInputValue(vm.getKey(), vm.getValue());
+ }
+ }
+ for (final CritereModel cm : sCtx.getCriteres()) {
+ String critereToAddId = cm.getId();
+ boolean skipThisCriteria = false;
+ for (final SourceTargetModel stm : shm.getExcludedCriteres()) {
+ if (critereToAddId.equals(stm.getSource())) {
+ skipThisCriteria = true;
+ break;
+ }
+ }
+ final SourceTargetModel cmm = shm.getCritereMappingBySource(critereToAddId);
+ if (cmm != null) {
+ // on vérifie que le critère existe dans cet élément
+ critereToAddId = cmm.getTarget();
+ }
+ for (final SourceTargetModel stm : shm.getExcludedCriteres()) {
+ if (critereToAddId.equals(stm.getTarget())) {
+ skipThisCriteria = true;
+ break;
+ }
+ }
+ if (!skipThisCriteria) {
+ final CritereModel localCm = this.pnl.getElementModel().getCritere(critereToAddId);
+ if (localCm != null) {
+ localCm.setValeurs(cm.getValeurs());
+ final CriteriaViewer cv = this.pnl.addLine();
+ cv.changeCritereModel(localCm);
+ }
+ }
+ }
+ this.getContentPane().add(this.pnl);
+ this.pack();
+ this.setLocationRelativeTo(parent);
+ }
+
+ private void setReturnedValue() {
+ this.inputField.setInputValue(this.returnValue.toString());
+ this.setVisible(false);
+ }
}
*/
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.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.JTextField;
import javax.swing.JToolBar;
import javax.swing.ScrollPaneConstants;
+import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;
import javax.xml.transform.Transformer;
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.Node;
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.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.AbstractURIResolver;
+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;
+
/**
- *
+ *
* @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();
- }
- }
+ private static final Logger logger = Logger.getLogger(PnlSearch.class);
+ // qui suis-je
+ private final 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 final 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 final PropertiesExpansion applicationProperties;
+
+ public PnlSearch(final DocumentModel documentModel, final EtatModel etatModel, final ElementModel elementModel, final DisplayParameters dp, final XemeliosUser user, final PropertiesExpansion applicationProperties) throws ToolException {
+ super();
+ this.documentModel = documentModel;
+ this.etatModel = etatModel;
+ this.elementModel = elementModel;
+ this.dp = dp;
+ this.user = user;
+ this.applicationProperties = applicationProperties;
+ this.initComponents();
+ }
+
+ /**
+ * Permet d'activer ou de désactiver la possibilité de recherche
+ *
+ * @param enableIt
+ */
+ public void setSearchEnabled(final boolean enableIt) {
+ this.pbSearch.setEnabled(enableIt);
+ this.pbSearchBackground.setEnabled(enableIt);
+ }
+
+ /**
+ * Permet de libérer la mémoire avant fermeture. Attention, ne pas appeler n'importe comment !
+ */
+ public void clearResources() {
+ this.elementModel = null;
+ this.etatModel = null;
+ this.documentModel = null;
+ if (this.table != null) {
+ final JXTable latable = (JXTable) this.table;
+ final 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() {
+ this.plugin = null;
+ this.pbValidateHeader.setEnabled(true);
+ if (this.criterias == null) {
+ return;
+ }
+ while (this.criterias.size() > 0) {
+ this.removeLine(this.criterias.elementAt(this.criterias.size() - 1));
+ }
+ }
+
+ public void removeLine(final CriteriaViewer whichOne) {
+ this.scroller.remove(whichOne);
+ this.criterias.remove(whichOne);
+ if (this.criterias.size() == 0) {
+ this.setSearchEnabled(false);
+ }
+ this.repaintCriterias();
+ }
+
+ public void repaintCriterias() {
+ if (!this.isVisible()) {
+ return;
+ }
+ this.scroller.getSize();
+ this.sc.setViewportView(this.scroller);
+ this.resizeParent(this.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() {
+ final CriteriaViewer cv = new CriteriaViewer(this, this.elementModel, this.currentCollectivite, this.currentBudget, true, true);
+ final CriteriaViewer lastCrit = (this.criterias.size() > 0 ? this.criterias.get(this.criterias.size() - 1) : cv);
+ this.criterias.add(cv);
+ if (this.pbClear != null) {
+ this.pbClear.setEnabled(true);
+ this.setSearchEnabled(true);
+ }
+ if (this.scroller != null) {
+ this.scroller.add(cv);
+ }
+ if (this.isVisible()) {
+ cv.setVisible(true);
+ this.scroller.validate();
+ final Rectangle rect = lastCrit.getBounds();
+ final Point p = new Point(0, (int) ((this.criterias.size()) * rect.getHeight()) - 1);
+ this.sc.getViewport().setViewPosition(p);
+ this.repaintCriterias();
+ }
+ return cv;
+ }
+
+ /**
+ * Ajoute un nouveau critère
+ *
+ * @return
+ */
+ public CriteriaViewer addLine() {
+ CriteriaViewer cv = null;
+ if (this.pluginSearchEnabled) {
+ cv = new CriteriaViewer(this, this.elementModel, this.currentCollectivite, this.currentBudget, (this.criterias.size() == 0), this.criteresOp);
+ } else {
+ cv = new CriteriaViewer(this, this.elementModel, this.currentCollectivite, this.currentBudget, (this.criterias.size() == 0));
+ }
+ this.criterias.add(cv);
+ if (this.pbClear != null) {
+ this.pbClear.setEnabled(true);
+ this.setSearchEnabled(true);
+ }
+ if (this.scroller != null) {
+ this.scroller.add(cv);
+ }
+ if (this.isVisible()) {
+ cv.setVisible(true);
+ this.scroller.validate();
+ final Rectangle rect = cv.getBounds();
+ final Point p = new Point(0, (int) ((this.criterias.size()) * rect.getHeight()) - 1);
+ this.sc.getViewport().setViewPosition(p);
+ this.repaintCriterias();
+ }
+ return cv;
+ }
+
+ /**
+ * Construit le panel
+ *
+ * @throws ToolException
+ */
+ protected void initComponents() throws ToolException {
+ this.setLayout(new BorderLayout());
+ final IhmFactory iF = IhmFactory.newInstance();
+
+ this.pbValidateHeader = new JButton(IhmFactory.getIconFromResource(ImageResources.ADD));
+ this.pbValidateHeader.setToolTipText("Ajouter un critère de recherche");
+ this.pbValidateHeader.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ PnlSearch.this.addLine();
+ }
+ });
+ this.pbSearch = new JButton(IhmFactory.getIconFromResource(ImageResources.SEARCH)) {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void fireActionPerformed(final ActionEvent event) {
+ PnlSearch.this.startWaiter();
+ super.fireActionPerformed(event);
+ }
+ };
+ this.pbSearch.setToolTipText("Chercher");
+ this.pbSearch.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ PnlSearch.this.search();
+ }
+ });
+ this.pbSearch.setEnabled(false);
+ this.budgets = new JComboBox();
+
+ int collCount = 0;
+ try {
+ collCount = DataLayerManager.getImplementation().getCollectivitesCount(this.documentModel, this.user);
+ } catch (final Exception ex) {
+ PnlSearch.logger.error("while getting collectivites count:", ex);
+ }
+
+ if (this.documentModel.getCollectivitePath().getParentsCount() == 0 || collCount < Constants.MAX_DISPLAYED_COLLECTIVITES) { // Constants.MAX_DISPLAYED_COLLECTIVITES
+ this.modeCollectivite = MODE_COLLECTIVITES.MODE_LIST;
+ try {
+ final Vector<Pair> collectivites = DataLayerManager.getImplementation().getCollectivites(this.documentModel, null, this.user);
+ this.colls = new JComboBox(collectivites);
+ this.colls.setSelectedIndex(0);
+ this.colls.addActionListener(new ActionListener() {
+
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ final Pair bd = (Pair) PnlSearch.this.colls.getSelectedItem();
+ PnlSearch.this.currentCollectivite = bd;
+ Vector<Pair> data = new Vector<Pair>();
+ try {
+ data = DataLayerManager.getImplementation().getBudgets(PnlSearch.this.documentModel, PnlSearch.this.currentCollectivite, PnlSearch.this.user);
+ } catch (final Exception ex) {
+ final Window ancestor = SwingUtilities.getWindowAncestor(PnlSearch.this);
+ if (ancestor instanceof JDialog) {
+ new DisplayExceptionDlg(ancestor, ex);
+ } else {
+ new DisplayExceptionDlg(ancestor, ex);
+ }
+ }
+ PnlSearch.this.budgets.removeAllItems();
+ for (final Pair c : data) {
+ PnlSearch.this.budgets.addItem(c);
+ }
+ if (data.size() > 0) {
+ PnlSearch.this.budgets.setSelectedIndex(0);
+ }
+ PnlSearch.this.clearAll();
+ PnlSearch.this.pluginSearchEnabled = false;
+ PnlSearch.this.addLine();
+ PnlSearch.this.pbSaveRequest.setEnabled(true);
+ }
+ });
+ this.currentCollectivite = (Pair) this.colls.getItemAt(0);
+ } catch (final Exception ex) {
+ final Window ancestor = SwingUtilities.getWindowAncestor(PnlSearch.this);
+ if (ancestor instanceof JDialog) {
+ new DisplayExceptionDlg(ancestor, ex);
+ } else {
+ new DisplayExceptionDlg(ancestor, ex);
+ }
+ throw new ToolException(ToolException.ERROR_NO_DATA);
+ }
+ this.colls.setEnabled(this.dp.isCollectiviteEditable());
+ } else {
+ this.modeCollectivite = MODE_COLLECTIVITES.MODE_FIELD;
+ // more than Constants.MAX_DISPLAYED_COLLECTIVITES collectivites
+ this.dfCollectivite.setColumns(15);
+ this.dfCollectivite.setEditable(false);
+ this.pbValidateHeader.setEnabled(false);
+ }
+ this.criterias = new Vector<CriteriaViewer>();
+ this.pbSaveRequest = new JButton(IhmFactory.getIconFromResource(ImageResources.SAVE));
+ this.pbSaveRequest.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ PnlSearch.this.saveRequest();
+ }
+ });
+ this.pbSaveRequest.setToolTipText("Enregistrer les critères de recherche");
+ final JButton pbOpenRequest = new JButton(IhmFactory.getIconFromResource(ImageResources.OPEN_REQUEST));
+ pbOpenRequest.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ PnlSearch.this.openRequest();
+ }
+ });
+ pbOpenRequest.setToolTipText("Ouvrir une recherche pré-enregistrée");
+ this.pbSearchBackground = new JButton(IhmFactory.getIconFromResource(ImageResources.SEARCH_BG));
+ this.pbSearchBackground.setToolTipText("Rechercher en tâche de fond");
+ this.pbSearchBackground.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ PnlSearch.this.searchBackground();
+ }
+ });
+ this.pbSearchBackground.setEnabled(false);
+
+ JToolBar tb = new JToolBar();
+ tb.setRollover(true);
+ tb.setFloatable(false);
+ tb.add(iF.newLabel(this.documentModel.getLibelleCollectivite(), "normal"));
+ if (this.modeCollectivite == MODE_COLLECTIVITES.MODE_LIST) {
+ tb.add(this.colls);
+ } else {
+ tb.add(this.dfCollectivite);
+ final JButton pbChooseCollectivite = new JButton("...");
+ pbChooseCollectivite.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ final DlgSelectCollectivite dlg = new DlgSelectCollectivite(PnlSearch.this.documentModel, PnlSearch.this.user, (JFrame) SwingUtilities.getWindowAncestor(PnlSearch.this));
+ if (dlg.run()) {
+ PnlSearch.this.currentCollectivite = dlg.getCollectivite();
+ PnlSearch.this.dfCollectivite.setText(PnlSearch.this.currentCollectivite.libelle);
+ Vector<Pair> data = new Vector<Pair>();
+ try {
+ data = DataLayerManager.getImplementation().getBudgets(PnlSearch.this.documentModel, PnlSearch.this.currentCollectivite, PnlSearch.this.user);
+ } catch (final Exception ex) {
+ final Window ancestor = SwingUtilities.getWindowAncestor(PnlSearch.this);
+ if (ancestor instanceof JDialog) {
+ new DisplayExceptionDlg(ancestor, ex);
+ } else {
+ new DisplayExceptionDlg(ancestor, ex);
+ }
+ }
+ PnlSearch.this.budgets.removeAllItems();
+ for (final Pair c : data) {
+ PnlSearch.this.budgets.addItem(c);
+ }
+ if (data.size() > 0) {
+ PnlSearch.this.budgets.setSelectedIndex(0);
+ }
+ PnlSearch.this.clearAll();
+ PnlSearch.this.pluginSearchEnabled = false;
+ PnlSearch.this.addLine();
+ PnlSearch.this.pbSaveRequest.setEnabled(true);
+ PnlSearch.this.pbValidateHeader.setEnabled(true);
+ }
+ }
+ });
+ tb.add(pbChooseCollectivite);
+ pbChooseCollectivite.setEnabled(this.dp.isCollectiviteEditable());
+ }
+ tb.addSeparator();
+ tb.add(iF.newLabel("Code Budget ", "normal"));
+ tb.add(this.budgets);
+ this.budgets.setEnabled(this.dp.isBudgetEditable());
+ this.add(tb, BorderLayout.PAGE_START);
+
+ tb = new JToolBar(SwingConstants.VERTICAL);
+ tb.setRollover(true);
+ // tb.addSeparator();
+ if (this.dp.isAddCriteriaVisible()) {
+ tb.add(this.pbValidateHeader);
+ }
+ tb.add(this.pbSearch);
+ if (this.dp.isSearchBackgroundVisible()) {
+ tb.add(this.pbSearchBackground);
+ }
+ this.pbClear = new JButton(IhmFactory.getIconFromResource(ImageResources.CLEAR_ALL));
+ if (this.dp.isClearAllVisible()) {
+ tb.add(this.pbClear);
+ }
+ if (this.documentModel.getReferentielXsltFile() != null && this.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(final ActionEvent evt) {
+ PnlSearch.this.showReferentiel();
+ }
+ });
+ }
+ tb.addSeparator();
+ if (this.dp.isSaveRequestVisible()) {
+ tb.add(this.pbSaveRequest);
+ }
+ if (this.dp.isOpenRequestVisible()) {
+ tb.add(pbOpenRequest);
+ }
+ tb.addSeparator();
+
+ final JButton pbEnvironment = new JButton(IhmFactory.getIconFromResource(ImageResources.ENVIRONMENT));
+ pbEnvironment.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ final DlgEditEnvironment dee = new DlgEditEnvironment((Frame) SwingUtilities.getWindowAncestor(PnlSearch.this), PnlSearch.this.elementModel, EnvironmentDomain.DOMAIN_ELEMENT, PnlSearch.this.getUser());
+ dee.setVisible(true);
+ }
+ });
+ pbEnvironment.setToolTipText("Modifier les paramètres d'environnement de recherche.");
+ if (this.dp.isEnvironmentVisible()) {
+ tb.add(pbEnvironment);
+ }
+
+ final JButton pbSortFields = new JButton(IhmFactory.getIconFromResource(ImageResources.SORT_FIELDS));
+ pbSortFields.setToolTipText("Champs et tris");
+ pbSortFields.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ final DlgSearchParams dsp = new DlgSearchParams(MainWindow.getInstance(), true, PnlSearch.this.elementModel.getListeResultat());
+ dsp.setVisible(true);
+ }
+ });
+ tb.addSeparator();
+ if (this.dp.isSortFieldsVisible()) {
+ tb.add(pbSortFields);
+ }
+ this.add(tb, BorderLayout.BEFORE_LINE_BEGINS);
+
+ this.pbClear.setEnabled(false);
+ this.pbClear.setToolTipText("Supprimer tous les critères");
+ this.pbClear.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ PnlSearch.this.clearAll();
+ PnlSearch.this.pluginSearchEnabled = false;
+ PnlSearch.this.addLine();
+ PnlSearch.this.pbSaveRequest.setEnabled(true);
+ }
+ });
+ if (this.dp.isExportVisible()) {
+ this.pbExport = new JButton(IhmFactory.getIconFromResource(ImageResources.ACT_EXPORT));
+ this.pbExport.setToolTipText("Exporter le résultat de recherche");
+ this.pbExport.setEnabled(false);
+ this.pbExport.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ final JPopupMenu popup = new JPopupMenu();
+ final AbstractAction actExportTable = new AbstractAction("Exporter la page courante") {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ PnlSearch.this.exportCSV();
+ }
+ };
+ final JMenuItem mnuExportResult = new JMenuItem(actExportTable);
+ final AbstractAction actAdvancedExport = new AbstractAction("Export avancé") {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ PnlSearch.this.exportXLS();
+ }
+ };
+ final JMenuItem mnuAdvanced = new JMenuItem(actAdvancedExport);
+ popup.add(mnuExportResult);
+ popup.add(mnuAdvanced);
+ final JButton source = (JButton) e.getSource();
+ popup.show(source.getParent(), source.getLocation().x + source.getWidth() + 3, source.getLocation().y);
+ }
+ });
+ tb.add(this.pbExport);
+ }
+
+ // ajout de la zone pour les criteres
+ this.scroller = new JPanel(new VerticalFlowLayout(VerticalFlowLayout.TOP, 0, 0));
+ this.sc = new JScrollPane(this.scroller);
+ this.validateHeader();
+ this.sc.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
+
+ this.splitter = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
+ this.splitter.setLeftComponent(this.sc);
+ this.splitter.setRightComponent(new JPanel());
+ this.add(this.splitter, BorderLayout.CENTER);
+
+ final JPanel bottomPane = new JPanel(new BorderLayout());
+ this.bottomField = new JTextField();
+ this.bottomField.setEditable(false);
+ this.bottomField.setBackground(bottomPane.getBackground());
+ this.bottomField.setBorder(BorderFactory.createEmptyBorder());
+ this.bottomField.setColumns(75);
+ bottomPane.add(this.bottomField, BorderLayout.WEST);
+
+ this.ps = new PageSeeker(this);
+ bottomPane.add(this.ps, BorderLayout.EAST);
+ this.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();
+ // }
+ // });
+
+ this.actSearch = new AbstractAction() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ PnlSearch.this.pbSearch.doClick();
+ }
+ };
+
+ if (this.colls != null) {
+ Vector<Pair> data = new Vector<Pair>();
+ try {
+ data = DataLayerManager.getImplementation().getBudgets(this.documentModel, this.currentCollectivite, this.user);
+ } catch (final Exception ex) {
+ final Window ancestor = SwingUtilities.getWindowAncestor(PnlSearch.this);
+ if (ancestor instanceof JDialog) {
+ new DisplayExceptionDlg(ancestor, ex);
+ } else {
+ new DisplayExceptionDlg(ancestor, ex);
+ }
+ }
+ this.budgets.removeAllItems();
+ for (final Pair c : data) {
+ this.budgets.addItem(c);
+ }
+ if (data.size() > 0) {
+ this.budgets.setSelectedIndex(0);
+ }
+ this.validateHeader();
+ }
+ this.budgets.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ PnlSearch.this.clearAll();
+ PnlSearch.this.validateHeader();
+ }
+ });
+
+ this.splitter.setDividerLocation(100);
+ }
+
+ /**
+ * Réalise l'export CSV du résultat de recherche
+ */
+ public void exportCSV() {
+ if (!this.canExport()) {
+ return;
+ }
+ final EtatResultTableModel ertm = (EtatResultTableModel) this.getTable().getModel();
+ final JFileChooser fc = new JFileChooser();
+ fc.setFileFilter(new FileFilter() {
+ @Override
+ public boolean accept(final File f) {
+ return f.isDirectory() || f.getName().toUpperCase().endsWith(".CSV");
+ }
+
+ @Override
+ public String getDescription() {
+ return "Fichier CSV";
+ }
+ });
+ final 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();
+ final 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;
+ final int[] selectedRows = this.getTable().getSelectedRows();
+ out = ertm.getCsvBuffer(MainWindow.fieldSeparator, eop.getExportAll(), selectedRows);
+ try {
+ final FileWriter fw = new FileWriter(f);
+ fw.write(out);
+ fw.flush();
+ fw.close();
+ } catch (final IOException ioEx) {
+ Component comp = this;
+ while (comp != null && !(comp instanceof JFrame)) {
+ comp = comp.getParent();
+ }
+ new DisplayExceptionDlg((JFrame) comp, ioEx);
+ }
+ }
+ }
+
+ public void exportXLS() {
+ if (!this.canExport()) {
+ return;
+ }
+ final EtatResultTableModel ertm = (EtatResultTableModel) this.getTable().getModel();
+
+ final DocumentsModel dmsTmp = new DocumentsModel(DocumentsModel.QN);
+ final DocumentModel dmTmp = this.getDocumentModel().clone();
+
+ // on ne garde dans dm que l'EtatModel qui a l'ElementModel em
+ final HashMap<String, EtatModel> hTmp = dmTmp.getHEtats();
+ final HashMap<String, EtatModel> hTmp2 = new HashMap<String, EtatModel>();
+ final Vector<EtatModel> vTmp2 = new Vector<EtatModel>();
+ for (final String k : hTmp.keySet()) {
+ final EtatModel emTmp = hTmp.get(k);
+ if (emTmp.getElementById(this.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 (final Throwable t) {
+ }
+
+ final DlgSearchConfig dlgSc = new DlgSearchConfig(MainWindow.getInstance(), dmsTmp, DlgSearchConfig.EXEC_FROM_RECHERCHE, this.user);
+ dlgSc.setErtm(ertm);
+ dlgSc.setEm(this.elementModel);
+ dlgSc.setDm(this.getDocumentModel());
+ dlgSc.setVisible(true);
+ }
+
+ private void validateHeader() {
+ this.currentBudget = (Pair) this.budgets.getSelectedItem();
+ if (this.currentBudget != null && this.currentCollectivite != null) {
+ this.pbSearch.setEnabled(true);
+ this.pbSearchBackground.setEnabled(true);
+ this.addLine();
+ }
+ }
+
+ /**
+ * Réalise la recherche et affiche l'éventuel résultat
+ */
+ public void search() {
+ SearchThread searcher = null;
+ this.setSearchEnabled(false);
+ try {
+ this.setCursor(new Cursor(Cursor.WAIT_CURSOR));
+ searcher = new SearchThread(this, this.elementModel, this.currentCollectivite, this.currentBudget, this.criterias, this.plugin);
+ SwingUtilities.invokeLater(searcher);
+ } catch (final OutOfMemoryError oomErr) {
+ searcher.exceptionDuringProcess = oomErr;
+ } finally {
+ }
+ }
+
+ /**
+ * Affiche la liste des widgets associés à cette recherche
+ *
+ * @param evt
+ */
+ public void displayWidgetList(final MouseEvent evt) {
+ if (!this.dp.isWidgetsVisible()) {
+ return;
+ }
+ final Point p = evt.getPoint();
+ final int row = this.getTable().rowAtPoint(p);
+ final EtatResultTableModel etrm = (EtatResultTableModel) this.getTable().getModel();
+ final JPopupMenu pm = new JPopupMenu();
+ for (final WidgetModel wm : etrm.getListeResultat().getWidgets()) {
+ AbstractWidget aw = null;
+ try {
+ final Class clazz = Class.forName(wm.getClassName());
+ final Constructor cc = clazz.getConstructor(WidgetModel.class, ElementModel.class);
+ aw = (AbstractWidget) cc.newInstance(wm, this.elementModel);
+ } catch (final Exception ex) {
+ new DisplayExceptionDlg(SwingUtilities.getWindowAncestor(this.getTable()), ex);
+ }
+ if (aw != null) {
+ final WidgetAction wa = new WidgetAction(aw, etrm, ((JXTable) this.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;
+ this.setSearchEnabled(false);
+ try {
+ searcher = new SearchThread(this, this.elementModel, this.currentCollectivite, this.currentBudget, this.criterias, this.plugin, true);
+ SwingUtilities.invokeLater(searcher);
+ } catch (final OutOfMemoryError oomErr) {
+ searcher.exceptionDuringProcess = oomErr;
+ } finally {
+ }
+ }
+
+ /**
+ * Renvoie l'utilisateur ayant ouvert ce panneau
+ *
+ * @return
+ */
+ public XemeliosUser getUser() {
+ return this.user;
+ }
+
+ /**
+ * Renvoie l'élément sur lequel on travaille
+ *
+ * @return
+ */
+ public ElementModel getElementModel() {
+ return this.elementModel;
+ }
+
+ /**
+ * Permet de définir la table
+ *
+ * @param table
+ */
+ public void setTable(final JTable table) {
+ this.table = table;
+ }
+
+ /**
+ * Renvoie la table de résultat
+ *
+ * @return
+ */
+ public JTable getTable() {
+ return this.table;
+ }
+
+ /**
+ * Renvoie le splitter
+ *
+ * @return
+ */
+ public JSplitPane getSplitter() {
+ return this.splitter;
+ }
+
+ /**
+ * Renvoie le PageSeeker
+ *
+ * @return
+ */
+ public PageSeeker getPageSeeker() {
+ return this.ps;
+ }
+
+ /**
+ * Renvoie la collectivite courante
+ *
+ * @return
+ */
+ public Pair getCurrentCollectivite() {
+ return this.currentCollectivite;
+ }
+
+ /**
+ * Renovie le budget courant
+ *
+ * @return
+ */
+ public Pair getCurrentBudget() {
+ return this.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(final String text) {
+ this.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(final boolean how) {
+ this.canExport = how;
+ if (this.pbExport != null) {
+ this.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 final PnlSearch sw;
+ private final Object obj;
+ private final ToolException tEx;
+
+ public DisplayErrorSearchThread(final PnlSearch sw, final ToolException tEx, final Object objToFocus) {
+ super();
+ this.sw = sw;
+ this.obj = objToFocus;
+ this.tEx = tEx;
+ }
+
+ @Override
+ public void run() {
+ JOptionPane.showMessageDialog(this.sw, this.tEx.getMessage(), "", JOptionPane.WARNING_MESSAGE);
+ this.sw.setSearchEnabled(true);
+ if (this.obj != null) {
+ ((CriteriaViewer) (this.obj)).doFocusOnError();
+ }
+ }
+ };
+
+ private String getRequestName() {
+ return JOptionPane.showInputDialog(this, "Veuillez saisir un nom pour cette recherche :", "Valeur par défaut");
+ }
+
+ private void saveRequest() {
+ final String requestName = this.getRequestName();
+ if (requestName == null || requestName.length() == 0) {
+ return;
+ }
+ final RechercheModel rm = new RechercheModel(RechercheModel.QN, requestName);
+ for (final CriteriaViewer cv : this.criterias) {
+ try {
+ rm.addChild(cv.getXmlMarshallable(), CritereModel.QN);
+ } catch (final SAXException ignore) {
+ // pour le moment, on la jette bien violement
+ ignore.printStackTrace();
+ }
+ }
+ MainWindow.getInstance().getSavedRequest(this.elementModel).add(rm);
+ try {
+ DataLayerManager.getImplementation().saveRequest(this.getElementModel(), rm, this.getUser());
+ } catch (final Exception ex) {
+ PnlSearch.logger.error(ex);
+ }
+
+ }
+
+ private void openRequest() {
+ String persistence = null;
+ try {
+ persistence = DataLayerManager.getImplementation().getLayerName();
+ } catch (final Throwable t) {
+ }
+ final TreeSet<ListDisplayable> data = new TreeSet<ListDisplayable>();
+ if (this.dp.isSavedRequestsIncluded()) {
+ final SavedRequestsModel srm = MainWindow.getInstance().getSavedRequest(this.elementModel);
+ data.addAll(srm.getRecherches());
+ }
+ final Vector<PluginModel> plugins = this.elementModel.getPlugins();
+ for (final PluginModel pm : plugins) {
+ if (pm.isAvailableFor(persistence)) {
+ if (pm.getPluginType().equals(PluginModel.TYPE_SEARCH) && this.dp.isSearchPluginsIncluded()) {
+ data.add(pm);
+ } else if (pm.getPluginType().equals(PluginModel.TYPE_EXPORT) && this.dp.isExportPluginsIncluded()) {
+ data.add(pm);
+ }
+ }
+ }
+ final Vector<ListDisplayable> vData = new Vector<ListDisplayable>();
+ vData.addAll(data);
+ final DlgSelectRequest dsr = new DlgSelectRequest(MainWindow.getInstance(), vData, this.elementModel);
+ if (dsr.run()) {
+ final ListDisplayable xm = (ListDisplayable) dsr.getSelectedItem();
+ if (xm instanceof RechercheModel) {
+ this.pluginSearchEnabled = false;
+ final RechercheModel rm = (RechercheModel) xm;
+ this.clearAll();
+ for (final CritereModel cm : rm.getCriteres()) {
+ final CriteriaViewer cv = this.addLine();
+ cv.changeCritereModel(cm);
+ }
+ this.pbSaveRequest.setEnabled(true);
+ } else if (xm instanceof PluginModel) {
+ this.pluginSearchEnabled = true;
+ final PluginModel pm = (PluginModel) xm;
+ this.clearAll();
+ this.plugin = pm.clone();
+ this.pbValidateHeader.setEnabled(false);
+ for (final CritereModel cm : pm.getCriteres()) {
+ final CriteriaViewer cv = this.addLineNoCriteria();
+ cv.changeCritereModel(cm.clone());
+ this.criterias.add(cv);
+ }
+ // debug
+ if (pm.getCriteresOp().size() > 0) {
+ this.pbValidateHeader.setEnabled(true);
+ }
+ this.criteresOp = new Vector<CritereModel>();
+ for (final CritereRefModel cmr : pm.getCriteresOp()) {
+ final CritereModel cm = this.elementModel.getCritere(cmr.getIdRef());
+ this.criteresOp.add(cm);
+ }
+ // debug
+ this.pbSaveRequest.setEnabled(false);
+ }
+ }
+ }
+
+ private void showReferentiel() {
+ try {
+ final Vector<Document> vXmlData = DataLayerManager.getImplementation().getRepositorysAsDom(this.documentModel, this.currentCollectivite, this.user);
+ if (vXmlData.size() == 0) {
+ JOptionPane.showMessageDialog(this, "Pas de nomenclature disponible");
+ return;
+ }
+
+ // TODO: vérifier que ça marche...
+ final XPath xp = XPathFactory.newInstance().newXPath();
+ xp.setNamespaceContext(this.documentModel.getNamespaces());
+
+ final Vector<Node> vRepository = new Vector<Node>();
+ Node repository;
+ for (final Document docXml : vXmlData) {
+ repository = (Node) xp.evaluate("//n:" + this.documentModel.getReferentiel(), docXml.getDocumentElement(), XPathConstants.NODE);
+ vRepository.add(repository);
+ }
+ final Document docRoot = FactoryProvider.getDocumentBuilderFactory().newDocumentBuilder().newDocument();
+
+ final 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++) {
+ final 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++) {
+ final Node nomencl = vRepository.get(i);
+ if (nomencl != null) {
+ docRoot.adoptNode(nomencl);
+ docRoot.getDocumentElement().appendChild(nomencl);
+ }
+ }
+ }
+
+ final File xslFile = new File(new File(this.documentModel.getBaseDirectory()), this.documentModel.getReferentielXsltFile());
+ final InputStream is = IoUtils.getInputStream(xslFile.getPath());
+ // InputStream htmlStream = DematTransform.transform(new ByteArrayInputStream(sXmlData.getBytes(encoding)),is,encoding);
+ final TransformerFactory tFactory = FactoryProvider.getTransformerFactory();
+ final AbstractURIResolver uriResolver = this.documentModel.createUriResolver();
+ AbstractURIResolver.initializationHelper(uriResolver, docRoot, tFactory.getURIResolver(), xslFile.toURI().toURL().toExternalForm());
+
+ tFactory.setURIResolver(uriResolver);
+
+ final Transformer t = tFactory.newTransformer(new StreamSource(is));
+ final ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ t.transform(new DOMSource(docRoot.getDocumentElement()), new StreamResult(baos));
+ final ByteArrayInputStream htmlStream = new ByteArrayInputStream(baos.toByteArray());
+ MainWindow.getInstance().displayHtmlStream(htmlStream, this.etatModel, MainWindow.getInstance().getDesk());
+
+ } catch (final 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(final Pair collectivite) {
+ if (this.modeCollectivite == MODE_COLLECTIVITES.MODE_LIST) {
+ this.colls.setSelectedItem(collectivite);
+ } else {
+ this.currentCollectivite = collectivite;
+ this.dfCollectivite.setText(collectivite.libelle);
+ Vector<Pair> data = new Vector<Pair>();
+ try {
+ data = DataLayerManager.getImplementation().getBudgets(this.documentModel, this.currentCollectivite, this.user);
+ } catch (final Exception ex) {
+ final Window ancestor = SwingUtilities.getWindowAncestor(PnlSearch.this);
+ if (ancestor instanceof JDialog) {
+ new DisplayExceptionDlg(ancestor, ex);
+ } else {
+ new DisplayExceptionDlg(ancestor, ex);
+ }
+ }
+ this.budgets.removeAllItems();
+ for (final Pair c : data) {
+ this.budgets.addItem(c);
+ }
+ if (data.size() > 0) {
+ this.budgets.setSelectedIndex(0);
+ }
+ this.clearAll();
+ this.pluginSearchEnabled = false;
+ this.addLine();
+ this.pbSaveRequest.setEnabled(true);
+ this.pbValidateHeader.setEnabled(true);
+ }
+ }
+
+ /**
+ * Permet de sélectionner un budget
+ *
+ * @param budget
+ */
+ public void setBudget(final Pair budget) {
+ this.budgets.setSelectedItem(budget);
+ }
+
+ public SearchContext getSearchContext() {
+ final SearchContext sCtx = new SearchContext(this.currentCollectivite, this.currentBudget);
+ sCtx.setUser(this.getUser());
+ for (final CriteriaViewer cv : this.criterias) {
+ sCtx.addCritere((CritereModel) cv.getXmlMarshallable());
+ }
+ return sCtx;
+ }
+
+ public PropertiesExpansion getApplicationProperties() {
+ return this.applicationProperties;
+ }
+
+ /**
+ * Renvoie l'action pour la recherche
+ *
+ * @return
+ */
+ public AbstractAction getActionSearch() {
+ return this.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 this.addCriteriaVisible;
+ }
+
+ public void setAddCriteriaVisible(final boolean addCriteriaVisible) {
+ this.addCriteriaVisible = addCriteriaVisible;
+ }
+
+ public boolean isClearAllVisible() {
+ return this.clearAllVisible;
+ }
+
+ public void setClearAllVisible(final boolean clearAllVisible) {
+ this.clearAllVisible = clearAllVisible;
+ }
+
+ public boolean isEnvironmentVisible() {
+ return this.environmentVisible;
+ }
+
+ public void setEnvironmentVisible(final boolean environmentVisible) {
+ this.environmentVisible = environmentVisible;
+ }
+
+ public boolean isExportPluginsIncluded() {
+ return this.exportPluginsIncluded;
+ }
+
+ public void setExportPluginsIncluded(final boolean exportPluginsIncluded) {
+ this.exportPluginsIncluded = exportPluginsIncluded;
+ }
+
+ public boolean isOpenRequestVisible() {
+ return this.openRequestVisible;
+ }
+
+ public void setOpenRequestVisible(final boolean openRequestVisible) {
+ this.openRequestVisible = openRequestVisible;
+ }
+
+ public boolean isSaveRequestVisible() {
+ return this.saveRequestVisible;
+ }
+
+ public void setSaveRequestVisible(final boolean saveRequestVisible) {
+ this.saveRequestVisible = saveRequestVisible;
+ }
+
+ public boolean isSavedRequestsIncluded() {
+ return this.savedRequestsIncluded;
+ }
+
+ public void setSavedRequestsIncluded(final boolean savedRequestsIncluded) {
+ this.savedRequestsIncluded = savedRequestsIncluded;
+ }
+
+ public boolean isSearchBackgroundVisible() {
+ return this.searchBackgroundVisible;
+ }
+
+ public void setSearchBackgroundVisible(final boolean searchBackgroundVisible) {
+ this.searchBackgroundVisible = searchBackgroundVisible;
+ }
+
+ public boolean isSearchPluginsIncluded() {
+ return this.searchPluginsIncluded;
+ }
+
+ public void setSearchPluginsIncluded(final boolean searchPluginsIncluded) {
+ this.searchPluginsIncluded = searchPluginsIncluded;
+ }
+
+ public boolean isShowRepositoryVisible() {
+ return this.showRepositoryVisible;
+ }
+
+ public void setShowRepositoryVisible(final boolean showRepositoryVisible) {
+ this.showRepositoryVisible = showRepositoryVisible;
+ }
+
+ public boolean isSortFieldsVisible() {
+ return this.sortFieldsVisible;
+ }
+
+ public void setSortFieldsVisible(final boolean sortFieldsVisible) {
+ this.sortFieldsVisible = sortFieldsVisible;
+ }
+
+ public boolean isWidgetsVisible() {
+ return this.widgetsVisible;
+ }
+
+ public void setWidgetsVisible(final boolean widgetsVisible) {
+ this.widgetsVisible = widgetsVisible;
+ }
+
+ public boolean isBudgetEditable() {
+ return this.budgetEditable;
+ }
+
+ public void setBudgetEditable(final boolean budgetEditable) {
+ this.budgetEditable = budgetEditable;
+ }
+
+ public boolean isCollectiviteEditable() {
+ return this.collectiviteEditable;
+ }
+
+ public void setCollectiviteEditable(final boolean collectiviteEditable) {
+ this.collectiviteEditable = collectiviteEditable;
+ }
+
+ public boolean isSummableVisible() {
+ return this.summableVisible;
+ }
+
+ public void setSummableVisible(final boolean summableVisible) {
+ this.summableVisible = summableVisible;
+ }
+
+ public boolean isExportVisible() {
+ return this.exportVisible;
+ }
+
+ public void setExportVisible(final boolean exportVisible) {
+ this.exportVisible = exportVisible;
+ }
+
+ }
+
+ private class WidgetAction extends AbstractAction {
+ private final AbstractWidget aw;
+ private final EtatResultTableModel etrm;
+ private final int row;
+
+ public WidgetAction(final AbstractWidget aw, final EtatResultTableModel etrm, final int row) {
+ super(aw.getWidgetModel().getLibelle());
+ this.aw = aw;
+ this.etrm = etrm;
+ this.row = row;
+ }
+
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ this.aw.run(this.etrm, this.row);
+ }
+ }
+
+ private class ExportOptionPane extends JPanel {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+ String separator = MainWindow.fieldSeparator;
+ private JTextField fldSep;
+ private JRadioButton rbAll, rbSelection;
+
+ public ExportOptionPane() {
+ super();
+ this.initComponents();
+ }
+
+ private void initComponents() {
+ final FormLayout fl = new FormLayout("1dlu,pref,1dlu", "1dlu,pref,1dlu,pref,4dlu,pref,1dlu,pref,1dlu");
+ final CellConstraints cc = new CellConstraints();
+ final PanelBuilder pb = new PanelBuilder(fl, this);
+ final IhmFactory iF = IhmFactory.newInstance();
+
+ final int col = 2;
+ final int start = 2;
+
+ pb.add(iF.newLabel("Séparateur"), cc.xy(col, 0 + start));
+ pb.add(this.fldSep = new JTextField(this.separator), cc.xy(col, 2 + start));
+ pb.add(this.rbSelection = new JRadioButton("Séléction"), cc.xy(col, 4 + start));
+ pb.add(this.rbAll = new JRadioButton("Tout"), cc.xy(col, 6 + start));
+ final ButtonGroup bg = new ButtonGroup();
+ bg.add(this.rbSelection);
+ bg.add(this.rbAll);
+ this.rbAll.setSelected(true);
+
+ this.setVisible(true);
+ }
+
+ public String getSeparator() {
+ String sep = this.fldSep.getText();
+ if ("\\t".equals(sep)) {
+ sep = "\t";
+ }
+ return sep;
+ }
+
+ public boolean getExportAll() {
+ return this.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();
+ this.initComponents();
+ }
+
+ private void initComponents() {
+ final FormLayout fl = new FormLayout("1dlu,pref,1dlu", "1dlu,pref,1dlu,pref,4dlu,pref,1dlu,pref,1dlu");
+ final CellConstraints cc = new CellConstraints();
+ final PanelBuilder pb = new PanelBuilder(fl, this);
+ final IhmFactory iF = IhmFactory.newInstance();
+
+ final int col = 2;
+ final int start = 2;
+
+ pb.add(this.rbSelection = new JRadioButton("Séléction"), cc.xy(col, 4 + start));
+ pb.add(this.rbAll = new JRadioButton("Tout"), cc.xy(col, 6 + start));
+ final ButtonGroup bg = new ButtonGroup();
+ bg.add(this.rbSelection);
+ bg.add(this.rbAll);
+ this.rbAll.setSelected(true);
+
+ this.setVisible(true);
+ }
+
+ public boolean getExportAll() {
+ return this.rbAll.isSelected();
+ }
+ }
}
import java.util.TreeSet;
import javax.swing.JScrollPane;
+import javax.swing.ScrollPaneConstants;
import javax.swing.table.TableModel;
import org.apache.log4j.Logger;
import org.jdesktop.swingx.JXTable;
+import fr.gouv.finances.cp.xemelios.ui.resulttable.EtatResultTableModel;
+import fr.gouv.finances.cp.xemelios.ui.resulttable.ResultTable;
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;
+import fr.gouv.finances.dgfip.xemelios.data.DataResultSet;
/**
* @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);
- }
- }
-
+ private final DataResultSet rs;
+ private final ListeResultatModel lrm;
+ private final long start;
+ private long startParsing;
+ private final ElementModel em;
+ private final PnlSearch sw;
+
+ public ResultDisplayerThread(final DataResultSet rs, final ListeResultatModel lrm, final long start, final ElementModel em, final 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() {
+ this.startParsing = System.currentTimeMillis();
+ try {
+ final TreeSet<DataHandler> ts = new TreeSet<DataHandler>();
+ int count = 0;
+ final CachedData cache = new CachedData();
+ if (this.rs == null) {
+ this.sw.setBottomText("Aucun enregistrement trouvé");
+ } else {
+ this.rs.setEnvironment(this.lrm, cache);
+ while (this.rs.hasNext()) {
+ final DataHandler dh = this.rs.next();
+ if (dh == null) {
+ continue;
+ }
+ ts.add(dh);
+ count++;
+ }
+ this.rs.clear();
+ if (true) {
+ // on vide l'ancienne table
+ final JXTable oldTable = (JXTable) this.sw.getTable();
+ JXTable table = null;
+ boolean tableIsNew = false;
+ if (oldTable != null) {
+ final EtatResultTableModel oldModel = (EtatResultTableModel) oldTable.getModel();
+ oldModel.dispose();
+ table = oldTable;
+ } else {
+ table = new ResultTable(null, this.sw, this.em, this.sw.getUser(), this.sw.getApplicationProperties());
+ tableIsNew = true;
+ }
+ final TableModel tm = new EtatResultTableModel(this.lrm, ts, this.rs);
+ table.setModel(tm);
+ if (tableIsNew) {
+ this.sw.setTable(table);
+ final int pos = this.sw.getSplitter().getDividerLocation();
+ final JScrollPane scrollTable = new JScrollPane(table);
+ scrollTable.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
+ scrollTable.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
+ this.sw.getSplitter().setRightComponent(scrollTable);
+ this.sw.getSplitter().setDividerLocation(pos);
+ this.sw.getSplitter().paintImmediately(this.sw.getSplitter().getBounds());
+ }
+ }
+ final double duration = (System.currentTimeMillis() - this.start) / 1000d;
+ final double durationSearch = (this.startParsing - this.start) / 1000d;
+ final double durationParsing = (System.currentTimeMillis() - this.startParsing) / 1000d;
+ final NumberFormat nf = new DecimalFormat("0.0##");
+ this.sw.setBottomText(this.rs.getEstimatedSize() + " " + this.em.getParent().getImportableElement().getTitre() + "(s) trouvé(s) en " + nf.format(duration) + " s (" + nf.format(durationSearch) + " s recherche, " + nf.format(durationParsing) + " s affichage)");
+ this.sw.getPageSeeker().updateData(this.rs);
+ }
+ this.sw.setCanExport(ts.size() > 0);
+ this.sw.notifyParentStateChanged();
+ } finally {
+ this.sw.setCursor(Cursor.getDefaultCursor());
+ this.sw.stopWaiter();
+ this.sw.setSearchEnabled(true);
+ }
+ }
+
}
package fr.gouv.finances.cp.xemelios.ui.search;
+import java.util.ArrayList;
+
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;
+ private Pair collectivite;
+ private Pair budget;
+ private XemeliosUser user;
+ // les criteres
+ ArrayList<CritereModel> criteres;
+
+ public SearchContext() {
+ super();
+ }
- public SearchContext() {
- super();
- }
- public SearchContext(Pair collectivite, Pair budget) {
- this();
- this.collectivite=collectivite;
- this.budget = budget;
- }
+ public SearchContext(final Pair collectivite, final Pair budget) {
+ this();
+ this.collectivite = collectivite;
+ this.budget = budget;
+ }
- public Pair getBudget() {
- return budget;
- }
+ public Pair getBudget() {
+ return this.budget;
+ }
- public void setBudget(Pair budget) {
- this.budget = budget;
- }
+ public void setBudget(final Pair budget) {
+ this.budget = budget;
+ }
- public Pair getCollectivite() {
- return collectivite;
- }
+ public Pair getCollectivite() {
+ return this.collectivite;
+ }
- public void setCollectivite(Pair collectivite) {
- this.collectivite = collectivite;
- }
+ public void setCollectivite(final Pair collectivite) {
+ this.collectivite = collectivite;
+ }
- public XemeliosUser getUser() {
- return user;
- }
+ public XemeliosUser getUser() {
+ return this.user;
+ }
- public void setUser(XemeliosUser user) {
- this.user = user;
- }
+ public void setUser(final XemeliosUser user) {
+ this.user = user;
+ }
- public ArrayList<CritereModel> getCriteres() {
- return criteres;
- }
+ public ArrayList<CritereModel> getCriteres() {
+ return this.criteres;
+ }
- public void addCritere(CritereModel cm) {
- if(criteres==null) criteres = new ArrayList<CritereModel>();
- criteres.add(cm);
- }
+ public void addCritere(final CritereModel cm) {
+ if (this.criteres == null) {
+ this.criteres = new ArrayList<CritereModel>();
+ }
+ this.criteres.add(cm);
+ }
}
import java.awt.Cursor;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
+import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Vector;
import org.apache.log4j.Logger;
-import fr.gouv.finances.dgfip.utils.Pair;
import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
+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.dgfip.utils.Pair;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
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.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;
+//import fr.gouv.finances.cp.xemelios.ui.MainWindow;
/**
* 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;
+ private static Logger logger = Logger.getLogger(SearchThread.class);
+ public Throwable exceptionDuringProcess = null;
+ public Object obj = null;
+ private boolean background;
+ private final 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(final PnlSearch parent, final ElementModel elementModel, final Pair collectivite, final Pair budget, final Vector<CriteriaViewer> criterias, final PluginModel plugin) {
+ super("Searcher");
+ this.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;
- }
+ public SearchThread(final PnlSearch parent, final ElementModel elementModel, final Pair collectivite, final Pair budget, final Vector<CriteriaViewer> criterias, final PluginModel plugin, final boolean runInBackground) {
+ this(parent, elementModel, collectivite, budget, criterias, plugin);
+ this.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);
- }
- }
+ @Override
+ public void run() {
+ final long start = System.currentTimeMillis();
+ this.setPriority(MIN_PRIORITY);
+ if (this.plugin == null) {
+ this.simpleSearch(start);
+ } else {
+ if (PluginModel.TYPE_SEARCH.equals(this.plugin.getPluginType())) {
+ this.pluginSearch(start);
+ } else if (PluginModel.TYPE_EXPORT.equals(this.plugin.getPluginType())) {
+ this.pluginExport(start);
+ }
+ }
+ if (this.exceptionDuringProcess != null) {
+ if (!(this.exceptionDuringProcess instanceof ToolException)) {
+ new DisplayExceptionDlg(SwingUtilities.getWindowAncestor(this.parentCaller), this.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 CriteriaViewer getDoublon(final Vector<CriteriaViewer> vcv) {
+ final Vector<String> ids = new Vector<String>();
+ for (final 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);
+ protected void pluginSearch(final long start) {
+ final Hashtable<String, String> parameters = new Hashtable<String, String>();
+ boolean shouldContinue = true;
+ for (final CriteriaViewer cv : this.criterias) {
+ try {
+ parameters.putAll(cv.getParameters());
+ } catch (final ToolException tEx) {
+ // un champ a mal ete saisi
+ shouldContinue = false;
+ this.exceptionDuringProcess = tEx;
+ this.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 = this.getDoublon(this.criterias)) != null) {
+ this.obj = doublon;// .focusOnDelete();
+ doublon.focusOnDelete();
+ this.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 {
+ final Class clazz = Class.forName(this.plugin.getPluginClass());
+ final Constructor cc = clazz.getConstructor(XemeliosUser.class);
+ final SearchPlugin xp = (SearchPlugin) cc.newInstance(this.parentCaller.getUser());
+ xp.setPluginModel(this.plugin);
+ xp.setCollectivite(this.collectivite);
+ xp.setBudget(this.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);
- }
- }
- }
+ final SearchPluginRunner runner = new SearchPluginRunner(this.parentCaller.getUser());
+ runner.setPlugin(xp);
+ runner.setParameters(parameters);
+ runner.setSearchWindow(this.parentCaller);
+ runner.setElementModel(this.elementModel);
+ runner.setListeResultat(this.getListeResultat());
+ runner.setStart(start);
+ runner.startSearch();
+ } catch (final ClassNotFoundException cnfEx) {
+ this.exceptionDuringProcess = cnfEx;
+ } catch (final InstantiationException iEx) {
+ this.exceptionDuringProcess = iEx;
+ } catch (final IllegalAccessException iaEx) {
+ this.exceptionDuringProcess = iaEx;
+ } catch (final Exception ex) {
+ this.exceptionDuringProcess = ex;
+ }
+ } else {
+ // erreur de saisie des criteres
+ this.parentCaller.stopWaiter();
+ this.parentCaller.setCursor(Cursor.getDefaultCursor());
+ final Runnable code = new PnlSearch.DisplayErrorSearchThread(this.parentCaller, (ToolException) this.exceptionDuringProcess, this.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);
+ protected void pluginExport(final long start) {
+ // throw new RuntimeException("not yet implemented");
+ logger.debug("entering pluginxport");
+ final Hashtable<String, String> parameters = new Hashtable<String, String>();
+ boolean shouldContinue = true;
+ for (final CriteriaViewer cv : this.criterias) {
+ try {
+ parameters.putAll(cv.getParameters());
+ } catch (final ToolException tEx) {
+ // un champ a mal ete saisi
+ shouldContinue = false;
+ this.exceptionDuringProcess = tEx;
+ this.obj = cv;
+ }
+ }
+ if (shouldContinue) {
+ try {
+ final Class clazz = Class.forName(this.plugin.getPluginClass());
+ final Constructor cc = clazz.getConstructor(XemeliosUser.class);
+ final ExportPlugin xp = (ExportPlugin) cc.newInstance(this.parentCaller.getUser());
+ xp.setPluginModel(this.plugin);
+ xp.setCollectivite(this.collectivite);
+ xp.setBudget(this.budget);
+ xp.setElementModel(this.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);
- }
- }
- }
+ final ExportPluginRunner runner = new ExportPluginRunner(this.parentCaller.getUser());
+ runner.setPlugin(xp);
+ runner.setStart(start);
+ runner.setSearchWindow(this.parentCaller);
+ runner.startExport();
+ } catch (final ClassNotFoundException cnfEx) {
+ this.exceptionDuringProcess = cnfEx;
+ } catch (final InstantiationException iEx) {
+ this.exceptionDuringProcess = iEx;
+ } catch (final IllegalAccessException iaEx) {
+ this.exceptionDuringProcess = iaEx;
+ } catch (final Exception ex) {
+ this.exceptionDuringProcess = ex;
+ }
+ } else {
+ // erreur de saisie des criteres
+ this.parentCaller.stopWaiter();
+ this.parentCaller.setCursor(Cursor.getDefaultCursor());
+ final Runnable code = new PnlSearch.DisplayErrorSearchThread(this.parentCaller, (ToolException) this.exceptionDuringProcess, this.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());
+ protected void simpleSearch(final long start) {
+ final StringBuffer buff = new StringBuffer();
+ buff.append(this.elementModel.getPath().getPath());
+ boolean shouldContinue = true;
+ final HashMap<String, ChampModel> additionnalFields = new HashMap<String, ChampModel>();
+ final Vector<CritereModel> models = new Vector<CritereModel>();
+ for (final CriteriaViewer cv : this.criterias) {
+ final CritereModel cm = cv.getModel();
+ models.add(cm);
+ try {
+ if (cv.getAndOrEr().equals(CriteriaViewer.OR_ASSOCIATOR)) {
+ buff.append("|").append(this.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() {
+ if (cv.isOptionalDisplayChecked()) {
+ // to add the optional columns to display
+ final String idAffichage = cm.getIdAffichage();
+ if (idAffichage != null && idAffichage.length() > 0) {
+ // Look for the "champ" matching this ID in the result list...
+ final ChampModel champOptionnel = this.elementModel.getListeResultat().getChamps().get(idAffichage).clone();
+ // ... and add it to the optional field list
+ if (champOptionnel != null) {
+ additionnalFields.put(champOptionnel.getId(), champOptionnel);
+ }
+ }
+ }
+ } catch (final ToolException tEx) {
+ shouldContinue = false;
+ this.parentCaller.stopWaiter();
+ this.setPriority(NORM_PRIORITY);
+ if (tEx.getErrorCode() != ToolException.ERROR_MISFILLED_CRITERIA) {
+ logger.error(tEx.getMessage(), tEx);
+ } else {
+ this.parentCaller.setCursor(Cursor.getDefaultCursor());
+ this.exceptionDuringProcess = tEx;
+ this.obj = cv;
+ }
+ final Runnable code = new PnlSearch.DisplayErrorSearchThread(this.parentCaller, tEx, this.obj);
+ if (SwingUtilities.isEventDispatchThread()) {
+ code.run();
+ } else {
+ SwingUtilities.invokeLater(code);
+ }
+ this.exceptionDuringProcess = null;
+ break;
+ } catch (final Exception ex) {
+ shouldContinue = false;
+ this.exceptionDuringProcess = ex;
+ this.parentCaller.stopWaiter();
+ }
+ }
+ if (!shouldContinue) {
+ this.parentCaller.stopWaiter();
+ this.parentCaller.setCursor(Cursor.getDefaultCursor());
+ return;
+ }
+ if (this.background) {
+ final Runnable code = new Runnable() {
- @Override
- 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);
+ @Override
+ public void run() {
+ logger.debug("iconify");
+ SearchThread.this.parentCaller.setTitle("Recherche en cours...");
+ SearchThread.this.parentCaller.iconify(true);
+ }
+ };
+ if (SwingUtilities.isEventDispatchThread()) {
+ code.run();
+ } else {
+ try {
+ SwingUtilities.invokeAndWait(code);
+ } catch (final Throwable t) {
+ }
+ }
+ Thread.yield();
+ this.setPriority(Thread.MIN_PRIORITY);
+ }
+ final ListeResultatModel lrm = new ListeResultatModel(ListeResultatModel.QN);
+ lrm.setParent(this.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() {
+ for (final ChampModel cm : additionnalFields.values()) {
+ try {
+ lrm.addChild(cm, ChampModel.QN);
+ } catch (final Throwable t) {
+ } // c'est nous qu'on maitrise, on fait pas de
+ // conneries
+ }
+ final ListeResultatModel lrm2 = this.elementModel.getListeResultat().clone();
+ for (final ChampModel cm : lrm2.getListeChamps()) {
+ try {
+ if (cm.isAfficheDefaut() && cm.isAffichable()) {
+ lrm.addChild(cm, ChampModel.QN);
+ }
+ } catch (final Throwable t) {
+ } // c'est nous qu'on maitrise toujours
+ }
+ lrm.setTriDefaut(lrm2.getTriDefaut());
+ lrm.setOrdre(lrm2.getOrdre());
+ for (final HiddenModel hm : lrm2.getHiddens()) {
+ try {
+ lrm.addChild(hm, HiddenModel.QN);
+ } catch (final Throwable t) {
+ } // qu'on matrise toujours, ouyouyouille !
+ }
+ for (final WidgetModel wm : lrm2.getWidgets()) {
+ try {
+ lrm.addChild(wm, WidgetModel.QN);
+ } catch (final Throwable t) {
+ }
+ }
+ try {
+ final XPathExecuter xe = new XPathExecuter(this.elementModel, buff.toString(), models, this.collectivite, this.budget, lrm, start, this.parentCaller);
+ if (this.background) {
+ xe.addPropertyChangeListener(new PropertyChangeListener() {
- @Override
- public void propertyChange(PropertyChangeEvent evt) {
- if ("COMPLETED".equals(evt.getPropertyName()) && Boolean.TRUE.equals(evt.getNewValue())) {
- Runnable code = new Runnable() {
+ @Override
+ public void propertyChange(final PropertyChangeEvent evt) {
+ if ("COMPLETED".equals(evt.getPropertyName()) && Boolean.TRUE.equals(evt.getNewValue())) {
+ final Runnable code = new Runnable() {
- @Override
- 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;
- }
- }
- }
+ @Override
+ public void run() {
+ logger.debug("uniconify");
+ SearchThread.this.parentCaller.redisplayTitle();
+ SearchThread.this.parentCaller.iconify(false);
+ }
+ };
+ if (SwingUtilities.isEventDispatchThread()) {
+ code.run();
+ } else {
+ SwingUtilities.invokeLater(code);
+ }
+ }
+ }
+ });
+ }
+ xe.execute();
+ try {
+ xe.get();
+ } catch (final Throwable t) { /* only to wait for completion */
+ }
+ } catch (final Throwable th) {
+ th.printStackTrace();
+ if (th instanceof OutOfMemoryError) {
+ this.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) {
+ this.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 {
+ this.exceptionDuringProcess = th;
+ }
+ }
+ }
- protected ListeResultatModel getListeResultat() {
- HashMap<String, ChampModel> additionnalFields = new HashMap<String, ChampModel>();
- for (CriteriaViewer cv : criterias) {
- CritereModel cm = cv.getModel();
- try {
+ protected ListeResultatModel getListeResultat() {
+ final HashMap<String, ChampModel> additionnalFields = new HashMap<String, ChampModel>();
+ for (final CriteriaViewer cv : this.criterias) {
+ final 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);
+ if (cv.isOptionalDisplayChecked()) {
+ // to add the optional columns to display
+ final String idAffichage = cm.getIdAffichage();
+ if (idAffichage != null && idAffichage.length() > 0) {
+ // Look for the "champ" matching this ID in the result list...
+ final ChampModel champOptionnel = this.elementModel.getListeResultat().getChamps().get(idAffichage).clone();
+ // ... and add it to the optional field list
+ if (champOptionnel != null) {
+ additionnalFields.put(champOptionnel.getId(), champOptionnel);
+ }
+ }
+ }
+ } catch (final Exception ex) {
+ }
+ }
+ final ListeResultatModel lrm = new ListeResultatModel(ListeResultatModel.QN);
+ lrm.setParent(this.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;
- }
+ for (final ChampModel cm : additionnalFields.values()) {
+ try {
+ lrm.addChild(cm, ChampModel.QN);
+ } catch (final Throwable t) {
+ }
+ }
+ final ListeResultatModel lrm2 = this.elementModel.getListeResultat().clone();
+ for (final ChampModel cm : lrm2.getListeChamps()) {
+ try {
+ if (cm.isAfficheDefaut() && cm.isAffichable()) {
+ lrm.addChild(cm, ChampModel.QN);
+ }
+ } catch (final Throwable t) {
+ }
+ }
+ lrm.setTriDefaut(lrm2.getTriDefaut());
+ lrm.setOrdre(lrm2.getOrdre());
+ for (final HiddenModel hm : lrm2.getHiddens()) {
+ try {
+ lrm.addChild(hm, HiddenModel.QN);
+ } catch (final Throwable t) {
+ }
+ }
+ for (final WidgetModel wm : lrm2.getWidgets()) {
+ try {
+ lrm.addChild(wm, WidgetModel.QN);
+ } catch (final 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) {
- }
- }
- }
+ /**
+ * display the result
+ *
+ * @param rs
+ * @param lrm
+ * @param start
+ * @deprecated. Instead, call this method in the done() method of a SwingWorker
+ */
+ protected void displayResult(final DataResultSet rs, final ListeResultatModel lrm, final long start) {
+ final Runnable code = new ResultDisplayerThread(rs, lrm, start, this.elementModel, this.parentCaller);
+ if (SwingUtilities.isEventDispatchThread()) {
+ code.run();
+ } else {
+ try {
+ SwingUtilities.invokeAndWait(code);
+ } catch (final Throwable t) {
+ }
+ }
+ }
}
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.utils.Pair;
+import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
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;
+//import fr.gouv.finances.cp.xemelios.ui.MainWindow;
/**
* @author chm
*
- * TODO To change the template for this generated type comment go to Window -
- * Preferences - Java - Code Style - Code Templates
+ * 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 static Logger logger = Logger.getLogger(XPathExecuter.class);
+ private final ListeResultatModel lrm;
+
+ private final long start;
+ private final String xPathQuery;
+
+ private final ElementModel elementModel;
+ private final Pair collectivite, budget;
+ private Vector<CritereModel> models = null;
+
+ private final PnlSearch sw;
- private long start;
- private String xPathQuery;
+ private final XemeliosUser user;
- private ElementModel elementModel;
- private Pair collectivite,budget;
- private Vector<CritereModel> models = null;
+ private Throwable errorWhileSearching;
- private PnlSearch sw;
-
- private XemeliosUser user;
+ public XPathExecuter(final ElementModel elementModel, final String xPathQuery, final Vector<CritereModel> models, final Pair collectivite, final Pair budget, final ListeResultatModel lrm, final long start, final 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();
+ }
- private Throwable errorWhileSearching;
+ @Override
+ public DataResultSet doInBackground() {
+ try {
+ logger.debug("XQuery=" + this.xPathQuery);
+ final DataResultSet rs = DataLayerManager.getImplementation().search(this.elementModel, this.collectivite, this.budget, this.xPathQuery, this.lrm, this.models, this.user);
+ return rs;
+ } catch (final Throwable t) {
+ logger.error("une erreur est survenue.", t);
+ try {
+ this.errorWhileSearching = t;
+ // on error, try to return an empty ResultSetClient
+ return DataLayerManager.getImplementation().getEmptyDataResultSet();
+ } catch (final Throwable t2) {
+ }
+ }
+ return null;
+ }
- 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();
- }
- }
+ @Override
+ public void done() {
+ try {
+ if (this.errorWhileSearching != null) {
+ final Runnable code = new Runnable() {
+ @Override
+ public void run() {
+ DisplayExceptionDlg.displayException(SwingUtilities.getWindowAncestor(XPathExecuter.this.sw), XPathExecuter.this.errorWhileSearching);
+ }
+ };
+ if (SwingUtilities.isEventDispatchThread()) {
+ code.run();
+ } else {
+ SwingUtilities.invokeLater(code);
+ }
+ } else {
+ final DataResultSet rs = this.get();
+ final Runnable code = new ResultDisplayerThread(rs, this.lrm, this.start, this.elementModel, this.sw);
+ if (SwingUtilities.isEventDispatchThread()) {
+ code.run();
+ } else {
+ try {
+ SwingUtilities.invokeAndWait(code);
+ } catch (final Throwable t) {
+ }
+ }
+ }
+ this.firePropertyChange("COMPLETED", Boolean.FALSE, Boolean.TRUE);
+ } catch (final Throwable t) {
+ DisplayExceptionDlg.displayException(SwingUtilities.getWindowAncestor(this.sw), t);
+ } finally {
+ this.sw.stopWaiter();
+ }
+ }
}
package fr.gouv.finances.cp.xemelios.ui.searchParams;
/**
- *
+ *
* @author chm
*/
public interface CommonDataUpdater {
- /**
- * Force data to be updated
- */
- public void doUpdate();
+ /**
+ * Force data to be updated
+ */
+ public void doUpdate();
}
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.JRootPane;
import javax.swing.KeyStroke;
+import fr.gouv.finances.dgfip.xemelios.common.config.ListeResultatModel;
+
/**
- *
- * @author chm
+ *
+ * @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;
- }
+ private List<CommonDataUpdater> panels;
+ private final ListeResultatModel originalReference;
+ private final ListeResultatModel currentlyModified;
+ private AbstractAction escapeAction;
+
+ /** Creates new form DlgSearchParams */
+ public DlgSearchParams(final java.awt.Frame parent, final boolean modal, final ListeResultatModel lrm) {
+ super(parent, modal);
+ this.originalReference = lrm;
+ this.currentlyModified = this.originalReference.clone();
+ this.initComponents();
+ this.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() {
+
+ this.tabs = new javax.swing.JTabbedPane();
+ this.pbOk = new javax.swing.JButton();
+ this.pbCancel = new javax.swing.JButton();
+
+ this.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+ this.setTitle("Tris et champs affichés");
+
+ this.pbOk.setText("Ok");
+ this.pbOk.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgSearchParams.this.pbOkActionPerformed(evt);
+ }
+ });
+
+ this.pbCancel.setText("Annuler");
+ this.pbCancel.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgSearchParams.this.pbCancelActionPerformed(evt);
+ }
+ });
+
+ final org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this.getContentPane());
+ this.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(this.tabs, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 544, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup().add(this.pbCancel).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.pbOk))).addContainerGap()));
+ layout.setVerticalGroup(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(
+ layout.createSequentialGroup().addContainerGap().add(this.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(this.pbOk).add(this.pbCancel)).addContainerGap()));
+
+ this.pack();
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void pbOkActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbOkActionPerformed
+ for (final CommonDataUpdater cdu : this.panels) {
+ cdu.doUpdate();
+ }
+
+ // on verifie que les champs triés sont dans les champs affiches
+ final String[] tri = this.currentlyModified.getTriDefaut().split(",");
+ for (final String s : tri) {
+ if (!this.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
+ this.originalReference.setOrdre(this.currentlyModified.getOrdre());
+ this.originalReference.setTriDefaut(this.currentlyModified.getTriDefaut());
+ this.originalReference.changeAllDisplayableChamps(this.currentlyModified.getListeChamps());
+ this.setVisible(false);
+ }// GEN-LAST:event_pbOkActionPerformed
+
+ private void pbCancelActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbCancelActionPerformed
+ this.setVisible(false);
+ }// GEN-LAST:event_pbCancelActionPerformed
+
+ protected void postInitComponents() {
+ this.panels = new ArrayList<CommonDataUpdater>();
+ final JPanel jp2 = new PnlFields(this.currentlyModified);
+ this.tabs.add("Champs", jp2);
+ this.panels.add((CommonDataUpdater) jp2);
+ final JPanel jp = new PnlSortBy(this.currentlyModified);
+ this.tabs.add("Tri", jp);
+ this.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() {
+ final KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
+ final JRootPane rp = new JRootPane();
+ this.escapeAction = new AbstractAction("Annuler") {
+ /**
+ * Comment for <code>serialVersionUID</code>
+ */
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ DlgSearchParams.this.setVisible(false);
+ }
+ };
+ rp.registerKeyboardAction(this.escapeAction, "TOTOTOTO", ks, JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
+ }
}
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;
+import fr.gouv.finances.dgfip.xemelios.common.config.ChampModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ListeResultatModel;
+
/**
- *
- * @author chm
+ *
+ * @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; }
- }
-
+ private final ListeResultatModel lrm;
+ private DisplayableFieldsTableModel tblModel;
+
+ /** Creates new form PnlFields */
+ public PnlFields(final ListeResultatModel lrm) {
+ super();
+ this.lrm = lrm;
+ this.initComponents();
+ this.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() {
+
+ this.jScrollPane1 = new javax.swing.JScrollPane();
+ this.tblFields = new javax.swing.JTable();
+ this.pbUp = new javax.swing.JButton();
+ this.pbDown = new javax.swing.JButton();
+
+ this.tblFields.setModel(this.tblModel = new PnlFields.DisplayableFieldsTableModel(this.lrm));
+ this.jScrollPane1.setViewportView(this.tblFields);
+
+ this.pbUp.setText("^");
+ this.pbUp.setToolTipText("Monter");
+ this.pbUp.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PnlFields.this.pbUpActionPerformed(evt);
+ }
+ });
+
+ this.pbDown.setText("V");
+ this.pbDown.setToolTipText("Descendre");
+ this.pbDown.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PnlFields.this.pbDownActionPerformed(evt);
+ }
+ });
+
+ final 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(this.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(this.pbUp).add(this.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(this.jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 275, Short.MAX_VALUE)
+ .add(layout.createSequentialGroup().add(this.pbUp).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.pbDown))).addContainerGap()));
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void pbUpActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbUpActionPerformed
+ final int i = this.tblFields.getSelectedRow();
+ if (i > 0) {
+ final ChampModel cm = this.tblModel.getData().remove(i);
+ this.tblModel.getData().insertElementAt(cm, i - 1);
+ this.tblModel.fireTableDataChanged();
+ this.tblFields.setRowSelectionInterval(i - 1, i - 1);
+ }
+ }// GEN-LAST:event_pbUpActionPerformed
+
+ private void pbDownActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbDownActionPerformed
+ final int i = this.tblFields.getSelectedRow();
+ if (i < this.tblModel.getData().size() - 1) {
+ final ChampModel cm = this.tblModel.getData().remove(i);
+ this.tblModel.getData().insertElementAt(cm, i + 1);
+ this.tblModel.fireTableDataChanged();
+ this.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
+
+ @Override
+ public void doUpdate() {
+ for (int i = this.lrm.getListeChamps().size() - 1; i >= 0; i--) {
+ final ChampModel cm = this.lrm.getListeChamps().elementAt(i);
+ if (cm.isAffichable()) {
+ this.lrm.getChamps().remove(cm);
+ this.lrm.getListeChamps().remove(cm);
+ }
+ }
+ for (final ChampModel cm : this.tblModel.getData()) {
+ try {
+ this.lrm.addChild(cm, ChampModel.QN);
+ } catch (final Throwable t) {
+ }
+ }
+ }
+
+ public static class DisplayableFieldsTableModel extends AbstractTableModel {
+ Vector<ChampModel> data;
+
+ public DisplayableFieldsTableModel(final ListeResultatModel lrm) {
+ this.data = new Vector<ChampModel>();
+ for (final ChampModel cm : lrm.getListeChamps()) {
+ if (cm.isAffichable()) {
+ this.data.add(cm); // cm.clone() ?
+ }
+ }
+ }
+
+ @Override
+ public int getRowCount() {
+ return this.data.size();
+ }
+
+ @Override
+ public int getColumnCount() {
+ return 2;
+ }
+
+ @Override
+ public Object getValueAt(final int rowIndex, final int columnIndex) {
+ final ChampModel cm = this.data.elementAt(rowIndex);
+ if (columnIndex == 0) {
+ return cm.isAfficheDefaut();
+ } else {
+ return cm.getLibelle();
+ }
+ }
+
+ @Override
+ public Class<?> getColumnClass(final int columnIndex) {
+ if (columnIndex == 0) {
+ return Boolean.class;
+ } else {
+ return String.class;
+ }
+ }
+
+ @Override
+ public String getColumnName(final int column) {
+ if (column == 0) {
+ return "Afficher";
+ } else {
+ return "Champ";
+ }
+ }
+
+ @Override
+ public boolean isCellEditable(final int rowIndex, final int columnIndex) {
+ return columnIndex == 0;
+ }
+
+ @Override
+ public void setValueAt(final Object aValue, final int rowIndex, final int columnIndex) {
+ final ChampModel cm = this.data.elementAt(rowIndex);
+ if (columnIndex == 0) {
+ cm.setAfficheDefaut(((Boolean) aValue).booleanValue());
+ }
+ }
+
+ public Vector<ChampModel> getData() {
+ return this.data;
+ }
+ }
+
}
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.JComboBox;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
+import javax.swing.table.AbstractTableModel;
+import javax.swing.table.TableCellEditor;
+
+import fr.gouv.finances.dgfip.xemelios.common.config.ChampModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.ListeResultatModel;
/**
- *
- * @author chm
+ *
+ * @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() {
- @Override
- 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
-
- @Override
- 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;
- }
-
- @Override
- public int getColumnCount() {
- return 2;
- }
-
- @Override
- public boolean isCellEditable(int row, int column) {
- return column==1;
- }
-
- @Override
- 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;
- }
-
- @Override
- 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();
- }
-
- }
+ private final 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(final ListeResultatModel lrm) {
+ this.lrm = lrm;
+ this.initComponents();
+ this.initData();
+ this.initListeners();
+ }
+
+ protected void initListeners() {
+ this.pbUp.setEnabled(false);
+ this.pbDown.setEnabled(false);
+ // pbRemoveAll.setEnabled(false);
+ this.pbRemoveOne.setEnabled(false);
+ // pbAddAll.setEnabled(false);
+ this.pbAddOne.setEnabled(false);
+ this.lstChamps.addListSelectionListener(new ListSelectionListener() {
+ @Override
+ public void valueChanged(final ListSelectionEvent e) {
+ if (PnlSortBy.this.lstChamps.getSelectedIndices().length == 0) {
+ // pbAddAll.setEnabled(false);
+ PnlSortBy.this.pbAddOne.setEnabled(false);
+ } else {
+ PnlSortBy.this.pbAddAll.setEnabled(true);
+ PnlSortBy.this.pbAddOne.setEnabled(true);
+ }
+ }
+ });
+ }
+
+ public void initData() {
+ this.cbxSortBy = new JComboBox(new String[] { "ASC", "DESC" });
+ this.sortableChamps = new Vector<ChampModel>();
+ final List<ChampModel> champs = this.lrm.getListeChamps();
+ for (final ChampModel cm : champs) {
+ if (cm.isTriable()) {
+ this.sortableChamps.add(cm);
+ }
+ }
+ this.champsTriables = new Vector<ChampTriable>();
+ final String triDefaut = this.lrm.getTriDefaut();
+ final String ordreDefaut = this.lrm.getOrdre();
+ final String champsTri[] = triDefaut.split(",");
+ final StringTokenizer to = new StringTokenizer(ordreDefaut, ",");
+ for (final String ch : champsTri) {
+ String or = to.nextToken();
+ if (or == null) {
+ or = "ASC";
+ }
+ this.champsTriables.add(new ChampTriable(ch, this.lrm.getChamps().get(ch).getLibelle(), or));
+ this.sortableChamps.remove(this.lrm.getChamps().get(ch));
+ }
+ this.tm = new TriableTableModel(this.champsTriables);
+ this.tblChampTries.setModel(this.tm);
+ this.lstChamps.setListData(this.sortableChamps);
+ }
+
+ public void tableListSelectionChanged(final ListSelectionEvent e) {
+ if (this.tblChampTries.getSelectedRows().length == 0) {
+ this.pbUp.setEnabled(false);
+ this.pbDown.setEnabled(false);
+ // pbRemoveAll.setEnabled(false);
+ this.pbRemoveOne.setEnabled(false);
+ } else {
+ this.pbUp.setEnabled(true);
+ this.pbDown.setEnabled(true);
+ this.pbRemoveAll.setEnabled(true);
+ this.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() {
+
+ this.jScrollPane1 = new javax.swing.JScrollPane();
+ this.lstChamps = new javax.swing.JList();
+ this.jScrollPane2 = new javax.swing.JScrollPane();
+ this.tblChampTries = new org.jdesktop.swingx.JXTable() {
+ @Override
+ public void valueChanged(final ListSelectionEvent e) {
+ super.valueChanged(e);
+ PnlSortBy.this.tableListSelectionChanged(e);
+ }
+
+ @Override
+ public TableCellEditor getCellEditor(final int row, final int column) {
+ if (column == 0) {
+ return super.getCellEditor(row, column);
+ } else {
+ final DefaultCellEditor dce = new DefaultCellEditor(PnlSortBy.this.cbxSortBy);
+ PnlSortBy.this.cbxSortBy.setSelectedItem(this.getValueAt(row, column));
+ return dce;
+ }
+ }
+ };
+ this.pbAddAll = new javax.swing.JButton();
+ this.pbAddOne = new javax.swing.JButton();
+ this.pbRemoveOne = new javax.swing.JButton();
+ this.pbRemoveAll = new javax.swing.JButton();
+ this.pbUp = new javax.swing.JButton();
+ this.pbDown = new javax.swing.JButton();
+
+ this.lstChamps.setModel(new javax.swing.AbstractListModel() {
+ String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
+
+ @Override
+ public int getSize() {
+ return this.strings.length;
+ }
+
+ @Override
+ public Object getElementAt(final int i) {
+ return this.strings[i];
+ }
+ });
+ this.jScrollPane1.setViewportView(this.lstChamps);
+
+ this.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" }));
+ this.jScrollPane2.setViewportView(this.tblChampTries);
+
+ this.pbAddAll.setText(">>");
+ this.pbAddAll.setToolTipText("Tout ajouter");
+ this.pbAddAll.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PnlSortBy.this.pbAddAllActionPerformed(evt);
+ }
+ });
+
+ this.pbAddOne.setText(">");
+ this.pbAddOne.setToolTipText("Ajouter");
+ this.pbAddOne.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PnlSortBy.this.pbAddOneActionPerformed(evt);
+ }
+ });
+
+ this.pbRemoveOne.setText("<");
+ this.pbRemoveOne.setToolTipText("Retirer");
+ this.pbRemoveOne.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PnlSortBy.this.pbRemoveOneActionPerformed(evt);
+ }
+ });
+
+ this.pbRemoveAll.setText("<<");
+ this.pbRemoveAll.setToolTipText("Tout retirer");
+ this.pbRemoveAll.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PnlSortBy.this.pbRemoveAllActionPerformed(evt);
+ }
+ });
+
+ this.pbUp.setText("^");
+ this.pbUp.setToolTipText("Monter");
+ this.pbUp.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PnlSortBy.this.pbUpActionPerformed(evt);
+ }
+ });
+
+ this.pbDown.setText("V");
+ this.pbDown.setToolTipText("Descendre");
+ this.pbDown.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PnlSortBy.this.pbDownActionPerformed(evt);
+ }
+ });
+
+ final 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(this.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, this.pbAddOne, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, this.pbAddAll, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).add(org.jdesktop.layout.GroupLayout.TRAILING, this.pbRemoveAll, 0, 0, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, this.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, this.pbDown, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, this.pbUp))).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.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, this.jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 286, Short.MAX_VALUE)
+ .add(this.jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 286, Short.MAX_VALUE)
+ .add(org.jdesktop.layout.GroupLayout.LEADING,
+ layout.createSequentialGroup().add(this.pbAddAll).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.pbAddOne).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.pbRemoveOne)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.pbRemoveAll).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 118, Short.MAX_VALUE).add(this.pbUp).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.pbDown)))
+ .addContainerGap()));
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void pbUpActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbUpActionPerformed
+ boolean moved = false;
+ final int[] selectedRows = this.tblChampTries.getSelectedRows();
+ for (int i = 0; i < selectedRows.length; i++) {
+ final int row = selectedRows[i];
+ if (row > i) {
+ final ChampTriable ch = this.champsTriables.remove(row);
+ this.champsTriables.insertElementAt(ch, row - 1);
+ moved = true;
+ }
+ }
+ if (moved) {
+ this.tm.fireTableDataChanged();
+ for (int i = 0; i < selectedRows.length; i++) {
+ final int row = selectedRows[i];
+ if (row > i) {
+ this.tblChampTries.getSelectionModel().addSelectionInterval(row - 1, row - 1);
+ }
+ }
+ }
+ }// GEN-LAST:event_pbUpActionPerformed
+
+ private void pbDownActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbDownActionPerformed
+ // TODO: corriger cette méthode
+
+ final int[] selectedRows = this.tblChampTries.getSelectedRows();
+ boolean moved = false;
+ for (int i = selectedRows.length - 1; i >= 0; i--) {
+ final int row = selectedRows[i];
+ if (row < this.champsTriables.size() - i - 1) {
+ final ChampTriable ch = this.champsTriables.remove(row);
+ if (row + 1 < this.champsTriables.size()) {
+ this.champsTriables.insertElementAt(ch, row + 1);
+ } else {
+ this.champsTriables.add(ch);
+ }
+ moved = true;
+ }
+ }
+ if (moved) {
+ this.tm.fireTableDataChanged();
+ for (int i = selectedRows.length - 1; i >= 0; i--) {
+ final int row = selectedRows[i];
+ if (row < this.champsTriables.size() - i) {
+ this.tblChampTries.getSelectionModel().addSelectionInterval(row + 1, row + 1);
+ }
+ }
+ }
+ }// GEN-LAST:event_pbDownActionPerformed
+
+ private void pbAddAllActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbAddAllActionPerformed
+ for (final ChampModel cm : this.sortableChamps) {
+ final ChampTriable ct = new ChampTriable(cm.getId(), cm.getLibelle(), "ASC");
+ this.champsTriables.add(ct);
+ }
+ this.sortableChamps.clear();
+ this.lstChamps.setListData(this.sortableChamps);
+ this.tm.fireTableDataChanged();
+ }// GEN-LAST:event_pbAddAllActionPerformed
+
+ private void pbAddOneActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbAddOneActionPerformed
+ final int[] indexes = this.lstChamps.getSelectedIndices();
+ for (final int i : indexes) {
+ final ChampModel cm = this.sortableChamps.get(i);
+ this.champsTriables.add(new ChampTriable(cm.getId(), cm.getLibelle(), "ASC"));
+ }
+ for (int i = indexes.length - 1; i >= 0; i--) {
+ this.sortableChamps.remove(indexes[i]);
+ }
+ this.lstChamps.setListData(this.sortableChamps);
+ this.tm.fireTableDataChanged();
+ }// GEN-LAST:event_pbAddOneActionPerformed
+
+ private void pbRemoveOneActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbRemoveOneActionPerformed
+ final int[] indexes = this.tblChampTries.getSelectedRows();
+ for (final int i : indexes) {
+ final ChampTriable ct = this.champsTriables.get(i);
+ final ChampModel cm = this.lrm.getChamps().get(ct.id);
+ this.sortableChamps.add(cm);
+ }
+ for (int i = indexes.length - 1; i >= 0; i--) {
+ this.champsTriables.remove(indexes[i]);
+ }
+ this.lstChamps.setListData(this.sortableChamps);
+ this.tm.fireTableDataChanged();
+ }// GEN-LAST:event_pbRemoveOneActionPerformed
+
+ private void pbRemoveAllActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbRemoveAllActionPerformed
+ for (final ChampTriable ct : this.champsTriables) {
+ final ChampModel cm = this.lrm.getChamps().get(ct.id);
+ this.sortableChamps.add(cm);
+ }
+ this.champsTriables.clear();
+ this.lstChamps.setListData(this.sortableChamps);
+ this.tm.fireTableDataChanged();
+ }// GEN-LAST:event_pbRemoveAllActionPerformed
+
+ @Override
+ public void doUpdate() {
+ final StringBuffer fields = new StringBuffer();
+ final StringBuffer sorts = new StringBuffer();
+ for (final ChampTriable ct : this.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);
+ }
+ this.lrm.setTriDefaut(fields.toString());
+ this.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 final String id;
+ private String sens;
+ private final String desc;
+
+ public ChampTriable(final String id, final String desc, final String sens) {
+ super();
+ this.id = id;
+ this.desc = desc;
+ this.sens = sens;
+ }
+
+ @Override
+ public String toString() {
+ return this.desc;
+ }
+ }
+
+ public static class TriableTableModel extends AbstractTableModel {
+ private final Vector<ChampTriable> champs;
+
+ public TriableTableModel(final Vector<ChampTriable> champs) {
+ // super(champs,null);
+ this.champs = champs;
+ }
+
+ @Override
+ public String getColumnName(final int column) {
+ switch (column) {
+ case 0:
+ return "Champ";
+ case 1:
+ return "Sens";
+ }
+ return null;
+ }
+
+ @Override
+ public int getColumnCount() {
+ return 2;
+ }
+
+ @Override
+ public boolean isCellEditable(final int row, final int column) {
+ return column == 1;
+ }
+
+ @Override
+ public Object getValueAt(final int row, final int column) {
+ final ChampTriable ct = this.champs.get(row);
+ switch (column) {
+ case 0:
+ return ct.toString();
+ case 1:
+ return ct.sens;
+ }
+ return null;
+ }
+
+ @Override
+ public int getRowCount() {
+ return this.champs.size();
+ }
+
+ @Override
+ public Class<?> getColumnClass(final int columnIndex) {
+ return String.class;
+ }
+
+ @Override
+ public void setValueAt(final Object aValue, final int rowIndex, final int columnIndex) {
+ final ChampTriable ct = this.champs.get(rowIndex);
+ ct.sens = aValue.toString();
+ }
+
+ }
}
*/
package fr.gouv.finances.cp.xemelios.ui.tools;
+import java.io.File;
+import java.lang.reflect.Constructor;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.log4j.Logger;
+
import fr.gouv.finances.cp.utils.PropertiesExpansion;
import fr.gouv.finances.cp.xemelios.ui.MainWindow;
import fr.gouv.finances.cp.xemelios.ui.importArchive.ArchiveWizardDisplayer;
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.net.MalformedURLException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.List;
-import org.apache.log4j.Logger;
/**
- *
+ *
* @author cmarchand
*/
public class SwingToolServiceProviderFactory extends ToolServiceProviderFactory {
- private static final Logger logger = Logger.getLogger(SwingToolServiceProviderFactory.class);
-
- 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 : MainWindow.getInstance().getDocModels().getDocuments()) {
- ids.add(dm.getId());
- }
- } catch (Exception ex) {
- // on peut ignorer
- }
- logger.debug(ids);
- return ids;
- }
-
- @Override
- public List<String> getSearchableDocumentsConfigurations() {
- return getAvailableDocumentsConfigurations();
- }
-
- @Override
- public List<String> getImportableDocumentsConfigurations() {
- ArrayList<String> ids = new ArrayList<String>();
- try {
- for (DocumentModel dm : MainWindow.getInstance().getDocModels().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 : MainWindow.getInstance().getDocModels().getDocuments()) {
- if (dm.isBrowsable()) {
- ids.add(dm.getId());
- }
- }
- } catch (Exception ex) {
- // on peut ignorer
- }
- return ids;
- }
-
- @Override
- public String getDocumentConfigurationTitle(String documentId) {
- try {
- return MainWindow.getInstance().getDocModels().getDocumentById(documentId).getTitre();
- } catch (Exception ex) {
- return null;
- }
- }
-
- @Override
- public void importFile(File fileToImport, String documentId) throws Exception {
- if (Constants.XEMELIOS_ARCHIVE_SIGN.equals(documentId)) {
- importXemeliosArchive(fileToImport);
- } else {
- try {
- DocumentModel dm = MainWindow.getInstance().getDocModels().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, PropertiesExpansion.class);
- Object obj = cc.newInstance(MainWindow.getInstance().getConnectedUser(), MainWindow.getInstance().getEnvProperties());
- 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 ex;
- } finally {
- //waiter.stopProgress();
- }
- }
- }
-
- private void importXemeliosArchive(File archive) throws Exception {
-// ImportServiceSwingProvider isp = new ImportServiceSwingProvider(MainWindow.getInstance(), null, 0);
-// isp.setDisplayFeedback(false);
-// XemeliosArchiveImporter xai = new XemeliosArchiveImporter(MainWindow.getInstance().getDocModels(), archive, isp, MainWindow.getInstance().getEnvProperties());
-// xai.setUser(MainWindow.getInstance().getConnectedUser());
-// MainWindow.XemeliosArchiveImporterWorker worker = new MainWindow.XemeliosArchiveImporterWorker(xai);
-// worker.execute();
- ArchiveWizardDisplayer awd = new ArchiveWizardDisplayer(MainWindow.getInstance(), archive);
- }
-
- @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());
- }
-
- public URL getDocumentSchema(String documentId) {
- DocumentModel dm = MainWindow.getInstance().getDocModels().getDocumentById(documentId);
- if(dm!=null) {
- if(dm.getSchema()!=null) {
- File dir = new File(dm.getBaseDirectory());
- File schema = new File(dir,dm.getSchema());
- try {
- return schema.toURI().toURL();
- } catch(MalformedURLException mEx) {
- logger.error("getDocumentSchema("+documentId+")",mEx);
- return null;
- }
- }
- }
- return null;
- }
- }
+ private static final Logger logger = Logger.getLogger(SwingToolServiceProviderFactory.class);
+
+ private final SwingToolServiceProvider service;
+
+ public SwingToolServiceProviderFactory() {
+ super();
+ this.service = new SwingToolServiceProvider();
+ }
+
+ @Override
+ public XemeliosToolServiceProvider getServiceProvider() {
+ return this.service;
+ }
+
+ private class SwingToolServiceProvider implements XemeliosToolServiceProvider {
+
+ @Override
+ public List<String> getAvailableDocumentsConfigurations() {
+ final ArrayList<String> ids = new ArrayList<String>();
+ try {
+ for (final DocumentModel dm : MainWindow.getInstance().getDocModels().getDocuments()) {
+ ids.add(dm.getId());
+ }
+ } catch (final Exception ex) {
+ // on peut ignorer
+ }
+ logger.debug(ids);
+ return ids;
+ }
+
+ @Override
+ public List<String> getSearchableDocumentsConfigurations() {
+ return this.getAvailableDocumentsConfigurations();
+ }
+
+ @Override
+ public List<String> getImportableDocumentsConfigurations() {
+ final ArrayList<String> ids = new ArrayList<String>();
+ try {
+ for (final DocumentModel dm : MainWindow.getInstance().getDocModels().getDocuments()) {
+ if (dm.isImportable()) {
+ ids.add(dm.getId());
+ }
+ }
+ } catch (final Exception ex) {
+ // on peut ignorer
+ }
+ return ids;
+ }
+
+ @Override
+ public List<String> getBrowsableDocumentsConfigurations() {
+ final ArrayList<String> ids = new ArrayList<String>();
+ try {
+ for (final DocumentModel dm : MainWindow.getInstance().getDocModels().getDocuments()) {
+ if (dm.isBrowsable()) {
+ ids.add(dm.getId());
+ }
+ }
+ } catch (final Exception ex) {
+ // on peut ignorer
+ }
+ return ids;
+ }
+
+ @Override
+ public String getDocumentConfigurationTitle(final String documentId) {
+ try {
+ return MainWindow.getInstance().getDocModels().getDocumentById(documentId).getTitre();
+ } catch (final Exception ex) {
+ return null;
+ }
+ }
+
+ @Override
+ public void importFile(final File fileToImport, final String documentId) throws Exception {
+ if (Constants.XEMELIOS_ARCHIVE_SIGN.equals(documentId)) {
+ this.importXemeliosArchive(fileToImport);
+ } else {
+ try {
+ final DocumentModel dm = MainWindow.getInstance().getDocModels().getDocumentById(documentId);
+ if (!DataLayerManager.getImplementation().canImportDocument(documentId, MainWindow.getInstance().getConnectedUser())) {
+ final 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);
+ }
+ final Class clazz = Class.forName(dm.getImportClass());
+ final Constructor cc = clazz.getConstructor(XemeliosUser.class, PropertiesExpansion.class);
+ final Object obj = cc.newInstance(MainWindow.getInstance().getConnectedUser(), MainWindow.getInstance().getEnvProperties());
+ 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.");
+ }
+ final EtatImporteur ei = (EtatImporteur) obj;
+ final MainWindow.ImportContent fToImport = new MainWindow.ImportContent();
+ final ArrayList<File> files = new ArrayList<File>();
+ files.add(fileToImport);
+ fToImport.setFilesToImport(files);
+ if (fToImport.getImportCount() > 0) {
+ MainWindow.getInstance().doImport(ei, fToImport, dm, false);
+ }
+ } catch (final Exception ex) {
+ throw ex;
+ } finally {
+ // waiter.stopProgress();
+ }
+ }
+ }
+
+ private void importXemeliosArchive(final File archive) throws Exception {
+ // ImportServiceSwingProvider isp = new ImportServiceSwingProvider(MainWindow.getInstance(), null, 0);
+ // isp.setDisplayFeedback(false);
+ // XemeliosArchiveImporter xai = new XemeliosArchiveImporter(MainWindow.getInstance().getDocModels(), archive, isp,
+ // MainWindow.getInstance().getEnvProperties());
+ // xai.setUser(MainWindow.getInstance().getConnectedUser());
+ // MainWindow.XemeliosArchiveImporterWorker worker = new MainWindow.XemeliosArchiveImporterWorker(xai);
+ // worker.execute();
+ final ArchiveWizardDisplayer awd = new ArchiveWizardDisplayer(MainWindow.getInstance(), archive);
+ }
+
+ @Override
+ public void importFiles(final List<ImportContent> filesToImport) throws Exception {
+ for (final ImportContent ic : filesToImport) {
+ this.importFile(ic.getFile(), ic.getDocumentId());
+ }
+ }
+
+ @Override
+ public XemeliosProperties getApplicationProperties() {
+ return new XemeliosPropertiesImpl(MainWindow.getInstance().getEnvProperties());
+ }
+
+ @Override
+ public URL getDocumentSchema(final String documentId) {
+ final DocumentModel dm = MainWindow.getInstance().getDocModels().getDocumentById(documentId);
+ if (dm != null) {
+ if (dm.getSchema() != null) {
+ final File dir = new File(dm.getBaseDirectory());
+ final File schema = new File(dir, dm.getSchema());
+ try {
+ return schema.toURI().toURL();
+ } catch (final MalformedURLException mEx) {
+ logger.error("getDocumentSchema(" + documentId + ")", mEx);
+ return null;
+ }
+ }
+ }
+ return null;
+ }
+ }
}
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); }
+ private static final long serialVersionUID = 1L;
+
+ public LocalException(final String msg) {
+ super(msg);
+ }
}
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);
- }
-
+
+ /** Creates a new instance of NotFoundException */
+ public NotFoundException(final String msg) {
+ super(msg);
+ }
+
}
package fr.gouv.finances.cp.xemelios.ui.xhtmlviewer;
/**
- *
+ *
* @author chm
* @deprecated
*/
+@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; }
+
+ private final XemeliosXhtmlPanel pane;
+ private final double scale;
+
+ public ScaleChangeEvent(final XemeliosXhtmlPanel pane, final double scale) {
+ super();
+ this.pane = pane;
+ this.scale = scale;
+ }
+
+ public XemeliosXhtmlPanel getComponent() {
+ return this.pane;
+ }
+
+ public double getScale() {
+ return this.scale;
+ }
}
package fr.gouv.finances.cp.xemelios.ui.xhtmlviewer;
/**
- *
+ *
* @author chm
* @deprecated
*/
+@Deprecated
public interface ScaleChangeListener {
- public void scaleChanged(ScaleChangeEvent evt);
+ public void scaleChanged(ScaleChangeEvent evt);
}
*/
package fr.gouv.finances.cp.xemelios.ui.xhtmlviewer;
-import fr.gouv.finances.cp.utils.PropertiesExpansion;
import java.awt.Component;
import java.awt.Desktop;
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.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
-import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
-import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Hashtable;
-import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.StringTokenizer;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
-import javax.xml.parsers.DocumentBuilder;
+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.xhtmlrenderer.resource.XMLResource;
import org.xhtmlrenderer.swing.NaiveUserAgent;
-import com.lowagie.text.DocumentException;
-
+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.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.NavigationContext;
import fr.gouv.finances.dgfip.utils.Pair;
import fr.gouv.finances.dgfip.utils.Xslt;
-import fr.gouv.finances.dgfip.utils.XsltFileChooser;
import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
-import fr.gouv.finances.dgfip.utils.xml.transform.CustomURIResolver;
+import fr.gouv.finances.dgfip.utils.xml.transform.AbstractURIResolver;
import fr.gouv.finances.dgfip.xemelios.auth.UnauthorizedException;
import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
import fr.gouv.finances.dgfip.xemelios.common.Constants;
-import fr.gouv.finances.dgfip.xemelios.common.DefaultXsltChooser;
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.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.TransformerException;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMResult;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamSource;
-
/**
*
* @author chm
public static final int MAX_VISITED_URIS = 100;
LinkedHashMap<String, Object> visitedUris;
private int index = -1;
- private ArrayList<String> history = new ArrayList<String>();
+ private final ArrayList<String> history = new ArrayList<String>();
private String baseUrl;
private UpdatableToolbar toolbar;
protected NavigationContext nc;
private XemeliosUser user;
private PropertiesExpansion envProperties;
- public XemeliosUserAgent(MainWindow mw, Component viewer, UpdatableToolbar toolbar, XemeliosUser user) {
+ public XemeliosUserAgent(final MainWindow mw, final Component viewer, final UpdatableToolbar toolbar, final XemeliosUser user) {
this(viewer, mw.getEnvProperties(), user);
// this.mainWindow = mw;
this.toolbar = toolbar;
- xpf = FactoryProvider.getXPathFactory();
+ this.xpf = FactoryProvider.getXPathFactory();
}
- public XemeliosUserAgent(Component viewer, PropertiesExpansion envProperties, XemeliosUser user) {
+ public XemeliosUserAgent(final Component viewer, final PropertiesExpansion envProperties, final XemeliosUser user) {
super();
this.user = user;
this.viewer = viewer;
this.envProperties = envProperties;
- visitedUris = new LinkedHashMap<String, Object>(16, 0.75f, true) {
+ this.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;
+ protected boolean removeEldestEntry(final Entry<String, Object> eldest) {
+ return this.size() == XemeliosUserAgent.MAX_VISITED_URIS;
}
};
}
@Override
- public boolean isVisited(String uri) {
- return visitedUris.containsKey(uri);
+ public boolean isVisited(final String uri) {
+ return this.visitedUris.containsKey(uri);
}
@Override
- public String resolveURI(String uri) {
+ public String resolveURI(final String uri) {
if (uri == null) {
- return getBaseURL();
+ return this.getBaseURL();
}
if (uri.startsWith("xemelios:")) {
- logger.debug("resolving " + uri);
+ XemeliosUserAgent.logger.debug("resolving " + uri);
String shortUri;
String anchor = null;
- int indexSharp = uri.indexOf("#");
+ final 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);
+ Dest dest = (Dest) this.visitedUris.get(shortUri);
+ if (dest == null || "true".equals(this.envProperties.getProperty("xemelios.navigation.force-reload"))) {
+ dest = this.calculateQuery(shortUri);
+ this.visitedUris.put(shortUri, dest);
}
- if (dest == null && nc != null) {
- dest = nc.getLastDestination();
+ if (dest == null && this.nc != null) {
+ dest = this.nc.getLastDestination();
}
if (dest != null && dest.url != null) {
if (dest.toExternal) {
try {
- logger.debug("openning " + dest.url.toExternalForm());
+ XemeliosUserAgent.logger.debug("openning " + dest.url.toExternalForm());
StartUrl.startUrl(dest.url.toExternalForm());
- } catch (ToolException toEx) {
+ } catch (final ToolException toEx) {
}
return null;
} else {
@Override
@SuppressWarnings("empty-statement")
- public void setBaseURL(String url) {
+ public void setBaseURL(final String url) {
super.setBaseURL(url);
- if (baseUrl != null && baseUrl.startsWith("error:")) {
- baseUrl = null;
+ if (this.baseUrl != null && this.baseUrl.startsWith("error:")) {
+ this.baseUrl = null;
}
- baseUrl = url;
- if (baseUrl == null) {
+ this.baseUrl = url;
+ if (this.baseUrl == null) {
return;
}
- if (index >= 0) {
- String historic = (String) history.get(index);
- if (historic.equals(baseUrl)) {
- toolbar.updateToolbarButtons();
+ if (this.index >= 0) {
+ final String historic = this.history.get(this.index);
+ if (historic.equals(this.baseUrl)) {
+ this.toolbar.updateToolbarButtons();
return;// moved in history
}
}
- index++;
- for (int i = index; i < history.size(); history.remove(i))
+ this.index++;
+ for (final int i = this.index; i < this.history.size(); this.history.remove(i)) {
;
- history.add(index, baseUrl);
- toolbar.updateToolbarButtons();
- toolbar.setBaseUrl(url);
+ }
+ this.history.add(this.index, this.baseUrl);
+ this.toolbar.updateToolbarButtons();
+ this.toolbar.setBaseUrl(url);
}
public String getForward() {
- index++;
- return (String) history.get(index);
+ this.index++;
+ return this.history.get(this.index);
}
public String getBack() {
- index--;
- return (String) history.get(index);
+ this.index--;
+ return this.history.get(this.index);
}
public boolean hasForward() {
- return (index + 1 < history.size() && index >= 0);
+ return (this.index + 1 < this.history.size() && this.index >= 0);
}
public boolean hasBack() {
- return (index > 0);
+ return (this.index > 0);
}
@Override
- protected InputStream resolveAndOpenStream(String uri) {
+ protected InputStream resolveAndOpenStream(final String uri) {
InputStream retValue = null;
try {
- URL url = new URL(uri);
+ final 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);
+ final HttpClient client = NetAccess.getHttpClient(this.envProperties);
+ final HttpMethod meth = new GetMethod(uri);
+ final int retCode = client.executeMethod(meth);
if (retCode <= 300) {
retValue = meth.getResponseBodyAsStream();
}
}
- } catch (MalformedURLException muEx) {
+ } catch (final MalformedURLException muEx) {
// TODO
- } catch (DataConfigurationException dcEx) {
+ } catch (final DataConfigurationException dcEx) {
// TODO
- } catch (IOException ioEx) {
+ } catch (final IOException ioEx) {
// TODO
}
if (retValue == null) {
return retValue;
}
- public Dest calculateQuery(String query) {
+ public Dest calculateQuery(final String query) {
NavigationContext ctx = null;
- if (nc == null) {
+ if (this.nc == null) {
ctx = new NavigationContext();
} else {
- ctx = nc.clone();
+ ctx = this.nc.clone();
}
- Hashtable<String, Object> params = new Hashtable<String, Object>();
+ final 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('?');
+ final 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, "&");
+ final Properties additionalParameters = new Properties();
+ final StringTokenizer st = new StringTokenizer(sTmp, "&");
while (st.hasMoreTokens()) {
- String data = st.nextToken();
- logger.debug("parsing " + data);
- int pos = data.indexOf('=');
+ final String data = st.nextToken();
+ XemeliosUserAgent.logger.debug("parsing " + data);
+ final int pos = data.indexOf('=');
if (pos > 0) {
- String paramName = data.substring(0, pos);
+ final 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);
+ XemeliosUserAgent.logger.debug(paramName + "=" + paramValue);
+ } catch (final Throwable t) {
+ XemeliosUserAgent.logger.error("decoding", t);
}
if ("docId".equals(paramName)) {
ctx.setDocId(paramValue);
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);
+ final int virg = paramValue.indexOf(',');
+ final String pName = paramValue.substring(1, virg);
String pValue = paramValue.substring(virg + 1, paramValue.length() - 1);
int pos2 = pValue.indexOf('%'); // interprétation
// de
// formulaires
while (pos2 >= 0) {
- int closing = pValue.indexOf('%', pos2 + 1);
+ final int closing = pValue.indexOf('%', pos2 + 1);
if (closing < 0) {
throw new RuntimeException("a '%' is not closed! : " + pValue);
}
- String paramNam = pValue.substring(pos2 + 1, closing);
+ final 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);
+ final String begin = pValue.substring(0, pos2);
+ final String end = pValue.substring(closing + 1);
+ final String replacedValue = additionalParameters.getProperty(paramNam);
pValue = begin.concat(replacedValue).concat(end);
pos2 = pValue.indexOf('%', pos2);
} else {
}
}
params.put(pName, pValue);
- logger.debug("Adding " + pName + "=" + pValue);
+ XemeliosUserAgent.logger.debug("Adding " + pName + "=" + pValue);
} else {
additionalParameters.setProperty(paramName, paramValue);
}
- logger.debug(paramName + "=" + paramValue);
- } catch (Throwable t) {
- logger.error("decoding", t);
+ XemeliosUserAgent.logger.debug(paramName + "=" + paramValue);
+ } catch (final Throwable t) {
+ XemeliosUserAgent.logger.error("decoding", t);
}
}
}
}
ctx.configXPath(additionalParameters);
- return generateDestContext(ctx, params, HtmlViewer.INTERNAL_DESTINATION);
+ return this.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(Constants.SYS_PROP_RESOURCES_LOCATION));
- File res = new File(resourceDir, sTmp);
+ final File resourceDir = new File(this.envProperties.getProperty(Constants.SYS_PROP_RESOURCES_LOCATION));
+ final File res = new File(resourceDir, sTmp);
ret = new Dest(res.toURI().toURL(), false);
- } catch (Throwable t) {
+ } catch (final Throwable t) {
}
return ret;
} else if ("attachment".equals(servlet)) {
- StringTokenizer st = new StringTokenizer(sTmp, "&");
+ final 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('=');
+ final String data = st.nextToken();
+ XemeliosUserAgent.logger.debug("parsing " + data);
+ final int pos = data.indexOf('=');
if (pos > 0) {
- String paramName = data.substring(0, pos);
+ final 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) {
+ } catch (final Throwable t) {
}
if ("collectivite".equals(paramName)) {
pjCollectivite = paramValue;
}
if (pjId != null && pjCollectivite != null) {
try {
- DataImpl impl = DataLayerManager.getImplementation();
- PJRef pjRef = impl.getPjByUniqueId(new Pair(pjCollectivite, ""), pjId, user);
+ final DataImpl impl = DataLayerManager.getImplementation();
+ final PJRef pjRef = impl.getPjByUniqueId(new Pair(pjCollectivite, ""), pjId, this.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);
+ final File tmpFile = File.createTempFile("tmp-", fileName, FileUtils.getTempDir());
+ XemeliosUserAgent.logger.debug("saving PJ to " + tmpFile.getAbsolutePath());
+ final 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);
+ JOptionPane.showMessageDialog(this.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);
+ } catch (final UnauthorizedException ex) {
+ JOptionPane.showMessageDialog(this.viewer, ex.getMessage(), "Droits insuffisants", JOptionPane.WARNING_MESSAGE);
+ } catch (final DataConfigurationException dcEx) {
+ XemeliosUserAgent.logger.error("while getting PJ:", dcEx);
+ } catch (final DataAccessException daEx) {
+ XemeliosUserAgent.logger.error("while getting PJ:", daEx);
+ } catch (final IOException ioEx) {
+ XemeliosUserAgent.logger.error("while getting PJ:", ioEx);
}
}
} else if ("customLink".equals(servlet)) {
- CustomLinkParameters clp = new CustomLinkParameters();
- Properties additionalParameters = new Properties();
+ final CustomLinkParameters clp = new CustomLinkParameters();
+ final Properties additionalParameters = new Properties();
- StringTokenizer st = new StringTokenizer(sTmp, "&");
+ final StringTokenizer st = new StringTokenizer(sTmp, "&");
while (st.hasMoreTokens()) {
- String data = st.nextToken();
- logger.debug("parsing " + data);
- int pos = data.indexOf('=');
+ final String data = st.nextToken();
+ XemeliosUserAgent.logger.debug("parsing " + data);
+ final int pos = data.indexOf('=');
if (pos > 0) {
- String paramName = data.substring(0, pos);
+ final 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);
+ XemeliosUserAgent.logger.debug(paramName + "=" + paramValue);
+ } catch (final Throwable t) {
+ XemeliosUserAgent.logger.error("decoding", t);
}
if ("srcDocId".equals(paramName)) {
clp.setSrcDocId(paramValue);
try {
if (paramName.startsWith("xsl:param")) {
// logger.debug("xsl:param -> "+paramValue);
- int virg = paramValue.indexOf(',');
- String pName = paramValue.substring(1, virg);
+ final int virg = paramValue.indexOf(',');
+ final String pName = paramValue.substring(1, virg);
String pValue = paramValue.substring(virg + 1, paramValue.length() - 1);
int pos2 = pValue.indexOf('%'); // interprétation
// de
// formulaires
while (pos2 >= 0) {
- int closing = pValue.indexOf('%', pos2 + 1);
+ final int closing = pValue.indexOf('%', pos2 + 1);
if (closing < 0) {
throw new RuntimeException("a '%' is not closed! : " + pValue);
}
- String paramNam = pValue.substring(pos2 + 1, closing);
+ final 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);
+ final String begin = pValue.substring(0, pos2);
+ final String end = pValue.substring(closing + 1);
+ final String replacedValue = additionalParameters.getProperty(paramNam);
pValue = begin.concat(replacedValue).concat(end);
pos2 = pValue.indexOf('%', pos2);
} else {
}
}
additionalParameters.put(pName, pValue);
- logger.debug("Adding additionalParameters " + pName + "=" + pValue);
+ XemeliosUserAgent.logger.debug("Adding additionalParameters " + pName + "=" + pValue);
} else {
// additionalParameters.setProperty(paramName,
// paramValue);
clp.addParameter(paramName, paramValue);
}
}
- logger.debug(paramName + "=" + paramValue);
- } catch (Throwable t) {
- logger.error("decoding", t);
+ XemeliosUserAgent.logger.debug(paramName + "=" + paramValue);
+ } catch (final Throwable t) {
+ XemeliosUserAgent.logger.error("decoding", t);
}
}
}
}
try {
- String clrClassName = clp.getCustomLinkResolverName(Loader.getDocumentsInfos(null));
- Class clazz = Class.forName(clrClassName);
- CustomLinkResolver clr = (CustomLinkResolver) clazz.newInstance();
+ final String clrClassName = clp.getCustomLinkResolverName(Loader.getDocumentsInfos(null));
+ final Class clazz = Class.forName(clrClassName);
+ final 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);
+ return this.generateDestContext(ctx, clr, clp, HtmlViewer.INTERNAL_DESTINATION);
+ } catch (final Exception ex) {
+ XemeliosUserAgent.logger.error("calculateQuery(" + query + ") / customLink", ex);
}
} else if ("showSrc".equals(servlet)) {
String hostName = null;
String urlStr = null;
- StringTokenizer st = new StringTokenizer(sTmp, "&");
+ final StringTokenizer st = new StringTokenizer(sTmp, "&");
while (st.hasMoreTokens()) {
- String data = st.nextToken();
- int pos = data.indexOf('=');
+ final String data = st.nextToken();
+ final int pos = data.indexOf('=');
if (pos > 0) {
- String paramName = data.substring(0, pos);
+ final String paramName = data.substring(0, pos);
String paramValue = null;
- try {
+ try {
paramValue = URLDecoder.decode(data.substring(pos + 1), "UTF-8");
- } catch (Throwable t) {
- logger.error("decoding", t);
+ } catch (final Throwable t) {
+ XemeliosUserAgent.logger.error("decoding", t);
}
if ("host".equals(paramName)) {
hostName = paramValue;
if (hostName != null && urlStr != null) {
if (hostName.equals(HostUtils.getHostName())) {
try {
- File f = new File(urlStr);
+ final File f = new File(urlStr);
if (!f.exists()) {
- JOptionPane.showMessageDialog(viewer, "Le fichier est introuvable : " + urlStr, "Information", JOptionPane.WARNING_MESSAGE);
+ JOptionPane.showMessageDialog(this.viewer, "Le fichier est introuvable : " + urlStr, "Information", JOptionPane.WARNING_MESSAGE);
} else {
- //URL url = new URL("file://" + urlStr);
- //Desktop.getDesktop().browse(url.toURI());
- //changement de méthode afin de prendre en compte les espaces à cause de cette daube d'IE qui n'interprète pas le %20
+ // URL url = new URL("file://" + urlStr);
+ // Desktop.getDesktop().browse(url.toURI());
+ // changement de méthode afin de prendre en compte les espaces à cause de cette daube d'IE qui n'interprète pas le %20
Desktop.getDesktop().open(f);
}
- } catch (Exception ex) {
- JOptionPane.showMessageDialog(viewer, "Une erreur inattendue s'est produite : \n" + ex.getMessage(), "Information", JOptionPane.WARNING_MESSAGE);
+ } catch (final Exception ex) {
+ JOptionPane.showMessageDialog(this.viewer, "Une erreur inattendue s'est produite : \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);
+ JOptionPane.showMessageDialog(this.viewer, "Ce fichier n'a pas été analysé sur cet ordinateur, il n'est pas possible de le visualiser", "Information", JOptionPane.WARNING_MESSAGE);
}
}
} else if ("savePdf".equals(servlet)) {
- try {
+ try {
// Paramètres
- StringTokenizer st = new StringTokenizer(sTmp, "&");
- Hashtable<String,String> additionalParameters = new Hashtable<String, String>();
+ final StringTokenizer st = new StringTokenizer(sTmp, "&");
+ final Hashtable<String, String> additionalParameters = new Hashtable<String, String>();
while (st.hasMoreTokens()) {
- String data = st.nextToken();
- logger.debug("parsing " + data);
- int pos = data.indexOf('=');
+ final String data = st.nextToken();
+ XemeliosUserAgent.logger.debug("parsing " + data);
+ final int pos = data.indexOf('=');
if (pos > 0) {
- String paramName = data.substring(0, pos);
+ final 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);
+ XemeliosUserAgent.logger.debug(paramName + "=" + paramValue);
+ } catch (final Throwable t) {
+ XemeliosUserAgent.logger.error("decoding", t);
}
if ("docId".equals(paramName)) {
ctx.setDocId(paramValue);
try {
if (paramName.startsWith("xsl:param")) {
// logger.debug("xsl:param -> "+paramValue);
- int virg = paramValue.indexOf(',');
- String pName = paramValue.substring(1, virg);
+ final int virg = paramValue.indexOf(',');
+ final 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);
+ final int closing = pValue.indexOf('%', pos2 + 1);
if (closing < 0) {
throw new RuntimeException("a '%' is not closed! : " + pValue);
}
- String paramNam = pValue.substring(pos2 + 1, closing);
+ final 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.get(paramNam);
+ final String begin = pValue.substring(0, pos2);
+ final String end = pValue.substring(closing + 1);
+ final String replacedValue = additionalParameters.get(paramNam);
pValue = begin.concat(replacedValue).concat(end);
pos2 = pValue.indexOf('%', pos2);
} else {
}
}
additionalParameters.put(pName, pValue);
- logger.debug("Adding additionalParameters " + pName + "=" + pValue);
+ XemeliosUserAgent.logger.debug("Adding additionalParameters " + pName + "=" + pValue);
}
- logger.debug(paramName + "=" + paramValue);
- } catch (Throwable t) {
- logger.error("decoding", t);
+ XemeliosUserAgent.logger.debug(paramName + "=" + paramValue);
+ } catch (final Throwable t) {
+ XemeliosUserAgent.logger.error("decoding", t);
}
}
}
}
- DataImpl impl = DataLayerManager.getImplementation();
- DocumentModel dm = Loader.getDocumentsInfos(null).getDocumentById(ctx.getDocId());
- EtatModel em = dm.getEtatById(ctx.getEtatId());
- ElementModel elm = em.getElementById(ctx.getElementId());
-
- ctx.setPath(elm.getPath().getPath()+ctx.getPath());
-
- // Récupération des document id en base
- ArrayList<String> docIds = impl.getDocumentListFromXPath(elm, ctx.getCollectivite(), ctx.getBudget(), ctx.getSp1(), ctx.getSp2(), ctx.getSp3(), ctx.getPath(), user);
+ final DataImpl impl = DataLayerManager.getImplementation();
+ final DocumentModel dm = Loader.getDocumentsInfos(null).getDocumentById(ctx.getDocId());
+ final EtatModel em = dm.getEtatById(ctx.getEtatId());
+ final ElementModel elm = em.getElementById(ctx.getElementId());
+
+ ctx.setPath(elm.getPath().getPath() + ctx.getPath());
+
+ // Récupération des document id en base
+ final ArrayList<String> docIds = impl.getDocumentListFromXPath(elm, ctx.getCollectivite(), ctx.getBudget(), ctx.getSp1(), ctx.getSp2(), ctx.getSp3(), ctx.getPath(), this.user);
String docId = null;
if (docIds.size() == 0) {
- throw new UnresolvedException("Le document est introuvable.");
- } else if (docIds.size() > 1 && !em.isMultiPage()) {
- throw new UnresolvedException("Plusieurs documents répondant à ces critères ont été trouvés.");
- } else {
- docId = docIds.get(0);
- }
-
+ throw new UnresolvedException("Le document est introuvable.");
+ } else if (docIds.size() > 1 && !em.isMultiPage()) {
+ throw new UnresolvedException("Plusieurs documents répondant à ces critères ont été trouvés.");
+ } else {
+ docId = docIds.get(0);
+ }
+
// Application de la XSL d'affichage
- Document doc = impl.getDocumentAsDom(em, new Pair(ctx.getCollectivite(), null), new Pair(ctx.getBudget(), null), docId, user);
-
- File xslFile = Xslt.getFile(dm, em, elm, doc);
- TransformerFactory tFactory = FactoryProvider.getTransformerFactory();
- tFactory.setURIResolver(new CustomURIResolver(tFactory.getURIResolver(), xslFile.getParentFile().toURI().toURL().toExternalForm()));
- Transformer t = tFactory.newTransformer(new StreamSource(xslFile));
- for (String key:additionalParameters.keySet()) {
- String paramValue = additionalParameters.get(key);
- t.setParameter(key, paramValue);
- logger.debug("putting xsl param(" + key + "," + paramValue + ")");
- }
- t.setParameter("browser-destination", "internal");
-
- //ByteArrayOutputStream baos = new ByteArrayOutputStream();
- File inputFile = File.createTempFile("xemelios-data-", ".html", FileUtils.getTempDir());
- FileOutputStream fos = new FileOutputStream(inputFile);
+ final Document doc = impl.getDocumentAsDom(em, new Pair(ctx.getCollectivite(), null), new Pair(ctx.getBudget(), null), docId, this.user);
+
+ final File xslFile = Xslt.getFile(dm, em, elm, doc);
+ final TransformerFactory tFactory = FactoryProvider.getTransformerFactory();
+ final AbstractURIResolver uriResolver = dm.createUriResolver();
+ AbstractURIResolver.initializationHelper(uriResolver, doc, tFactory.getURIResolver(), xslFile.getParentFile().toURI().toURL().toExternalForm());
+
+ tFactory.setURIResolver(uriResolver);
+
+ final Transformer t = tFactory.newTransformer(new StreamSource(xslFile));
+ for (final String key : additionalParameters.keySet()) {
+ final String paramValue = additionalParameters.get(key);
+ t.setParameter(key, paramValue);
+ XemeliosUserAgent.logger.debug("putting xsl param(" + key + "," + paramValue + ")");
+ }
+ t.setParameter("browser-destination", "internal");
+
+ // ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ final File inputFile = File.createTempFile("xemelios-data-", ".html", FileUtils.getTempDir());
+ final FileOutputStream fos = new FileOutputStream(inputFile);
t.transform(new DOMSource(doc), new StreamResult(fos));
fos.flush();
fos.close();
-
+
// Constitution du PDF
- File outputFile = File.createTempFile("xemelios-data-", ".pdf", FileUtils.getTempDir());
- String url = inputFile.toURI().toURL().toString();
- OutputStream os = new FileOutputStream(outputFile);
-
- File resourceDir = new File(MainWindow.getInstance().getEnvProperties().getProperty(Constants.SYS_PROP_RESOURCES_LOCATION));
- ITextRenderer renderer = new ITextRenderer();
- CustomUserAgentCallback callback = new CustomUserAgentCallback(renderer.getOutputDevice());
- callback.setSharedContext(renderer.getSharedContext());
- renderer.getSharedContext().setUserAgentCallback(callback);
- StyleReference css = new StyleReference(callback);
- renderer.getSharedContext().setCss(css);
- renderer.setDocument(url);
- callback.setBaseURL(resourceDir.toURI().toURL().toExternalForm());
- renderer.layout();
- renderer.createPDF(os);
- os.close();
-
+ final File outputFile = File.createTempFile("xemelios-data-", ".pdf", FileUtils.getTempDir());
+ final String url = inputFile.toURI().toURL().toString();
+ final OutputStream os = new FileOutputStream(outputFile);
+
+ final File resourceDir = new File(MainWindow.getInstance().getEnvProperties().getProperty(Constants.SYS_PROP_RESOURCES_LOCATION));
+ final ITextRenderer renderer = new ITextRenderer();
+ final CustomUserAgentCallback callback = new CustomUserAgentCallback(renderer.getOutputDevice());
+ callback.setSharedContext(renderer.getSharedContext());
+ renderer.getSharedContext().setUserAgentCallback(callback);
+ final StyleReference css = new StyleReference(callback);
+ renderer.getSharedContext().setCss(css);
+ renderer.setDocument(url);
+ callback.setBaseURL(resourceDir.toURI().toURL().toExternalForm());
+ renderer.layout();
+ renderer.createPDF(os);
+ os.close();
+
// Ouverture du PDF
- return new Dest(outputFile.toURI().toURL(), true);
-
- } catch (Exception e) {
- logger.error("Problème lors de l'ouverture PDF !", e);
+ return new Dest(outputFile.toURI().toURL(), true);
+
+ } catch (final Exception e) {
+ XemeliosUserAgent.logger.error("Problème lors de l'ouverture PDF !", e);
}
-
+
}
return null;
}
- public Dest generateDestContext(NavigationContext ctx, CustomLinkResolver resolver, CustomLinkParameters parameters, boolean toExternalDest) {
+ public Dest generateDestContext(NavigationContext ctx, final CustomLinkResolver resolver, final CustomLinkParameters parameters, final 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;
+ final File tmp = File.createTempFile("xemelios-data-", ".html", FileUtils.getTempDir());
+ ctx = resolver.resolve(parameters, new StreamResult(tmp), ctx, this.user);
+ final URL url = tmp.toURI().toURL();
+ this.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);
+ } catch (final UnresolvedException unEx) {
+ JOptionPane.showMessageDialog(this.viewer, unEx.getMessage(), "Erreur", JOptionPane.INFORMATION_MESSAGE);
+ } catch (final Exception ex) {
+ XemeliosUserAgent.logger.error("generateDestContext(NavigationContext,CustomLinkResolver,CustomLinkParameters,boolean)", ex);
}
return ret;
}
- public Dest generateDestContext(NavigationContext ctx, Hashtable<String, Object> params, final boolean toExternalDest) {
+ public Dest generateDestContext(final NavigationContext ctx, final 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());
+ final DocumentModel dm = Loader.getDocumentsInfos(null).getDocumentById(ctx.getDocId());
if (dm == null) {
throw new LocalException("doc " + ctx.getDocId() + " inconnu");
}
- EtatModel em = dm.getEtatById(ctx.getEtatId());
+ final 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());
+ final 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();
+ final 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);
+ final ArrayList<String> documents = impl.getDocumentListFromSpecialKeys(element, ctx.getCollectivite(), ctx.getBudget(), ctx.getSp1(), ctx.getSp2(), ctx.getSp3(), this.user);
if (documents.size() == 0) {
- JOptionPane.showMessageDialog(viewer, "Le document est introuvable", "", JOptionPane.WARNING_MESSAGE);
+ JOptionPane.showMessageDialog(this.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);
+ JOptionPane.showMessageDialog(this.viewer, "Plusieurs documents répondant à ces critères ont été trouvés.", "Erreur", JOptionPane.ERROR_MESSAGE);
noException = true;
} else {
docId = documents.get(0);
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);
+ final ArrayList<String> documents = impl.getDocumentListFromXPath(element, ctx.getCollectivite(), ctx.getBudget(), ctx.getSp1(), ctx.getSp2(), ctx.getSp3(), ctx.getPath(), this.user);
if (documents.size() == 0) {
- JOptionPane.showMessageDialog(viewer, "Le document est introuvable", "", JOptionPane.WARNING_MESSAGE);
+ JOptionPane.showMessageDialog(this.viewer, "Le document est introuvable", "", JOptionPane.WARNING_MESSAGE);
noException = true;
} else if (documents.size() > 1 && !em.isMultiPage()) {
String message = "Plusieurs documents répondant à ces critères ont été trouvés.";
// bordereau
// exemple de path =
// /n:PES_Aller/n:PES_DepenseAller/n:Bordereau[@added:primary-key='2011-01-1289']
- String[] cle = ctx.getPath().replaceAll("']", "").split("added:primary-key='")[1].split("-");
+ final String[] cle = ctx.getPath().replaceAll("']", "").split("added:primary-key='")[1].split("-");
if (cle.length == 3) {
message = message.concat("\n(le bordereau n° ").concat(cle[2]).concat(" de type ").concat(cle[1]).concat(" pour l'exercice ").concat(cle[0]).concat(" apparait plusieurs fois).");
}
} else if (params.get("mandatId") != null && !params.get("mandatId").equals("")) {
// piece
- String[] cle = ctx.getPath().replaceAll("']", "").split("added:primary-key='")[1].split("-");
+ final String[] cle = ctx.getPath().replaceAll("']", "").split("added:primary-key='")[1].split("-");
if (cle.length == 3) {
- message = message.concat("\n(la pièce n° ").concat(params.get("mandatId").toString()).concat(" du bordereau n° ").concat(cle[2]).concat(" de type ").concat(cle[1]).concat(" pour l'exercice ").concat(cle[0])
- .concat(" apparait plusieurs fois).");
+ message = message.concat("\n(la pièce n° ").concat(params.get("mandatId").toString()).concat(" du bordereau n° ").concat(cle[2]).concat(" de type ").concat(cle[1]).concat(" pour l'exercice ").concat(cle[0]).concat(" apparait plusieurs fois).");
}
}
}
- JOptionPane.showMessageDialog(viewer, message, "Erreur", JOptionPane.ERROR_MESSAGE);
+ JOptionPane.showMessageDialog(this.viewer, message, "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 = Xslt.getFile(dm, em, element, doc);
+ final Document doc = impl.getDocumentAsDom(em, new Pair(ctx.getCollectivite(), null), new Pair(ctx.getBudget(), null), docId, this.user);
+ final File f = Xslt.getFile(dm, em, element, doc);
// 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());
+ final 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));
+ final TransformerFactory tFactory = FactoryProvider.getTransformerFactory();
+ final AbstractURIResolver uriResolver = dm.createUriResolver();
+ AbstractURIResolver.initializationHelper(uriResolver, doc, tFactory.getURIResolver(), f.getParentFile().toURI().toURL().toExternalForm());
+
+ tFactory.setURIResolver(uriResolver);
+
+ final 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()) {
+ for (final 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();
+ final XPath xp = this.xpf.newXPath();
xp.setNamespaceContext(dm.getNamespaces());
String idRepository = null;
if (dm.getReferenceNomenclaturePath() != null && dm.getReferenceNomenclaturePath().getCodePath() != null) {
if (idRepository != null && idRepository.length() == 0) {
idRepository = null;
}
- Document repository = impl.getRepositoryAsDom(dm, new Pair(ctx.getCollectivite(), null), idRepository, user);
+ final Document repository = impl.getRepositoryAsDom(dm, new Pair(ctx.getCollectivite(), null), idRepository, this.user);
if (repository != null) {
t.setParameter("repository", repository);
}
t.setParameter("config", Loader.getDocumentsInfos(null).getSmallDOM());
t.setParameter("collectivite", ctx.getCollectivite());
t.setParameter("budget", ctx.getBudget());
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ final 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);
-// if (doPDF) {
-// ITextRenderer renderer = null;
-// renderer = new ITextRenderer();
-// renderer.setDocument(f);
-// renderer.layout();
-// renderer.createPDF(baos);
-// renderer.finishPDF();
-// baos.flush();
-// baos.close();
-// nc = ctx;
-// return new Dest(tmp.toURI().toURL(), true);
-// } else {
- 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);
-// }
+ final ByteArrayInputStream htmlStream = new ByteArrayInputStream(baos.toByteArray());
+ final File tmp = File.createTempFile("xemelios-data-", ".html", FileUtils.getTempDir());
+ final BufferedInputStream bis = new BufferedInputStream(htmlStream);
+ // if (doPDF) {
+ // ITextRenderer renderer = null;
+ // renderer = new ITextRenderer();
+ // renderer.setDocument(f);
+ // renderer.layout();
+ // renderer.createPDF(baos);
+ // renderer.finishPDF();
+ // baos.flush();
+ // baos.close();
+ // nc = ctx;
+ // return new Dest(tmp.toURI().toURL(), true);
+ // } else {
+ final BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmp));
+ final 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();
+ final URL url = tmp.toURI().toURL();
+ this.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;
+ } catch (final LocalException lEx) {
+ JOptionPane.showMessageDialog(this.viewer, lEx.getMessage(), "Erreur de paramétrage", JOptionPane.ERROR_MESSAGE);
+ } catch (final Exception ex) {
+ Component comp2 = this.viewer;
while (comp2 != null && !(comp2 instanceof JFrame)) {
comp2 = comp2.getParent();
}
}
return ret;
}
-
public Component getViewer() {
- return viewer;
+ return this.viewer;
}
- public void setToolbar(UpdatableToolbar toolbar) {
+ public void setToolbar(final UpdatableToolbar toolbar) {
this.toolbar = toolbar;
}
+ private class CustomUserAgentCallback extends ITextUserAgent {
+ private static final String IMG_BLANK = "1x1blank.gif";
+
+ public CustomUserAgentCallback(final ITextOutputDevice outputDevice) {
+ super(outputDevice);
+ }
+
+ @Override
+ protected InputStream resolveAndOpenStream(final String uri) {
+ InputStream is = null;
+ final StringBuilder errors = new StringBuilder();
+ try {
+ /* if (uri.matches("^file:/.*" + Pattern.quote(XHTML_TMP_FILE_PREFIX) + ".*")) { */
+ XemeliosUserAgent.logger.debug("**uri**=" + uri);
+ final URL url = new URL(uri);
+ is = url.openStream();
+ /*
+ * } else { String path = compactPath(getBaseURL() + "/" + uri); is = archive.getInputStream(path); }
+ */
+ } catch (final MalformedURLException e) {
+ XemeliosUserAgent.logger.error("An error has occured : The URL '" + uri + "' is not a well formed URL");
+ throw new RuntimeException(e);
+ } catch (final IOException e) {
+ throw new RuntimeException(e);
+ }
+ return is;
+ }
+
+ @Override
+ public CSSResource getCSSResource(final String uri) {
+ return new CSSResource(this.resolveAndOpenStream(uri));
+ }
+
+ @Override
+ public String resolveURI(final String uri) {
+ return uri;
+ }
+
+ @Override
+ public boolean isVisited(final String uri) {
+ boolean retValue;
+ retValue = super.isVisited(uri);
+ return retValue;
+ }
- private class CustomUserAgentCallback extends ITextUserAgent {
- private static final String IMG_BLANK = "1x1blank.gif";
-
- public CustomUserAgentCallback(ITextOutputDevice outputDevice) {
- super(outputDevice);
- }
-
- @Override
- protected InputStream resolveAndOpenStream(String uri) {
- InputStream is = null;
- StringBuilder errors = new StringBuilder();
- try {
- /*if (uri.matches("^file:/.*" + Pattern.quote(XHTML_TMP_FILE_PREFIX) + ".*")) {*/
- logger.debug("**uri**=" + uri);
- URL url = new URL(uri);
- is = url.openStream();
- /*} else {
- String path = compactPath(getBaseURL() + "/" + uri);
- is = archive.getInputStream(path);
- }*/
- } catch (MalformedURLException e) {
- logger.error("An error has occured : The URL '" + uri + "' is not a well formed URL");
- throw new RuntimeException(e);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- return is;
- }
-
- @Override
- public CSSResource getCSSResource(String uri) {
- return new CSSResource(resolveAndOpenStream(uri));
- }
-
- @Override
- public String resolveURI(String uri) {
- return uri;
- }
-
- @Override
- public boolean isVisited(String uri) {
- boolean retValue;
- retValue = super.isVisited(uri);
- return retValue;
- }
-
- @Override
- public ImageResource getImageResource(String uri) {
- ImageResource retValue;
- try {
- //logger.debug("uri before="+uri);
- if(uri.contains("xemelios:/resource?")){
- uri = new StringBuilder(getBaseURL()).append("/").append(uri.split("[?]")[1]).toString();
- } else {
- uri = new StringBuilder(getBaseURL()).append("/").append(IMG_BLANK).toString();
- }
- //logger.debug("uri after="+uri);
- } catch (Exception e) {
- logger.debug("Image vide non trouvée !");
- }
-
- retValue = super.getImageResource(uri);
- return retValue;
- }
-
- @Override
- public XMLResource getXMLResource(String uri) {
- XMLResource retValue;
- retValue = super.getXMLResource(uri);
- return retValue;
- }
-
- @Override
- public void setBaseURL(String url) {
- if (url.equals(new File(System.getProperty("java.io.tmpdir")).toURI().toString())) {
- return;
- }
- String s = url;
- String[] items = s.split("/");
- StringBuilder sb = new StringBuilder();
- for (String item : items) {
- if (!item.endsWith("xhtml")) {
- sb.append(item).append("/");
- }
- }
- sb.deleteCharAt(sb.length() - 1);
- super.setBaseURL(sb.toString());
- }
-
- @Override
- public String getBaseURL() {
- String retValue;
- retValue = super.getBaseURL();
- return retValue;
- }
- }
+ @Override
+ public ImageResource getImageResource(String uri) {
+ ImageResource retValue;
+ try {
+ // logger.debug("uri before="+uri);
+ if (uri.contains("xemelios:/resource?")) {
+ uri = new StringBuilder(this.getBaseURL()).append("/").append(uri.split("[?]")[1]).toString();
+ } else {
+ uri = new StringBuilder(this.getBaseURL()).append("/").append(CustomUserAgentCallback.IMG_BLANK).toString();
+ }
+ // logger.debug("uri after="+uri);
+ } catch (final Exception e) {
+ XemeliosUserAgent.logger.debug("Image vide non trouvée !");
+ }
+
+ retValue = super.getImageResource(uri);
+ return retValue;
+ }
+
+ @Override
+ public XMLResource getXMLResource(final String uri) {
+ XMLResource retValue;
+ retValue = super.getXMLResource(uri);
+ return retValue;
+ }
+
+ @Override
+ public void setBaseURL(final String url) {
+ if (url.equals(new File(System.getProperty("java.io.tmpdir")).toURI().toString())) {
+ return;
+ }
+ final String s = url;
+ final String[] items = s.split("/");
+ final StringBuilder sb = new StringBuilder();
+ for (final String item : items) {
+ if (!item.endsWith("xhtml")) {
+ sb.append(item).append("/");
+ }
+ }
+ sb.deleteCharAt(sb.length() - 1);
+ super.setBaseURL(sb.toString());
+ }
+
+ @Override
+ public String getBaseURL() {
+ String retValue;
+ retValue = super.getBaseURL();
+ return retValue;
+ }
+ }
}
*/
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.Color;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.Graphics;
import java.awt.Graphics2D;
+import java.awt.Point;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseMotionAdapter;
+import java.awt.geom.Rectangle2D;
+import java.io.File;
import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import org.apache.log4j.Logger;
-
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-
import org.xhtmlrenderer.css.style.derived.RectPropertySet;
import org.xhtmlrenderer.event.DocumentListener;
import org.xhtmlrenderer.extend.UserAgentCallback;
import org.xhtmlrenderer.swing.FSMouseListener;
import org.xhtmlrenderer.swing.ScalableXHTMLPanel;
-
-import java.awt.Point;
-import java.awt.event.MouseEvent;
-import java.awt.event.MouseMotionAdapter;
-import java.awt.geom.Rectangle2D;
-
-import java.io.File;
-import java.io.InputStream;
-import java.net.MalformedURLException;
-import java.net.URL;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
/**
- *
+ *
* @author chm
*/
public class XemeliosXhtmlPanel extends ScalableXHTMLPanel {
- private static final Logger logger = Logger.getLogger(XemeliosXhtmlPanel.class);
- private static final int TOOLTIP_BORDER_X = 5;
- private static final int TOOLTIP_BORDER_Y = 5;
- private static final int TOOLTIP_BORDER_MARG_X = 6;
- private static final int TOOLTIP_BORDER_MARG_Y = 6;
- private static final int TOOLTIP_X = 9;
- private static final int TOOLTIP_Y = 10;
- private JInternalFrame iframe;
- private JFrame frame;
- private String toolTip;
+ private static final Logger logger = Logger.getLogger(XemeliosXhtmlPanel.class);
+ private static final int TOOLTIP_BORDER_X = 5;
+ private static final int TOOLTIP_BORDER_Y = 5;
+ private static final int TOOLTIP_BORDER_MARG_X = 6;
+ private static final int TOOLTIP_BORDER_MARG_Y = 6;
+ private static final int TOOLTIP_X = 9;
+ private static final int TOOLTIP_Y = 10;
+ private JInternalFrame iframe;
+ private JFrame frame;
+ private String toolTip;
private Point mousePosition;
private Font toolTipFont;
+ public XemeliosXhtmlPanel(final UserAgentCallback uac, final JInternalFrame frame) {
+ super(uac);
+ this.iframe = frame;
+ this.addListeners();
+ this.addMonospacedFont();
+ }
+
+ public XemeliosXhtmlPanel(final UserAgentCallback uac, final JFrame frame) {
+ super(uac);
+ this.frame = frame;
+ this.addListeners();
+ this.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(final String filename) {
+ final String url = this.getSharedContext().getUac().resolveURI(filename);
+ if (url != null) {
+ if (this.isAnchorInCurrentDocument(filename)) {
+ final String id = this.getAnchorId(filename);
+ final Box box = this.getSharedContext().getBoxById(id);
+ if (box != null) {
+ Point pt;
+ if (box.getStyle().isInline()) {
+ pt = new Point(box.getAbsX(), box.getAbsY());
+ } else {
+ final RectPropertySet margin = box.getMargin(this.getLayoutContext());
+ pt = new Point(box.getAbsX() + (int) margin.left(), box.getAbsY() + (int) margin.top());
+ }
+ this.scrollTo(pt);
+ return;
+ }
+ }
+ final Document dom = this.loadDocument(url);
+ this.setDocument(dom, url);
+ }
+ }
+
+ private boolean isAnchorInCurrentDocument(final String str) {
+ return str.charAt(0) == '#';
+ }
+
+ private String getAnchorId(final String url) {
+ return url.substring(1, url.length());
+ }
- public XemeliosXhtmlPanel(UserAgentCallback uac, JInternalFrame frame) {
- super(uac);
- this.iframe=frame;
- addListeners();
- addMonospacedFont();
- }
- public XemeliosXhtmlPanel(UserAgentCallback uac, JFrame frame) {
- super(uac);
- this.frame=frame;
- addListeners();
- 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 String getTitle(Box b){
- Element element = b.getElement();
- String title = null;
- if (element!=null){
- if (element.getAttribute("title")!=null && !element.getAttribute("title").equals("")) {
+ private void addMonospacedFont() {
+ try {
+ if (MainWindow.instance != null && !MainWindow.instance.getEnvProperties().replace("${" + Constants.SYS_PROP_RESOURCES_LOCATION + "}").equals("${" + Constants.SYS_PROP_RESOURCES_LOCATION + "}")) {
+ final Font font = Font.createFont(Font.TRUETYPE_FONT, new File(new File(MainWindow.instance.getEnvProperties().replace("${" + Constants.SYS_PROP_RESOURCES_LOCATION + "}")), "couri.ttf"));
+ this.getSharedContext().setFontMapping("monospace", font);
+ }
+ } catch (final FontFormatException ex) {
+ logger.error(ex);
+ } catch (final IOException ex) {
+ logger.error(ex);
+ } catch (final NullPointerException npEx) {
+ logger.error(npEx);
+ }
+ }
+
+ private String getTitle(final Box b) {
+ final Element element = b.getElement();
+ String title = null;
+ if (element != null) {
+ if (element.getAttribute("title") != null && !element.getAttribute("title").equals("")) {
title = element.getAttribute("title");
- }
- else if (b.getParent()!=null) {
- return getTitle(b.getParent());
- }
- }
+ } else if (b.getParent() != null) {
+ return this.getTitle(b.getParent());
+ }
+ }
return title;
- }
-
- @Override
- public void paint(Graphics g) {
+ }
+
+ @Override
+ public void paint(final Graphics g) {
super.paint(g);
- if (toolTip != null) {
- Graphics2D g2 = (Graphics2D)g;
- toolTipFont = new Font("Arial", Font.PLAIN, 13);
- g2.setFont(toolTipFont);
- Rectangle2D text_border = g2.getFontMetrics().getStringBounds(toolTip, g2);
- Rectangle2D.Double box = new Rectangle2D.Double(mousePosition.getX() + TOOLTIP_BORDER_X,
- mousePosition.getY() - text_border.getHeight() - TOOLTIP_BORDER_MARG_Y - TOOLTIP_BORDER_Y,
- text_border.getWidth() + TOOLTIP_BORDER_MARG_X,
- text_border.getHeight() + TOOLTIP_BORDER_MARG_Y);
-
- g2.setColor(new Color(233, 233, 233));
- g2.fill(box);
- g2.setColor(Color.black);
- g2.draw(box);
- g2.drawString(toolTip, (int)mousePosition.getX() + TOOLTIP_X, (int)mousePosition.getY() - TOOLTIP_Y);
-
+ if (this.toolTip != null) {
+ final Graphics2D g2 = (Graphics2D) g;
+ this.toolTipFont = new Font("Arial", Font.PLAIN, 13);
+ g2.setFont(this.toolTipFont);
+ final Rectangle2D text_border = g2.getFontMetrics().getStringBounds(this.toolTip, g2);
+ final Rectangle2D.Double box = new Rectangle2D.Double(this.mousePosition.getX() + TOOLTIP_BORDER_X, this.mousePosition.getY() - text_border.getHeight() - TOOLTIP_BORDER_MARG_Y - TOOLTIP_BORDER_Y, text_border.getWidth() + TOOLTIP_BORDER_MARG_X, text_border.getHeight()
+ + TOOLTIP_BORDER_MARG_Y);
+
+ g2.setColor(new Color(233, 233, 233));
+ g2.fill(box);
+ g2.setColor(Color.black);
+ g2.draw(box);
+ g2.drawString(this.toolTip, (int) this.mousePosition.getX() + TOOLTIP_X, (int) this.mousePosition.getY() - TOOLTIP_Y);
+
}
}
-
- private void addListeners() {
- addMouseMotionListener(new MouseMotionAdapter() {
+
+ private void addListeners() {
+ this.addMouseMotionListener(new MouseMotionAdapter() {
@Override
- public void mouseMoved(MouseEvent e) {
- mousePosition = e.getPoint();
- if (toolTip != null) {
- repaint();
+ public void mouseMoved(final MouseEvent e) {
+ XemeliosXhtmlPanel.this.mousePosition = e.getPoint();
+ if (XemeliosXhtmlPanel.this.toolTip != null) {
+ XemeliosXhtmlPanel.this.repaint();
}
super.mouseMoved(e);
});
- addMouseTrackingListener(new FSMouseListener() {
+ this.addMouseTrackingListener(new FSMouseListener() {
@Override
- public void onMouseOver(BasicPanel arg0, Box b) {
- if (getTitle(b) != null) {
- toolTip = getTitle(b);
- }
+ public void onMouseOver(final BasicPanel arg0, final Box b) {
+ if (XemeliosXhtmlPanel.this.getTitle(b) != null) {
+ XemeliosXhtmlPanel.this.toolTip = XemeliosXhtmlPanel.this.getTitle(b);
+ }
}
-
@Override
- public void onMouseOut(BasicPanel arg0, Box arg1) {
- toolTip = null;
- repaint();
+ public void onMouseOut(final BasicPanel arg0, final Box arg1) {
+ XemeliosXhtmlPanel.this.toolTip = null;
+ XemeliosXhtmlPanel.this.repaint();
}
+ @Override
+ public void onMouseDragged(final BasicPanel arg0, final MouseEvent arg1) {
+ // TODO Auto-generated method stub
+
+ }
@Override
- public void onMouseDragged(BasicPanel arg0, MouseEvent arg1) {
+ public void onMousePressed(final BasicPanel arg0, final MouseEvent arg1) {
// TODO Auto-generated method stub
-
+
}
+ @Override
+ public void onMouseUp(final BasicPanel arg0, final Box arg1) {
+ // TODO Auto-generated method stub
+
+ }
@Override
- public void onMousePressed(BasicPanel arg0, MouseEvent arg1) {
+ public void reset() {
// TODO Auto-generated method stub
-
+
}
+ });
+ this.addDocumentListener(new DocumentListener() {
@Override
- public void onMouseUp(BasicPanel arg0, Box arg1) {
- // TODO Auto-generated method stub
-
+ public void documentLoaded() {
+ final String sUrl = XemeliosXhtmlPanel.this.getSharedContext().getUac().getBaseURL();
+ try {
+ final URL __url = new URL(sUrl);
+ final String url = __url.toExternalForm();
+ final int sharpPos = url.indexOf('#');
+
+ if (sharpPos >= 0) {
+ final String anchorName = url.substring(sharpPos + 1);
+ final Box box = XemeliosXhtmlPanel.this.getSharedContext().getBoxById(anchorName);
+
+ if (box != null) {
+ Point pt;
+
+ if (box.getStyle().isInline()) {
+ pt = new Point(box.getAbsX(), box.getAbsY());
+ } else {
+ final RectPropertySet margin = box.getMargin(XemeliosXhtmlPanel.this.getLayoutContext());
+
+ pt = new Point(box.getAbsX() + (int) margin.left(), box.getAbsY() + (int) margin.top());
+ }
+
+ // TODO
+ final Point transPoint = new Point((int) (pt.getX() / XemeliosXhtmlPanel.this.getScale()), (int) (pt.getY() / XemeliosXhtmlPanel.this.getScale()));
+ // Point transPoint = new Point((int) (pt.getX()/ 1.0), (int) (pt.getY()/ 1.0));
+
+ XemeliosXhtmlPanel.this.scrollTo(transPoint);
+ XemeliosXhtmlPanel.this.repaint();
+
+ return;
+ } else {
+ logger.error("anchor not found: " + anchorName);
+ }
+ }
+ XemeliosXhtmlPanel.this.displayTitle(XemeliosXhtmlPanel.this.getDocumentTitle());
+ } catch (final MalformedURLException muEx) {
+ // ignorable
+ }
+
}
+ @Override
+ public void onLayoutException(final Throwable throwable) {
+ logger.error("layout error: ", throwable);
+ }
@Override
- public void reset() {
- // TODO Auto-generated method stub
-
+ public void onRenderException(final Throwable throwable) {
+ logger.error("render error: ", throwable);
}
+ @Override
+ public void documentStarted() {
+ }
});
-
- 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);
- }
-}
+ }
+
+ public JInternalFrame getFrame() {
+ return this.iframe;
+ }
+
+ protected void displayTitle(final String title) {
+ if (title != null) {
+ if (this.frame != null) {
+ this.frame.setTitle(title);
+ }
+ if (this.iframe != null) {
+ this.iframe.setTitle(title);
+ }
+ }
+ }
+
+ // ~--- set methods --------------------------------------------------------
+
+ @Override
+ public void setDocument(final File file) throws Exception {
+ this.setScalePolicy(SCALE_POLICY_FIT_WIDTH);
+ super.setDocument(file);
+ }
+
+ @Override
+ public void setDocument(final Document doc, final String url) {
+ this.setScalePolicy(SCALE_POLICY_FIT_WIDTH);
+ super.setDocument(doc, url);
+ }
+
+ @Override
+ public void setDocument(final InputStream stream, final String url) throws Exception {
+ this.setScalePolicy(SCALE_POLICY_FIT_WIDTH);
+ super.setDocument(stream, url);
+ }
+}
/**
* This class is the parent of all configurator started after an update.
+ *
* @author chm
- *
+ *
*/
public abstract class AbstractConfigurator {
protected PropertiesExpansion props;
public AbstractConfigurator() {
super();
}
+
/**
* Called by updater to set parameters.
+ *
* @param props
*/
- public void setProperties(PropertiesExpansion props) {
- this.props=props;
+ public void setProperties(final 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 setMainWindow(final MainWindow mw) {
+ this.mw = mw;
}
- public void setPreviousConfigurator(AbstractConfigurator prev) {
- if(prev==null) return;
+
+ public void setPreviousConfigurator(final AbstractConfigurator prev) {
+ if (prev == null) {
+ return;
+ }
this.previousConfigurator = prev;
- prev.setMainWindow(mw);
- prev.setProperties(props);
+ prev.setMainWindow(this.mw);
+ prev.setProperties(this.props);
}
+
public void doConfigure() throws Exception {
- run();
- if(previousConfigurator!=null) previousConfigurator.doConfigure();
+ this.run();
+ if (this.previousConfigurator != null) {
+ this.previousConfigurator.doConfigure();
+ }
}
+
/**
- * Called by updater to perform configuration.
- * Implementors just have to implement this method.
+ * Called by updater to perform configuration. Implementors just have to implement this method.
+ *
* @throws Exception
*/
public abstract void run() throws Exception;
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;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+import fr.gouv.finances.dgfip.xemelios.common.Constants;
+
/**
- *
+ *
* @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
+ public static final transient String MSG = "<html>Des mises à jour sont disponibles.<br><br>Voulez-vous les installer ?</html>";
+ private final UpdateUtil uu;
+ private int retValue = JOptionPane.NO_OPTION;
+
+ /** Creates new form DlgConfirmDownloadUpdate */
+ public DlgConfirmDownloadUpdate(final java.awt.Frame parent, final UpdateUtil uu) {
+ super(parent, true);
+ this.uu = uu;
+ this.initComponents();
+ this.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() {
+
+ this.jLabel1 = new javax.swing.JLabel();
+ this.jSeparator1 = new javax.swing.JSeparator();
+ this.pbYes = new javax.swing.JButton();
+ this.pbNo = new javax.swing.JButton();
+ this.pbDetail = new javax.swing.JButton();
+
+ this.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+ this.setTitle("Mises à jour");
+
+ this.jLabel1.setText(MSG);
+
+ this.pbYes.setText("Oui");
+ this.pbYes.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgConfirmDownloadUpdate.this.pbYesActionPerformed(evt);
+ }
+ });
+
+ this.pbNo.setText("Non");
+ this.pbNo.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgConfirmDownloadUpdate.this.pbNoActionPerformed(evt);
+ }
+ });
+
+ this.pbDetail.setText("Voir le détail...");
+ this.pbDetail.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgConfirmDownloadUpdate.this.pbDetailActionPerformed(evt);
+ }
+ });
+
+ final javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this.getContentPane());
+ this.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(this.jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE))
+ .addComponent(this.jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 388, Short.MAX_VALUE).addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addContainerGap(291, Short.MAX_VALUE).addComponent(this.pbDetail)))
+ .addContainerGap())
+ .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addContainerGap(173, Short.MAX_VALUE).addComponent(this.pbYes).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(this.pbNo).addGap(162, 162, 162)));
+ layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
+ layout.createSequentialGroup().addContainerGap().addComponent(this.jLabel1).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE).addComponent(this.pbDetail).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(this.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(this.pbYes).addComponent(this.pbNo)).addContainerGap()));
+
+ this.pack();
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void pbYesActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbYesActionPerformed
+ this.retValue = JOptionPane.YES_OPTION;
+ this.setVisible(false);
+ }// GEN-LAST:event_pbYesActionPerformed
+
+ private void pbNoActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbNoActionPerformed
+ this.retValue = JOptionPane.NO_OPTION;
+ this.setVisible(false);
+ }// GEN-LAST:event_pbNoActionPerformed
+
+ private void pbDetailActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbDetailActionPerformed
+ final String source = MainWindow.getInstance().getEnvProperties().getProperty(Constants.SYS_PROP_MAJ_CONFIG);
+ final DlgShowUpdateDetail dsud = new DlgShowUpdateDetail(this, this.uu, source);
+ dsud.setVisible(true);
+ }// GEN-LAST:event_pbDetailActionPerformed
+
+ public int run() {
+ this.setVisible(true);
+ return this.retValue;
+ }
+
+ @Override
+ protected JRootPane createRootPane() {
+ final JRootPane rp = new JRootPane();
+ final KeyStroke ksEscape = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
+ final AbstractAction escapeAction = new AbstractAction("Non") {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ DlgConfirmDownloadUpdate.this.pbNo.doClick();
+ }
+ };
+ rp.registerKeyboardAction(escapeAction, "CANCEL", ksEscape, JComponent.WHEN_IN_FOCUSED_WINDOW);
+ final KeyStroke ksEnter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
+ final AbstractAction enterAction = new AbstractAction("Oui") {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ DlgConfirmDownloadUpdate.this.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
}
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.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.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;
+import fr.gouv.finances.cp.utils.StartUrl;
+import fr.gouv.finances.cp.xemelios.updater.profils.ComponentModel;
+
/**
- *
+ *
* @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;
- }
-
- }
+ public static final transient String VERSION_NOTE_LIB = "Notes de version";
+ private static final Logger logger = Logger.getLogger(DlgShowUpdateDetail.class);
+ private final String updateSource;
+ private final DownloadModel downloadModel;
+ private final UpdateModel updateModel;
+ private final TreeSet<String> visitedUrls = new TreeSet<String>();
+
+ /** Creates new form DlgShowUpdateDetail */
+ public DlgShowUpdateDetail(final JDialog parent, final UpdateUtil uu, final String updateSource) {
+ super(parent, true);
+ this.updateSource = updateSource;
+ // download table
+ final ArrayList<ComponentModel> downloadList = new ArrayList<ComponentModel>();
+ for (final ComponentModel cm : uu.getComponentsToAdd()) {
+ if (!uu.getComponentsToBeUpdated().contains(cm)) {
+ downloadList.add(cm);
+ }
+ }
+ this.downloadModel = new DownloadModel(downloadList);
+ // update table
+ final ArrayList<ComponentModel> updateList = new ArrayList<ComponentModel>();
+ updateList.addAll(uu.getComponentsToBeUpdated());
+ this.updateModel = new UpdateModel(updateList);
+ this.initComponents();
+ this.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() {
+
+ this.pbClose = new javax.swing.JButton();
+ this.jLabel1 = new javax.swing.JLabel();
+ this.jScrollPane1 = new javax.swing.JScrollPane();
+ this.tblCompsToDownload = new MyTable();
+ this.jLabel2 = new javax.swing.JLabel();
+ this.jScrollPane2 = new javax.swing.JScrollPane();
+ this.tblCompsToUpdate = new MyTable();
+
+ this.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+
+ this.pbClose.setText("Fermer");
+ this.pbClose.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgShowUpdateDetail.this.pbCloseActionPerformed(evt);
+ }
+ });
+
+ this.jLabel1.setText("Composants à installer");
+
+ this.tblCompsToDownload.setModel(this.downloadModel);
+ this.jScrollPane1.setViewportView(this.tblCompsToDownload);
+
+ this.jLabel2.setText("Composants à mettre à jour");
+
+ this.tblCompsToUpdate.setModel(this.updateModel);
+ this.jScrollPane2.setViewportView(this.tblCompsToUpdate);
+
+ final javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this.getContentPane());
+ this.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(this.jLabel1).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 429, Short.MAX_VALUE))
+ .addComponent(this.jLabel2).addComponent(this.jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 576, Short.MAX_VALUE).addComponent(this.jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 576, Short.MAX_VALUE))
+ .addGap(11, 11, 11)).addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addComponent(this.pbClose).addContainerGap()))));
+ layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
+ layout.createSequentialGroup().addContainerGap().addComponent(this.jLabel1).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(this.jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE).addGap(3, 3, 3)
+ .addComponent(this.jLabel2).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(this.jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 102, Short.MAX_VALUE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(this.pbClose).addContainerGap()));
+
+ this.pack();
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void pbCloseActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbCloseActionPerformed
+ this.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 final List<ComponentModel> comps;
+
+ public DownloadModel(final List<ComponentModel> comps) {
+ super();
+ this.comps = comps;
+ }
+
+ @Override
+ public int getRowCount() {
+ if (this.comps == null) {
+ return 0;
+ }
+ return this.comps.size();
+ }
+
+ @Override
+ public int getColumnCount() {
+ return 2;
+ }
+
+ @Override
+ public String getColumnName(final int column) {
+ switch (column) {
+ case 0:
+ return "Composant";
+ default:
+ return "Informations";
+ }
+ }
+
+ @Override
+ public Object getValueAt(final int row, final int column) {
+ final ComponentModel cm = this.comps.get(row);
+ switch (column) {
+ case 0:
+ return cm.getDescription();
+ default: {
+ try {
+ return new URL(cm.getUri() + "/" + DlgShowUpdateDetail.this.updateSource + "/update.xml");
+ } catch (final Exception ex) {
+ return null;
+ }
+ }
+ }
+ }
+
+ @Override
+ public Class<?> getColumnClass(final int columnIndex) {
+ switch (columnIndex) {
+ case 0:
+ return String.class;
+ default:
+ return URL.class;
+ }
+ }
+
+ @Override
+ public boolean isCellEditable(final int row, final int column) {
+ return column == 1;
+ }
+
+ @Override
+ public void setValueAt(final Object aValue, final int row, final int column) {
+ }
+
+ }
+
+ private class UpdateModel extends AbstractTableModel {
+ private final List<ComponentModel> comps;
+
+ public UpdateModel(final List<ComponentModel> comps) {
+ super();
+ this.comps = comps;
+ }
+
+ @Override
+ public int getRowCount() {
+ return this.comps.size();
+ }
+
+ @Override
+ public int getColumnCount() {
+ return 3;
+ }
+
+ @Override
+ public String getColumnName(final int column) {
+ switch (column) {
+ case 0:
+ return "Composant";
+ case 1:
+ return "Version";
+ default:
+ return "Informations";
+ }
+ }
+
+ @Override
+ public Class<?> getColumnClass(final int columnIndex) {
+ switch (columnIndex) {
+ case 2:
+ return URL.class;
+ default:
+ return String.class;
+ }
+ }
+
+ @Override
+ public Object getValueAt(final int row, final int column) {
+ final ComponentModel cm = this.comps.get(row);
+ switch (column) {
+ case 0:
+ return cm.getDescription();
+ case 1:
+ return cm.getVersion();
+ default:
+ try {
+ return new URL(cm.getUri() + "/" + DlgShowUpdateDetail.this.updateSource + "/update.xml");
+ } catch (final Exception ex) {
+ return null;
+ }
+ }
+ }
+
+ @Override
+ public boolean isCellEditable(final int row, final int column) {
+ return column == 2;
+ }
+
+ @Override
+ public void setValueAt(final Object aValue, final int row, final int column) {
+ }
+
+ }
+
+ @Override
+ protected JRootPane createRootPane() {
+ final JRootPane rp = new JRootPane();
+ final KeyStroke ksEscape = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
+ final AbstractAction escapeAction = new AbstractAction("Fermer") {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ DlgShowUpdateDetail.this.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();
+ this.setDefaultEditor(URL.class, this.urlEditor);
+ }
+
+ @Override
+ public TableCellRenderer getCellRenderer(final int row, final int column) {
+ final TableModel tm = this.getModel();
+ final Class clazz = tm.getColumnClass(this.convertColumnIndexToModel(column));
+ if (String.class.equals(clazz)) {
+ return super.getCellRenderer(row, column);
+ } else {
+ return this.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 final ReleaseNoteHL hl = new ReleaseNoteHL();
+
+ @Override
+ public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) {
+ this.hl.setURL((URL) value);
+ this.hl.setBackground(isSelected || hasFocus ? table.getSelectionBackground() : table.getBackground());
+ return this.hl;
+ }
+
+ }
+
+ private class ReleaseNoteHL extends JXHyperlink {
+ private URL url;
+ private String externalForm;
+
+ public ReleaseNoteHL() {
+ super();
+ this.setText(VERSION_NOTE_LIB);
+ this.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ try {
+ DlgShowUpdateDetail.this.visitedUrls.add(ReleaseNoteHL.this.externalForm);
+ StartUrl.startUrl(ReleaseNoteHL.this.externalForm);
+ } catch (final Exception ex) {
+ logger.error("starting " + ReleaseNoteHL.this.url, ex);
+ }
+ }
+ });
+ }
+
+ public ReleaseNoteHL(final Action act) {
+ super(act);
+ }
+
+ protected void setURL(final URL url) {
+ this.url = url;
+ this.externalForm = url != null ? url.toExternalForm() : null;
+ }
+
+ @Override
+ protected boolean isAutoSetClicked() {
+ return true;
+ }
+
+ @Override
+ public boolean isClicked() {
+ final boolean ret = this.externalForm == null ? false : DlgShowUpdateDetail.this.visitedUrls.contains(this.externalForm);
+ // logger.debug(externalForm+(ret?" visited":" not visited"));
+ return ret;
+ }
+
+ }
+
+ private class UrlCellEditor extends DefaultCellEditor {
+ private final ReleaseNoteHL hl;
+
+ public UrlCellEditor() {
+ super(new JTextField());
+ final AbstractAction action = new AbstractAction(VERSION_NOTE_LIB) {
+ @Override
+ public void actionPerformed(final ActionEvent e) {
+ UrlCellEditor.this.fireEditingStopped();
+ try {
+ StartUrl.startUrl(UrlCellEditor.this.hl.url.toExternalForm());
+ } catch (final Exception ex) {
+ logger.error("while opening " + UrlCellEditor.this.hl.url, ex);
+ }
+ }
+ };
+ this.hl = new ReleaseNoteHL(action);
+ }
+
+ @Override
+ public Component getTableCellEditorComponent(final JTable table, final Object value, final boolean isSelected, final int row, final int column) {
+ this.hl.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
+ this.hl.setURL((URL) value);
+ return this.hl;
+ }
+
+ }
}
*/
package fr.gouv.finances.cp.xemelios.updater;
-import fr.gouv.finances.cp.utils.PropertiesExpansion;
import java.util.HashMap;
import java.util.Vector;
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
import fr.gouv.finances.dgfip.xemelios.common.config.DocumentsModel;
/**
* Cette classe génère la page d'index de la liste des documetns disponibles dans l'aide utilisateur
+ *
* @author cmarchand
*/
public class GeneratorHelpIndex {
- public GeneratorHelpIndex() {
- super();
- }
+ public GeneratorHelpIndex() {
+ super();
+ }
- /**
- *
- * @return
- */
- public static String generateIndex(DocumentsModel documentsModel, PropertiesExpansion applicationProperties) {
- StringBuilder sb = new StringBuilder("");
- sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
- sb.append("<html><head><title>Guide utilisateur XéMéLios</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"></meta>");
- 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("html { background: #f4f5f0; }");
- 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 : documentsModel.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 : documentsModel.getDocuments()) {
- if (dm.getDisplayInMenuIf() == null || "true".equals(applicationProperties.getProperty(dm.getDisplayInMenuIf())) || "true".equals(applicationProperties.getProperty("xemelios.show.all.documents"))) {
- sb.append("<li type=\"square\"><a href=\"" + dm.getId() + ".html\">" + dm.getTitre() + "</a></li>");
- }
- }
- sb.append("</ul></p></body></html>");
- return sb.toString();
- }
+ /**
+ *
+ * @return
+ */
+ public static String generateIndex(final DocumentsModel documentsModel, final PropertiesExpansion applicationProperties) {
+ final StringBuilder sb = new StringBuilder("");
+ sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
+ sb.append("<html><head><title>Guide utilisateur XéMéLios</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"></meta>");
+ 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("html { background: #f4f5f0; }");
+ 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
+ final HashMap<String, Vector<String>> hashDocIds = new HashMap<String, Vector<String>>();
+ for (final DocumentModel dm : documentsModel.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 {
+ final Vector<String> v = new Vector<String>();
+ hashDocIds.put(dm.getId(), v);
+ }
+ }
+ for (final DocumentModel dm : documentsModel.getDocuments()) {
+ if (dm.getDisplayInMenuIf() == null || "true".equals(applicationProperties.getProperty(dm.getDisplayInMenuIf())) || "true".equals(applicationProperties.getProperty("xemelios.show.all.documents"))) {
+ sb.append("<li type=\"square\"><a href=\"" + dm.getId() + ".html\">" + dm.getTitre() + "</a></li>");
+ }
+ }
+ sb.append("</ul></p></body></html>");
+ return sb.toString();
+ }
}
*/
package fr.gouv.finances.cp.xemelios.updater;
-import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
-import fr.gouv.finances.cp.utils.ui.IhmFactory;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Paint;
import java.awt.Point;
import java.awt.Rectangle;
-import fr.gouv.finances.cp.xemelios.ui.MainWindow;
-import fr.gouv.finances.dgfip.xemelios.updater.UpdaterPropertyChangeListener;
import java.beans.PropertyChangeEvent;
import java.util.Timer;
import java.util.TimerTask;
+
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
+
import org.apache.log4j.Logger;
import org.jdesktop.swingx.JXPanel;
+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.updater.UpdaterPropertyChangeListener;
+
/**
- * 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>
+ * 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>
+ * <li><tt>close</tt> : pour indiquer la fin du téléchargement d'une mise à jour</li>
+ * </ul>
+ *
* @author cmarchand
*/
public class PnlUpdaterProgress extends JXPanel implements UpdaterPropertyChangeListener {
- private static final String INITIAL_LBL = "Recherche de mises à jour...";
- private static final String DWNLOAD_LBL = "Téléchargement en cours...";
-
- private static final transient Logger logger = Logger.getLogger(PnlUpdaterProgress.class);
- Icon[] waiters = new Icon[12];
- private Timer timer;
- private ProgressPainter currentPainter;
- private Paint painter = null;
- private MainWindow mainWindow;
-
- /** Creates new form PnlUpdaterProgress */
- public PnlUpdaterProgress(MainWindow mainWindow ) {
- this.mainWindow = mainWindow;
- initIcons();
- initComponents();
- pgr.setIndeterminate(true);
- pgr.setMaximum(100);
- setSize(220, 48);
- setBorder(BorderFactory.createEtchedBorder());
- painter = new GradientPaint(new Point(0,0), new Color(0xf7, 0xb2, 0x21), new Point(0,24), new Color(0xff, 0xd2, 0x72));
- }
-
- @Override
- protected void paintComponent(Graphics g) {
- super.paintComponent(g);
-
- if (painter != null) {
- Dimension d = getSize();
- Graphics2D g2 = (Graphics2D) g;
- g2.setPaint(painter);
- g2.fill(new Rectangle(0, 0, d.width, d.height));
- }
- }
-
- /** 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();
- lbl = new javax.swing.JLabel();
-
- setToolTipText("Téléchargement des mises à jour en cours...");
- setMaximumSize(new java.awt.Dimension(200, 48));
- setMinimumSize(new java.awt.Dimension(200, 48));
- setPreferredSize(new java.awt.Dimension(200, 48));
-
- 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);
-
- lbl.setForeground(new java.awt.Color(42, 71, 93));
- lbl.setText("Recherche de mises à jour...");
-
- javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
- this.setLayout(layout);
- layout.setHorizontalGroup(
- layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGroup(layout.createSequentialGroup()
- .addGap(3, 3, 3)
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGroup(layout.createSequentialGroup()
- .addComponent(lblWait)
- .addGap(1, 1, 1)
- .addComponent(pgr, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE))
- .addComponent(lbl, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE))
- .addGap(15, 15, 15))
- );
- layout.setVerticalGroup(
- layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
- .addComponent(lbl)
- .addGap(4, 4, 4)
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addComponent(lblWait, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
- .addComponent(pgr, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
- .addContainerGap())
- );
- }// </editor-fold>//GEN-END:initComponents
- // Variables declaration - do not modify//GEN-BEGIN:variables
- private javax.swing.JLabel lbl;
- 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 startHide() {
-// if(timer == null) {
-// timer = new Timer();
-// }
-// Hider hider = new Hider();
-// timer.schedule(hider, 0, 100);
-// }
-
- 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();
- lbl.setText(DWNLOAD_LBL);
- pgr.setIndeterminate(false);
- pgr.setValue(value);
- } else if (evt.getPropertyName().equals("init")) {
- lbl.setText(INITIAL_LBL);
- pgr.setValue(0);
- pgr.setIndeterminate(true);
- setVisible(true);
- } else if (evt.getPropertyName().equals("close")) {
- setVisible(false);
- }
- }
-
- @Override
- public void showMessage(String htmlMessage) {
- JOptionPane.showMessageDialog(mainWindow, htmlMessage, "Information", JOptionPane.INFORMATION_MESSAGE);
- }
-
- @Override
- public void displayException(Exception ex) {
- new DisplayExceptionDlg(mainWindow, ex);
- }
- // 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;
- }
- }
- }
+ private static final String INITIAL_LBL = "Recherche de mises à jour...";
+ private static final String DWNLOAD_LBL = "Téléchargement en cours...";
+
+ private static final transient Logger logger = Logger.getLogger(PnlUpdaterProgress.class);
+ Icon[] waiters = new Icon[12];
+ private Timer timer;
+ private ProgressPainter currentPainter;
+ private Paint painter = null;
+ private final MainWindow mainWindow;
+
+ /** Creates new form PnlUpdaterProgress */
+ public PnlUpdaterProgress(final MainWindow mainWindow) {
+ this.mainWindow = mainWindow;
+ this.initIcons();
+ this.initComponents();
+ this.pgr.setIndeterminate(true);
+ this.pgr.setMaximum(100);
+ this.setSize(220, 48);
+ this.setBorder(BorderFactory.createEtchedBorder());
+ this.painter = new GradientPaint(new Point(0, 0), new Color(0xf7, 0xb2, 0x21), new Point(0, 24), new Color(0xff, 0xd2, 0x72));
+ }
+
+ @Override
+ protected void paintComponent(final Graphics g) {
+ super.paintComponent(g);
+
+ if (this.painter != null) {
+ final Dimension d = this.getSize();
+ final Graphics2D g2 = (Graphics2D) g;
+ g2.setPaint(this.painter);
+ g2.fill(new Rectangle(0, 0, d.width, d.height));
+ }
+ }
+
+ /**
+ * 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() {
+
+ this.lblWait = new javax.swing.JLabel();
+ this.pgr = new javax.swing.JProgressBar();
+ this.lbl = new javax.swing.JLabel();
+
+ this.setToolTipText("Téléchargement des mises à jour en cours...");
+ this.setMaximumSize(new java.awt.Dimension(200, 48));
+ this.setMinimumSize(new java.awt.Dimension(200, 48));
+ this.setPreferredSize(new java.awt.Dimension(200, 48));
+
+ this.lblWait.setIcon(new javax.swing.ImageIcon(this.getClass().getResource("/fr/gouv/finances/cp/xemelios/updater/ui/res/wait-01.png"))); // NOI18N
+ this.lblWait.setToolTipText("Téléchargement des mises à jour en cours...");
+
+ this.pgr.setStringPainted(true);
+
+ this.lbl.setForeground(new java.awt.Color(42, 71, 93));
+ this.lbl.setText("Recherche de mises à jour...");
+
+ final javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
+ this.setLayout(layout);
+ layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
+ layout.createSequentialGroup()
+ .addGap(3, 3, 3)
+ .addGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addComponent(this.lblWait).addGap(1, 1, 1).addComponent(this.pgr, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addComponent(this.lbl, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)).addGap(15, 15, 15)));
+ layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
+ javax.swing.GroupLayout.Alignment.TRAILING,
+ layout.createSequentialGroup()
+ .addComponent(this.lbl)
+ .addGap(4, 4, 4)
+ .addGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(this.lblWait, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addComponent(this.pgr, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)).addContainerGap()));
+ }// </editor-fold>//GEN-END:initComponents
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+
+ private javax.swing.JLabel lbl;
+ private javax.swing.JLabel lblWait;
+ private javax.swing.JProgressBar pgr;
+
+ // End of variables declaration//GEN-END:variables
+
+ private void initIcons() {
+ final String[] names = { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12" };
+ for (int i = 0; i < 12; i++) {
+ final String name = names[i];
+ final String resName = "fr/gouv/finances/cp/xemelios/updater/ui/res/wait-" + name + ".png";
+ final ImageIcon ii = IhmFactory.getIconFromResource(resName);
+ this.waiters[i] = ii;
+ }
+ }
+
+ @Override
+ public void setVisible(final boolean aFlag) {
+ super.setVisible(aFlag);
+ if (aFlag) {
+ this.startUpdater();
+ } else {
+ this.stopUpdater();
+ }
+ }
+
+ // private void startHide() {
+ // if(timer == null) {
+ // timer = new Timer();
+ // }
+ // Hider hider = new Hider();
+ // timer.schedule(hider, 0, 100);
+ // }
+
+ private void startUpdater() {
+ if (this.timer == null) {
+ this.timer = new Timer();
+ }
+ if (this.currentPainter != null) {
+ return;
+ }
+ this.currentPainter = new ProgressPainter();
+ this.timer.schedule(this.currentPainter, 0, 50);
+ }
+
+ private void stopUpdater() {
+ if (this.currentPainter == null) {
+ return;
+ }
+ this.currentPainter.cancel();
+ this.currentPainter = null;
+ }
+
+ @Override
+ public void propertyChange(final PropertyChangeEvent evt) {
+ if (evt.getPropertyName().equals("progress")) {
+ final int value = (Integer) evt.getNewValue();
+ this.lbl.setText(DWNLOAD_LBL);
+ this.pgr.setIndeterminate(false);
+ this.pgr.setValue(value);
+ } else if (evt.getPropertyName().equals("init")) {
+ this.lbl.setText(INITIAL_LBL);
+ this.pgr.setValue(0);
+ this.pgr.setIndeterminate(true);
+ this.setVisible(true);
+ } else if (evt.getPropertyName().equals("close")) {
+ this.setVisible(false);
+ }
+ }
+
+ @Override
+ public void showMessage(final String htmlMessage) {
+ JOptionPane.showMessageDialog(this.mainWindow, htmlMessage, "Information", JOptionPane.INFORMATION_MESSAGE);
+ }
+
+ @Override
+ public void displayException(final Exception ex) {
+ new DisplayExceptionDlg(this.mainWindow, ex);
+ }
+
+ // affiche la machin qui tourne
+
+ private class ProgressPainter extends TimerTask {
+
+ private final long startTime;
+ private int lastIndex;
+
+ public ProgressPainter() {
+ super();
+ this.startTime = System.currentTimeMillis();
+ }
+
+ @Override
+ public void run() {
+ final long delay = (System.currentTimeMillis() - this.startTime) / 100;
+ final int pos = (int) (delay % 12);
+ if (pos != this.lastIndex) {
+ try {
+ SwingUtilities.invokeAndWait(new Runnable() {
+
+ @Override
+ public void run() {
+ PnlUpdaterProgress.this.lblWait.setIcon(PnlUpdaterProgress.this.waiters[pos]);
+ }
+ });
+ } catch (final Exception ex) {
+ }
+ this.lastIndex = pos;
+ }
+ }
+ }
}
*/
package fr.gouv.finances.cp.xemelios.updater;
-import fr.gouv.finances.cp.utils.PropertiesExpansion;
-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 fr.gouv.finances.dgfip.xemelios.updater.UpdaterPropertyChangeListener;
import java.beans.PropertyChangeEvent;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.zip.GZIPInputStream;
+
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;
+import fr.gouv.finances.cp.utils.PropertiesExpansion;
+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.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 fr.gouv.finances.dgfip.xemelios.updater.UpdaterPropertyChangeListener;
+
/**
- * 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
+ * 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 = "";
- private UpdaterPropertyChangeListener propertyChangeListener;
-
- public UpdateUtil(PropertiesExpansion applicationProperties, UpdaterPropertyChangeListener propertyChangeListener) throws Exception {
- this.applicationProperties = applicationProperties;
- this.propertyChangeListener = propertyChangeListener;
- 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();
- propertyChangeListener.propertyChange(new PropertyChangeEvent(this,"init", 0, 1));
-// pup.setVisible(true);
- if (availableProfils == null) {
- loadProfils();
- }
- checkForStructuralUpdates();
- checkForVersionUpdates();
- dumpDebug();
- propertyChangeListener.propertyChange(new PropertyChangeEvent(this,"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(propertyChangeListener);
- 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(applicationProperties);
- // 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)) {
- propertyChangeListener.showMessage("<html>Téléchargement des mises à jour terminé<br/>Veuillez redémarrer Xemelios afin de finaliser l'installation</html>");
- }
- } catch (Exception ex) {
- logger.error(ex);
- propertyChangeListener.displayException(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;
- }
- }
+ private static Logger logger = Logger.getLogger(UpdateUtil.class);
+ private final PropertiesExpansion applicationProperties;
+ private String installedFileLocation;
+ private ProfilsModel availableProfils;
+ private final InstalledModel im;
+ private final ArrayList<ProfilModel> profilsToAdd = new ArrayList<ProfilModel>();
+ private final ArrayList<ProfilModel> profilsToDelete = new ArrayList<ProfilModel>();
+ private final ArrayList<ComponentModel> componentsToAdd = new ArrayList<ComponentModel>();
+ private final ArrayList<ComponentModel> componentsToBeEditable = new ArrayList<ComponentModel>();
+ private final ArrayList<ComponentModel> componentsToCheckForUpdate = new ArrayList<ComponentModel>();
+ /* Cet array contient les ComponentModel a INSTALLER, avec LA VERSION a installer */
+ private final ArrayList<ComponentModel> componentsToBeUpdated = new ArrayList<ComponentModel>();
+ private final ArrayList<ComponentModel> componentsAllreadyScanned = new ArrayList<ComponentModel>();
+ private final ArrayList<UpdateModel> updateModels = new ArrayList<UpdateModel>();
+ private String checkMethod = "";
+ private final UpdaterPropertyChangeListener propertyChangeListener;
+
+ public UpdateUtil(final PropertiesExpansion applicationProperties, final UpdaterPropertyChangeListener propertyChangeListener) throws Exception {
+ this.applicationProperties = applicationProperties;
+ this.propertyChangeListener = propertyChangeListener;
+ this.im = this.loadInstalled();
+ }
+
+ public String getCheckMethod() {
+ return this.checkMethod;
+ }
+
+ public void setCheckMethod(final String checkMethod) {
+ this.checkMethod = checkMethod;
+ }
+
+ private InstalledModel loadInstalled() throws Exception {
+ this.installedFileLocation = this.applicationProperties.getProperty(Constants.SYS_PROP_INSTALLED_FILENAME);
+ return InstalledModel.readFromFile(this.installedFileLocation);
+ }
+
+ private void loadProfils() throws Exception {
+ final String urlLocation = this.applicationProperties.getProperty(Constants.SYS_PROP_MAJ_PROFILS_URL);
+ this.availableProfils = ProfilsModel.loadModel(urlLocation);
+ }
+
+ public void checkForUpdates() throws Exception {
+ // PnlUpdaterProgress pup = MainWindow.getInstance().getUpdaterProgress();
+ this.propertyChangeListener.propertyChange(new PropertyChangeEvent(this, "init", 0, 1));
+ // pup.setVisible(true);
+ if (this.availableProfils == null) {
+ this.loadProfils();
+ }
+ this.checkForStructuralUpdates();
+ this.checkForVersionUpdates();
+ this.dumpDebug();
+ this.propertyChangeListener.propertyChange(new PropertyChangeEvent(this, "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(final PropertiesExpansion applicationProperties, final ComponentModel cm) throws Exception {
+ final String urlLocation = applicationProperties.getProperty(Constants.SYS_PROP_INSTALLED_FILENAME);
+ final InstalledModel im = InstalledModel.readFromFile(urlLocation);
+ final 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 (final ComponentModel cm : this.componentsToCheckForUpdate) {
+ try {
+ logger.debug("Check new release of : " + cm.getUri() + "(now:" + cm.getVersion() + ") " + cm.getDescription());
+ UpdateModel um = this.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, this.getUpdateTarget());
+ this.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() + ")");
+ final ComponentModel ucm = new ComponentModel(cm.getUri(), um.getLast_version(), cm.getDescription(), cm.isEditable());
+ this.addUniqueComponentModel(this.componentsToBeUpdated, ucm);
+ }
+ } catch (final 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 = this.applicationProperties.getProperty(Constants.SYS_PROP_MAJ_CONFIG);
+ if (ret == null) {
+ ret = Constants.MAJ_PROD;
+ }
+ return ret;
+ }
+
+ private ArrayList<ComponentModel> doAddComponentDependencies(final ComponentModel cm) throws Exception {
+ final 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 = this.getUpdateModelByComponentUriFromCache(cm.getUri());
+ if (um == null) {
+ try {
+ um = UpdateModel.loadModel(cm, this.getUpdateTarget());
+ this.addUniqueUpdateModelInCache(um); // On met en "cache" l'update model de ce composant
+ } catch (final Exception ex) {
+ this.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());
+ this.addUniqueComponentModel(cms, cm);
+ logger.debug(" Dernière version du composant : " + um.getLast_version());
+ final 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 (final ComponentRefModel crm : um.getVersions().get(lastVersionIdx).getRequires().getComponents()) {
+ final ComponentModel cmm = new ComponentModel(crm.getUri());
+ logger.debug(" Scan du composant dépendant de " + cm.getUri() + " : " + cmm.getUri() + "...");
+ if (!this.component_exists(this.componentsAllreadyScanned, cm)) {
+ this.addUniqueComponentModel(this.componentsAllreadyScanned, cm);
+ final ArrayList<ComponentModel> acm = this.doAddComponentDependencies(cmm);
+ logger.debug("============================ DUMP Array returned, size=" + acm.size());
+ for (final ComponentModel ccc : acm) {
+ logger.debug(ccc.getUri());
+ }
+ logger.debug("============================ ");
+ this.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(final ArrayList<ComponentModel> components, final ComponentModel cm) {
+ for (final 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 (final ProfilModel apm : this.availableProfils.getProfils()) {
+ /*
+ * Profil Requis On ajoute ses composants
+ */
+ if (apm.isRequired()) {
+ if (this.im.getProfilIdx(apm.getId()) == InstalledModel.NOT_FOUND) {
+ logger.debug("ph0 : ajout du profil required et non abonné " + apm.getId() + "/" + apm.getDescription());
+ this.profilsToAdd.add(apm);
+ for (final ComponentModel cm : apm.getComponents()) {
+ logger.debug("ph0 : ajout du composant du profil " + apm.getId() + " : " + cm.getUri() + "/" + cm.getDescription());
+ // componentsToAdd.add(cm);
+ this.addUniqueComponentModel(this.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());
+ final int ipidx = this.im.getProfilIdx(apm.getId());
+ if (ipidx != InstalledModel.NOT_FOUND) {
+ logger.debug("ph0: profil toujours abonné...");
+ for (final ComponentModel acm : apm.getComponents()) {
+ final ComponentModel icm = this.im.getComponent(acm.getUri());
+ if (icm != null) {
+ logger.debug("ph0: composant rendu éditable : " + icm.getUri() + "/" + icm.getDescription());
+ icm.setEditable(true);
+ // componentsToBeEditable.add(icm);
+ this.addUniqueComponentModel(this.componentsToBeEditable, icm);
+ }
+ }
+ this.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
+ final ArrayList<ComponentModel> acms = new ArrayList<ComponentModel>();
+
+ for (final ProfilModel ipm : this.im.getProfils()) {
+ final int idx = this.availableProfils.getIdxById(ipm.getId());
+ if (idx == InstalledModel.NOT_FOUND) {
+ continue;
+ }
+ final ProfilModel apm = this.availableProfils.getProfils().get(idx);
+ for (final ComponentModel acm : apm.getComponents()) {
+ // acms.add(acm); // utilisé pour le phase 2
+ this.addUniqueComponentModel(acms, acm);
+ if (this.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);
+ this.addUniqueComponentModel(this.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 (final ComponentModel icm : this.im.getComponents()) {
+ if (!icm.isEditable()) {
+ boolean bFound = false;
+ for (final ComponentModel acm : acms) {
+ if (acm.getUri().equalsIgnoreCase(icm.getUri())) {
+ bFound = true;
+ break;
+ }
+ }
+ if (!bFound) {
+ icm.setEditable(true);
+ // componentsToBeEditable.add(icm);
+ this.addUniqueComponentModel(this.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 < this.componentsToAdd.size(); i++) {
+ final ComponentModel cm = this.im.getComponent(this.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());
+ this.componentsToAdd.remove(i);
+ }
+ }
+ for (int i = 0; i < this.componentsToBeEditable.size(); i++) {
+ for (int j = 0; j < this.componentsToAdd.size(); j++) {
+ if (this.componentsToAdd.get(j).getUri().equalsIgnoreCase(this.componentsToBeEditable.get(i).getUri())) {
+ final ComponentModel cm = this.componentsToBeEditable.get(i);
+ logger.debug("clean: del component tagged to be editabled, already tagged to be add : " + cm.getUri() + "/" + cm.getDescription());
+ this.componentsToBeEditable.remove(i);
+ }
+ }
+ }
+
+ /*
+ * Liste des composants pour lesquels il faut vérifier la version donc potentiellement updatables
+ */
+ // componentsToCheckForUpdate.addAll(im.getComponents());
+ this.addAllUniqueComponentModels(this.componentsToCheckForUpdate, this.im.getComponents());
+ // componentsToCheckForUpdate.addAll(componentsToAdd);
+ this.addAllUniqueComponentModels(this.componentsToCheckForUpdate, this.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...
+ */
+ final ArrayList<ComponentModel> cmd = new ArrayList<ComponentModel>();
+ for (final ComponentModel cm : this.componentsToCheckForUpdate) {
+ final ArrayList<ComponentModel> ccmd = this.doAddComponentDependencies(cm);
+ this.addAllUniqueComponentModels(cmd, ccmd);
+ }
+ logger.debug("FINAL ------------------------------------------- DUMP Array returned, size=" + cmd.size());
+ for (final ComponentModel ccc : cmd) {
+ logger.debug(ccc.getUri());
+ }
+ logger.debug("FINAL ------------------------------------------- ");
+ this.addAllUniqueComponentModels(this.componentsToCheckForUpdate, cmd);
+
+ /*
+ * On ADD aussi les composants non installé qui découlent des dépendances
+ */
+
+ for (final ComponentModel depcm : cmd) {
+ boolean bFound = false;
+ for (final ComponentModel icm : this.im.getComponents()) {
+ if (icm.getUri().equalsIgnoreCase(depcm.getUri())) {
+ bFound = true;
+ break;
+ }
+ }
+ if (!bFound) {
+ this.addUniqueComponentModel(this.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 (final ProfilModel pm : this.profilsToDelete) {
+ logger.debug("- " + pm.getId() + "/" + pm.getDescription());
+ }
+ logger.debug("Liste des profils à ajouter :");
+ for (final ProfilModel pm : this.profilsToAdd) {
+ logger.debug("- " + pm.getId() + "/" + pm.getDescription());
+ }
+ logger.debug("Liste des composants à ajouter :");
+ for (final ComponentModel cm : this.componentsToAdd) {
+ logger.debug("- " + cm.getUri() + "/" + cm.getDescription());
+ }
+ logger.debug("Liste des composants à rendre éditable (à éffacer) :");
+ for (final ComponentModel cm : this.componentsToBeEditable) {
+ logger.debug("- " + cm.getUri() + "/" + cm.getDescription() + "/" + cm.getVersion());
+ }
+ logger.debug("Liste des composants à mettre à installer :");
+ for (final ComponentModel cm : this.componentsToBeUpdated) {
+ logger.debug("- " + cm.getUri() + "/" + cm.getDescription());
+ }
+
+ logger.debug("UpdateNeeded returns " + (this.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 {
+
+ final Downloader dl = new Downloader(this.componentsToBeUpdated, this.updateModels);
+ dl.execute();
+ // saveInstalledModel();
+ }
+
+ public void saveInstalledModel() throws Exception {
+
+ /*
+ * Traitement des profils a ajouter et à effacer
+ */
+ for (final ProfilModel pm : this.profilsToDelete) {
+ this.im.removeProfil(pm.getId());
+ }
+ for (final ProfilModel pm : this.profilsToAdd) {
+ /*
+ * On ajoute seulement le TAG profil du profil dans le fichier installed.xml et non pas les composants qui sont attachés
+ */
+ this.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 (final ComponentModel cm : this.componentsToBeEditable) {
+ try {
+ this.im.getComponent(cm.getUri()).setEditable(true);
+ } catch (final 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) { } }
+ */
+ this.im.saveInstalledModel();
+
+ }
+
+ private boolean addUniqueComponentModel(final ArrayList<ComponentModel> ar, final 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(final ArrayList<ComponentModel> ar, final ArrayList<ComponentModel> ar_toadd) {
+ if (ar == null || ar_toadd == null) {
+ return;
+ }
+ for (int i = 0; i < ar_toadd.size(); i++) {
+ this.addUniqueComponentModel(ar, ar_toadd.get(i));
+ }
+ }
+
+ private boolean addUniqueUpdateModelInCache(final UpdateModel c) {
+ if (c == null) {
+ return false;
+ }
+ if (c.getComponentUri() == null || c.getComponentUri().isEmpty()) {
+ return false;
+ }
+ for (final UpdateModel um : this.updateModels) {
+ if (um.getComponentUri().equalsIgnoreCase(c.getComponentUri())) {
+ return false;
+ }
+ }
+ this.updateModels.add(c);
+ return true;
+ }
+
+ private UpdateModel getUpdateModelByComponentUriFromCache(final String ComponentUri) {
+ if (ComponentUri == null || ComponentUri.isEmpty()) {
+ return null;
+ }
+ for (final UpdateModel um : this.updateModels) {
+ if (ComponentUri.equalsIgnoreCase(um.getComponentUri())) {
+ return um;
+ }
+ }
+ return null;
+ }
+
+ /**
+ *
+ * @return Vérifie si des MAJ sont nécessaires
+ */
+ public boolean updateNeeded() {
+ return (!this.profilsToAdd.isEmpty() || !this.profilsToDelete.isEmpty() || !this.componentsToBeUpdated.isEmpty());
+
+ // return (!componentsToAdd.isEmpty()
+ // || !componentsToBeEditable.isEmpty()
+ // || !profilsToAdd.isEmpty()
+ // || !profilsToDelete.isEmpty()
+ // || !componentsToBeUpdated.isEmpty());
+ }
+
+ /**
+ *
+ * @param r1
+ * @param r2
+ * @return
+ */
+ public static int compareReleases(final String r1, final String r2) {
+ final String[] s1 = splitRelease(r1);
+ final 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 (final 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 (final Throwable t2) {
+ }
+ }
+ }
+ try {
+ b = Integer.parseInt(s2[i]);
+ } catch (final 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 (final 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 this.componentsToAdd;
+ }
+
+ public ArrayList<ComponentModel> getComponentsToBeUpdated() {
+ return this.componentsToBeUpdated;
+ }
+
+ private static String[] splitRelease(final String r) {
+ return r.split("\\.");
+ }
+
+ private File getLocalFileName(final String filePath, final String fileName) {
+ String ret = filePath;
+ int pos = ret.indexOf("${");
+ while (pos >= 0) {
+ final String before = ret.substring(0, pos);
+ final int end = ret.indexOf("}");
+ final String after = ret.substring(end + 1);
+ final String key = ret.substring(pos + 2, end);
+ ret = before + this.applicationProperties.getProperty(key) + after;
+ pos = ret.indexOf("${");
+ }
+ logger.debug("ret=" + ret);
+ final File f = new File(new File(ret), fileName);
+ if (f.exists()) {
+ return f;
+ }
+ return null;
+ }
+
+ private String unescapePath(final String path) {
+ return this.applicationProperties.replace(path);
+ }
+
+ public class Downloader extends SwingWorker<Boolean, Integer> {
+
+ private final ArrayList<ComponentModel> ci;
+ private final ArrayList<UpdateModel> ui;
+ protected String errorMsg = null;
+ protected Exception exception = null;
+
+ public Exception getException() {
+ return this.exception;
+ }
+
+ public String getErrorMessage() {
+ return this.errorMsg;
+ }
+
+ private Downloader(final ArrayList<ComponentModel> ci, final ArrayList<UpdateModel> ui) {
+ super();
+ this.ci = ci;
+ this.ui = ui;
+ }
+
+ private UpdateModel getUpdateModelFromComponentURI(final String ComponentUri) {
+ for (final UpdateModel um : this.ui) {
+ if (ComponentUri.equalsIgnoreCase(um.getComponentUri())) {
+ return um;
+ }
+ }
+ return null;
+ }
+
+ @Override
+ protected Boolean doInBackground() throws Exception {
+ logger.debug("in doInBackground");
+ boolean bRet = true;
+ this.addPropertyChangeListener(UpdateUtil.this.propertyChangeListener);
+ this.firePropertyChange("init", 0, 1);
+ try {
+ final File tmpDir = new File(UpdateUtil.this.unescapePath("${xemelios.dir}/tmp-upd"));
+ logger.debug("tmpDir=" + tmpDir.getPath());
+ tmpDir.mkdirs();
+ final StringBuilder sb = new StringBuilder();
+ final HttpClient client = NetAccess.getHttpClient(UpdateUtil.this.applicationProperties);
+ // step 1: on compte le nombre de fichiers à traiter
+ int nbItemsToTreat = 0;
+ for (final ComponentModel cm : this.ci) {
+ final UpdateModel um = this.getUpdateModelFromComponentURI(cm.getUri());
+ if (um != null) {
+ final VersionModel vm = um.getLastVersionModel();
+ final 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 (final ComponentModel cm : this.ci) {
+ logger.debug("Installation du composant : " + cm.getUri() + " / " + cm.getDescription());
+ final UpdateModel um = this.getUpdateModelFromComponentURI(cm.getUri());
+ logger.debug("UpdateModel utilisé : " + um.getLast_version() + " du " + um.getGenerate_date());
+ if (um != null) {
+ final VersionModel vm = um.getLastVersionModel();
+ logger.debug("Version utilisée : " + vm.getVersion() + " du " + vm.getDate());
+ final FileListModel fl = vm.getFiles();
+ final String root = fl.getRoot();
+ logger.debug("root = " + root);
+ for (final 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());
+ final File localFile = UpdateUtil.this.getLocalFileName(fm.getDest(), fm.getName());
+ if (localFile != null) {
+ final AbstractChecksum localChecksum = new MD("MD5");
+ final FileInputStream fis = new FileInputStream(localFile);
+ final 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;
+ }
+ }
+ final String sUrl = root + "/" + fm.getSource();
+ final URL url = new URL(sUrl);
+ final AbstractChecksum checksum = new MD("MD5");
+ FileOutputStream fos;
+ final File tmpFile = File.createTempFile("upd-", null, tmpDir);
+ fos = new FileOutputStream(tmpFile);
+ logger.info("downloading " + sUrl + " to " + tmpFile.getPath());
+ final HttpMethod meth = new GetMethod(sUrl);
+ meth.addRequestHeader("Pragma", "no-cache");
+ final int returnCode = client.executeMethod(meth);
+ if (returnCode <= 300) {
+ final InputStream is = meth.getResponseBodyAsStream();
+ final 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
+ final AbstractChecksum checksumUncompressed = new MD("MD5");
+ final GZIPInputStream gzipis = new GZIPInputStream(new FileInputStream(tmpFile));
+ final File tmpFileUncompressed = File.createTempFile("upd-", null, tmpDir);
+ final FileOutputStream fosUncompressed = new FileOutputStream(tmpFileUncompressed);
+ final 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 {
+ this.errorMsg = " " + returnCode + " : " + meth.getStatusText() + " : " + sUrl;
+ bRet = false;
+ throw new IOException(this.errorMsg);
+ }
+ itemsRun++;
+ final int newProgressValue = this.calculateProgress(nbItemsToTreat, itemsRun);
+ this.firePropertyChange("progress", lastProgressValue, newProgressValue);
+ lastProgressValue = newProgressValue;
+ }
+ for (final DeleteModel dm : fl.getDeletes()) {
+ sb.append("delete|").append(dm.getName()).append("\n");
+ final int newProgressValue = this.calculateProgress(nbItemsToTreat, itemsRun);
+ this.firePropertyChange("progress", lastProgressValue, newProgressValue);
+ lastProgressValue = newProgressValue;
+ }
+ for (final ConfigurationModel conf : vm.getConfigurators()) {
+ if (!vm.getConfigurators().isEmpty()) {
+ sb.append("configuration|").append(conf.getClassName()).append("");
+ sb.append("\n");
+ final int newProgressValue = this.calculateProgress(nbItemsToTreat, itemsRun);
+ this.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");
+ }
+ }
+ final File batch = new File(tmpDir, "update-script.xem");
+ final FileOutputStream fos = new FileOutputStream(batch);
+ final 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 (final UpdaterException uex) {
+ bRet = false;
+ this.exception = uex;
+ logger.error(uex);
+ } catch (final MalformedURLException e) {
+ bRet = false;
+ logger.error(e);
+ } catch (final IOException e) {
+ bRet = false;
+ logger.error(e);
+ } catch (final DataConfigurationException dcEx) {
+ bRet = false;
+ this.errorMsg = dcEx.getMessage();
+ logger.error(dcEx);
+ } finally {
+ this.firePropertyChange("close", 0, 1);
+ }
+ return bRet;
+ }
+
+ @Override
+ protected void done() {
+ try {
+ UpdateUtil.this.saveInstalledModel();
+ if (Constants.MAJ_CONFIRM.equals(UpdateUtil.this.checkMethod)) {
+ UpdateUtil.this.propertyChangeListener.showMessage("<html>Téléchargement des mises à jour terminé<br/>Veuillez redémarrer Xemelios afin de finaliser l'installation</html>");
+ }
+ } catch (final Exception ex) {
+ logger.error(ex);
+ UpdateUtil.this.propertyChangeListener.displayException(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(final int total, final int current) {
+ final int ret = 100 * current / total;
+ logger.debug("item " + current + " done -> value=" + ret);
+ return ret;
+ }
+ }
}
// TODO Auto-generated constructor stub
}
- public UpdaterException(String message) {
+ public UpdaterException(final String message) {
super(message);
// TODO Auto-generated constructor stub
}
- public UpdaterException(String message, Throwable cause) {
+ public UpdaterException(final String message, final Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
- public UpdaterException(Throwable cause) {
+ public UpdaterException(final Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
*/
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 javax.xml.namespace.QName;
import org.xml.sax.Attributes;
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;
+import fr.gouv.finances.dgfip.xemelios.common.config.TexteModel;
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;
- }
+ 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(final QName tag) {
+ super();
+ this.fileLists = new ArrayList<FileListModel>();
+ }
+
+ @Override
+ public void addCharacterData(final String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(final XmlMarshallable child, final QName tagName) throws SAXException {
+ if (ReleaseModel.QN.equals(tagName)) {
+ this.release = (ReleaseModel) child;
+ } else if (UpdateParser.DESCRIPTION.equals(tagName)) {
+ this.description = (TexteModel) child;
+ } else if (RequireModel.QN.equals(tagName)) {
+ this.requires = (RequireModel) child;
+ } else if (FileListModel.QN.equals(tagName)) {
+ this.fileLists.add((FileListModel) child);
+ } else if (ConfigurationModel.QN.equals(tagName)) {
+ this.configuration = (ConfigurationModel) child;
+ }
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(final XmlAttributes attributes) throws SAXException {
+ this.id = attributes.getValue("cid");
+ this.name = attributes.getValue("name");
+ final String sTmp = attributes.getValue("visible");
+ if (sTmp != null) {
+ this.visible = attributes.getBooleanValue("visible");
+ }
+ return this;
+ }
+
+ @Override
+ public void marshall(final XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("cid", this.id);
+ output.addAttribute("name", this.name);
+ if (!this.visible) {
+ output.addAttribute("visible", "no");
+ }
+ this.release.marshall(output);
+ this.description.marshall(output);
+ if (this.requires != null) {
+ this.requires.marshall(output);
+ }
+ for (final FileListModel fileListModel : this.fileLists) {
+ fileListModel.marshall(output);
+ }
+ // TODO
+ output.endTag(TAG);
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ if (this.id == null) {
+ throw new InvalidXmlDefinition("cid attribute is mandatory for element " + TAG);
+ }
+ if (this.name == null) {
+ throw new InvalidXmlDefinition("name attribute is mandatory for element " + TAG);
+ }
+ }
+
+ @Override
+ public ComponentModel clone() {
+ final ComponentModel cm = new ComponentModel(QN);
+ cm.id = this.id;
+ cm.name = this.name;
+ cm.release = this.release.clone();
+ cm.description = this.description.clone();
+ for (final FileListModel fileListModel : this.fileLists) {
+ cm.fileLists.add(fileListModel.clone());
+ }
+ return cm;
+ }
+
+ public TexteModel getDescription() {
+ return this.description;
+ }
+
+ public void setDescription(final TexteModel description) {
+ this.description = description;
+ }
+
+ public void setDescription(final String s) {
+ final TexteModel desc = new TexteModel(UpdateParser.DESCRIPTION);
+ try {
+ desc.addCharacterData(s);
+ } catch (final Throwable t) {
+ }
+ this.setDescription(desc);
+ }
+
+ public ArrayList<FileListModel> getFileLists() {
+ return this.fileLists;
+ }
+
+ public void setFileLists(final ArrayList<FileListModel> fileLists) {
+ this.fileLists = fileLists;
+ }
+
+ public String getId() {
+ return this.id;
+ }
+
+ public void setId(final String id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ public void setName(final String name) {
+ this.name = name;
+ }
+
+ public ReleaseModel getRelease() {
+ return this.release;
+ }
+
+ public void setRelease(final ReleaseModel release) {
+ this.release = release;
+ }
+
+ public void setRelease(final String s) {
+ final ReleaseModel rm = new ReleaseModel(ReleaseModel.QN);
+ rm.setV(s);
+ this.setRelease(rm);
+ }
+
+ public RequireModel getRequires() {
+ return this.requires;
+ }
+
+ public void setRequires(final RequireModel requires) {
+ this.requires = requires;
+ }
+
+ @Override
+ public String toString() {
+ return this.getId() + " (" + this.getRelease().getV() + ")";
+ }
+
+ public boolean isVisible() {
+ return this.visible;
+ }
+
+ @Override
+ public boolean equals(final Object o) {
+ if (o instanceof ComponentModel) {
+ final ComponentModel cm = (ComponentModel) o;
+ return cm.getId().equals(this.id) && cm.getRelease().getV().equals(this.getRelease().getV());
+ } else if (o instanceof ComponentRefModel) {
+ final ComponentRefModel cm = (ComponentRefModel) o;
+ return cm.getId().equals(this.id) && cm.getVersion().equals(this.getRelease().getV());
+ } else if (o instanceof String) {
+ return this.getId().equals(o);
+ }
+ return false;
+ }
+
+ public ConfigurationModel getConfiguration() {
+ return this.configuration;
+ }
+
+ public void setConfiguration(final ConfigurationModel configuration) {
+ this.configuration = configuration;
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(final String uri, final String localName, final String qName, final Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
}
package fr.gouv.finances.cp.xemelios.updater.config;
+import javax.xml.namespace.QName;
+
import org.xml.sax.Attributes;
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 ComponentRefModel implements XmlMarshallable {
public static final transient String TAG = "component-ref";
- public static final transient QName QN = new QName(TAG);
+ public static final transient QName QN = new QName(TAG);
private String id, version;
- public ComponentRefModel(QName tag) {
+ public ComponentRefModel(final QName tag) {
super();
}
- public void addCharacterData(String cData) throws SAXException {
+ @Override
+ public void addCharacterData(final String cData) throws SAXException {
}
- public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
+ @Override
+ public void addChild(final XmlMarshallable child, final QName tagName) throws SAXException {
}
- public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
- id=attributes.getValue("cid");
- version=attributes.getValue("version");
+ @Override
+ public XmlMarshallable getAttributes(final XmlAttributes attributes) throws SAXException {
+ this.id = attributes.getValue("cid");
+ this.version = attributes.getValue("version");
return this;
}
- public void marshall(XmlOutputter output) {
+ @Override
+ public void marshall(final XmlOutputter output) {
output.startTag(TAG);
- output.addAttribute("cid",id);
- output.addAttribute("version",version);
+ output.addAttribute("cid", this.id);
+ output.addAttribute("version", this.version);
output.endTag(TAG);
}
+ @Override
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);
+ if (this.id == null) {
+ throw new InvalidXmlDefinition("cid attribute is mandatory for element " + TAG);
+ }
+ if (this.version == null) {
+ throw new InvalidXmlDefinition("version attribute is mandatory for element " + TAG);
+ }
}
+
+ @Override
public ComponentRefModel clone() {
- ComponentRefModel cr = new ComponentRefModel(QN);
- cr.id=id;
- cr.version=version;
+ final ComponentRefModel cr = new ComponentRefModel(QN);
+ cr.id = this.id;
+ cr.version = this.version;
return cr;
}
public String getId() {
- return id;
+ return this.id;
}
- public void setId(String id) {
+ public void setId(final String id) {
this.id = id;
}
public String getVersion() {
- return version;
+ return this.version;
}
- public void setVersion(String version) {
+ public void setVersion(final String version) {
this.version = version;
}
+
+ @Override
public String toString() {
- return id+" ("+version+")";
+ return this.id + " (" + this.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 boolean equals(final ComponentRefModel crm) {
+ return crm.getId().equals(this.id);
+ }
- public QName getQName() {
- return QN;
- }
+ public boolean equals(final ComponentModel crm) {
+ return crm.getId().equals(this.id);
+ }
+
+ public boolean equals(final String id) {
+ return this.id.equals(id);
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(final String uri, final String localName, final String qName, final Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
}
package fr.gouv.finances.cp.xemelios.updater.config;
import java.util.ArrayList;
-import java.util.Iterator;
+
+import javax.xml.namespace.QName;
import org.xml.sax.Attributes;
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 ConfigurationModel implements XmlMarshallable {
- public static final transient String TAG="configuration";
- public static final transient QName QN = new QName(TAG);
-
+ 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) {
+ public ConfigurationModel(final QName tagName) {
super();
- params = new ArrayList<ParamModel>();
+ this.params = new ArrayList<ParamModel>();
}
- public void addCharacterData(String cData) throws SAXException {
+ @Override
+ public void addCharacterData(final String cData) throws SAXException {
}
- public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
- if(ParamModel.QN.equals(tagName)) params.add((ParamModel)child);
+ @Override
+ public void addChild(final XmlMarshallable child, final QName tagName) throws SAXException {
+ if (ParamModel.QN.equals(tagName)) {
+ this.params.add((ParamModel) child);
+ }
}
- public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
- className = attributes.getValue("class");
+ @Override
+ public XmlMarshallable getAttributes(final XmlAttributes attributes) throws SAXException {
+ this.className = attributes.getValue("class");
return this;
}
- public void marshall(XmlOutputter output) {
+ @Override
+ public void marshall(final XmlOutputter output) {
output.startTag(TAG);
- output.addAttribute("class",className);
- for(Iterator<ParamModel> it=params.iterator();it.hasNext();)
- it.next().marshall(output);
+ output.addAttribute("class", this.className);
+ for (final ParamModel paramModel : this.params) {
+ paramModel.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());
+ final ConfigurationModel cm = new ConfigurationModel(QN);
+ cm.className = this.className;
+ for (final ParamModel paramModel : this.params) {
+ cm.params.add(paramModel);
+ }
return cm;
}
public String getClassName() {
- return className;
+ return this.className;
}
- public void setClassName(String className) {
+ public void setClassName(final String className) {
this.className = className;
}
public ArrayList<ParamModel> getParams() {
- return params;
+ return this.params;
}
- public void setParams(ArrayList<ParamModel> params) {
+ public void setParams(final ArrayList<ParamModel> params) {
this.params = params;
}
- public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
- return null;
- }
+ @Override
+ public XmlMarshallable getChildToModify(final String uri, final String localName, final String qName, final Attributes atts) {
+ return null;
+ }
- public QName getQName() {
- return QN;
- }
+ @Override
+ public QName getQName() {
+ return QN;
+ }
}
*/
package fr.gouv.finances.cp.xemelios.updater.config;
+import javax.xml.namespace.QName;
+
import org.xml.sax.Attributes;
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 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();
- }
-
- @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 = this.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;
- }
+ public static final transient String TAG = "delete";
+ public static final transient QName QN = new QName(TAG);
+ private String name;
+
+ public DeleteModel(final QName tagName) {
+ super();
+ }
+
+ @Override
+ public void addCharacterData(final String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(final XmlMarshallable child, final QName tagName) throws SAXException {
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(final XmlAttributes attributes) throws SAXException {
+ this.name = attributes.getValue("name");
+ return this;
+ }
+
+ @Override
+ public void marshall(final XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("name", this.name);
+ output.endTag(TAG);
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ }
+
+ @Override
+ public DeleteModel clone() {
+ final DeleteModel dm = new DeleteModel(QN);
+ dm.name = this.name;
+ return dm;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ public void setName(final String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String toString() {
+ return "- " + this.getName();
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(final String uri, final String localName, final String qName, final Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
}
package fr.gouv.finances.cp.xemelios.updater.config;
import java.util.ArrayList;
-import java.util.Iterator;
+
+import javax.xml.namespace.QName;
import org.xml.sax.Attributes;
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 FileListModel implements XmlMarshallable {
public static final transient String TAG = "files";
- public static final transient QName QN = new QName(TAG);
-
+ public static final transient QName QN = new QName(TAG);
+
private String root;
-
+
public ArrayList<XmlMarshallable> files;
- public FileListModel(QName tag) {
+ public FileListModel(final QName tag) {
super();
- files=new ArrayList<XmlMarshallable>();
+ this.files = new ArrayList<XmlMarshallable>();
}
- public void addCharacterData(String cData) throws SAXException {
+ @Override
+ public void addCharacterData(final String cData) throws SAXException {
}
- public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
- files.add(child);
+ @Override
+ public void addChild(final XmlMarshallable child, final QName tagName) throws SAXException {
+ this.files.add(child);
}
- public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
- root = attributes.getValue("root");
+ @Override
+ public XmlMarshallable getAttributes(final XmlAttributes attributes) throws SAXException {
+ this.root = attributes.getValue("root");
return this;
}
- public void marshall(XmlOutputter output) {
+ @Override
+ public void marshall(final XmlOutputter output) {
output.startTag(TAG);
- output.addAttribute("root",root);
- for(Iterator<XmlMarshallable> it=files.iterator();it.hasNext();)
- it.next().marshall(output);
+ output.addAttribute("root", this.root);
+ for (final XmlMarshallable xmlMarshallable : this.files) {
+ xmlMarshallable.marshall(output);
+ }
output.endTag(TAG);
}
- public void validate() throws InvalidXmlDefinition { }
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ }
+
+ @Override
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());
+ final FileListModel flm = new FileListModel(QN);
+ flm.root = this.root;
+ for (final XmlMarshallable xmlMarshallable : this.files) {
+ flm.files.add((XmlMarshallable) xmlMarshallable.clone());
+ }
return flm;
}
public ArrayList<XmlMarshallable> getFiles() {
- return files;
+ return this.files;
}
- public void setFiles(ArrayList<XmlMarshallable> files) {
+ public void setFiles(final ArrayList<XmlMarshallable> files) {
this.files = files;
}
public String getRoot() {
- return root;
+ return this.root;
}
- public void setRoot(String root) {
+ public void setRoot(final String root) {
this.root = root;
}
- public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
- return null;
- }
+ @Override
+ public XmlMarshallable getChildToModify(final String uri, final String localName, final String qName, final Attributes atts) {
+ return null;
+ }
- public QName getQName() {
- return QN;
- }
+ @Override
+ public QName getQName() {
+ return QN;
+ }
}
*/
package fr.gouv.finances.cp.xemelios.updater.config;
+import javax.xml.namespace.QName;
+
import org.xml.sax.Attributes;
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 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;
- }
+ 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(final QName tag) {
+ super();
+ }
+
+ @Override
+ public void addCharacterData(final String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(final XmlMarshallable child, final QName tagName) throws SAXException {
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(final XmlAttributes attributes) throws SAXException {
+ this.name = attributes.getValue("name");
+ this.source = attributes.getValue("source");
+ this.dest = attributes.getValue("dest");
+ this.md5 = attributes.getValue("md5");
+ this.unpackedMd5 = attributes.getValue("unpacked-md5");
+ return this;
+ }
+
+ @Override
+ public void marshall(final XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("name", this.name);
+ output.addAttribute("source", this.source);
+ output.addAttribute("dest", this.dest);
+ output.addAttribute("md5", this.md5);
+ output.endTag(TAG);
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ }
+
+ @Override
+ public FileModel clone() {
+ final FileModel fm = new FileModel(QN);
+ fm.name = this.name;
+ fm.source = this.source;
+ fm.dest = this.dest;
+ return fm;
+ }
+
+ public String getDest() {
+ return this.dest;
+ }
+
+ public void setDest(final String dest) {
+ this.dest = dest;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ public void setName(final String name) {
+ this.name = name;
+ }
+
+ public String getSource() {
+ return this.source;
+ }
+
+ public void setSource(final String source) {
+ this.source = source;
+ }
+
+ @Override
+ public String toString() {
+ return this.getName();
+ }
+
+ public String getMd5() {
+ return this.md5;
+ }
+
+ public void setMd5(final String md5) {
+ this.md5 = md5;
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(final String uri, final String localName, final String qName, final Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
+
+ public String getUnpackedMd5() {
+ return this.unpackedMd5;
+ }
+
+ public void setUnpackedMd5(final String unpackedMd5) {
+ this.unpackedMd5 = unpackedMd5;
+ }
}
package fr.gouv.finances.cp.xemelios.updater.config;
import java.util.ArrayList;
-import java.util.Iterator;
+
+import javax.xml.namespace.QName;
import org.xml.sax.Attributes;
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 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;
- }
+ public static final transient String TAG = "foreign-sites";
+ public static final transient QName QN = new QName(TAG);
+ private ArrayList<SiteModel> sites;
+
+ public ForeignSitesModel(final QName tag) {
+ super();
+ this.sites = new ArrayList<SiteModel>();
+ }
+
+ @Override
+ public void addCharacterData(final String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(final XmlMarshallable child, final QName tagName) throws SAXException {
+ this.sites.add((SiteModel) child);
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(final XmlAttributes attributes) throws SAXException {
+ return this;
+ }
+
+ @Override
+ public void marshall(final XmlOutputter output) {
+ output.startTag(TAG);
+ for (final SiteModel siteModel : this.sites) {
+ siteModel.marshall(output);
+ }
+ output.endTag(TAG);
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ }
+
+ @Override
+ public ForeignSitesModel clone() {
+ final ForeignSitesModel fs = new ForeignSitesModel(QN);
+ for (final SiteModel siteModel : this.sites) {
+ fs.sites.add(siteModel);
+ }
+ return fs;
+ }
+
+ public ArrayList<SiteModel> getSites() {
+ return this.sites;
+ }
+
+ public void setSites(final ArrayList<SiteModel> sites) {
+ this.sites = sites;
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(final String uri, final String localName, final String qName, final Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
}
*/
package fr.gouv.finances.cp.xemelios.updater.config;
+import javax.xml.namespace.QName;
+
import org.xml.sax.Attributes;
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 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;
- }
+ public static final transient String TAG = "param";
+ public static final transient QName QN = new QName(TAG);
+ private String name;
+ private StringBuilder paramValue;
+
+ public ParamModel(final QName tagName) {
+ super();
+ this.paramValue = new StringBuilder();
+ }
+
+ @Override
+ public void addCharacterData(final String cData) throws SAXException {
+ this.paramValue.append(cData);
+ }
+
+ @Override
+ public void addChild(final XmlMarshallable child, final QName tagName) throws SAXException {
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(final XmlAttributes attributes) throws SAXException {
+ this.name = attributes.getValue("name");
+ return this;
+ }
+
+ @Override
+ public void marshall(final XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("name", this.name);
+ output.addCharacterData(this.getParamValue());
+ output.endTag(TAG);
+
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ }
+
+ @Override
+ public ParamModel clone() {
+ final ParamModel pm = new ParamModel(QN);
+ pm.name = this.name;
+ pm.paramValue.append(this.getParamValue());
+ return pm;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ public void setName(final String name) {
+ this.name = name;
+ }
+
+ public String getParamValue() {
+ return this.paramValue.toString();
+ }
+
+ public void setParamValue(final StringBuilder paramValue) {
+ this.paramValue = paramValue;
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(final String uri, final String localName, final String qName, final Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
}
import java.text.SimpleDateFormat;
import java.util.Date;
+import javax.xml.namespace.QName;
+
import org.xml.sax.Attributes;
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 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;
- }
+ 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(final QName tag) {
+ super();
+ }
+
+ @Override
+ public void addCharacterData(final String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(final XmlMarshallable child, final QName tagName) throws SAXException {
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(final XmlAttributes attributes) throws SAXException {
+ this.v = attributes.getValue("v");
+ final String sTmp = attributes.getValue("date");
+ try {
+ this.date = sdf.parse(sTmp);
+ } catch (final ParseException pEx) {
+ throw new SAXException("format for date attribute is YYYY-MM-DD");
+ }
+ return this;
+ }
+
+ @Override
+ public void marshall(final XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("v", this.v);
+ output.addAttribute("date", sdf.format(this.date));
+ }
+
+ public Date getDate() {
+ return this.date;
+ }
+
+ public void setDate(final Date date) {
+ this.date = date;
+ }
+
+ public String getV() {
+ return this.v;
+ }
+
+ public void setV(final String v) {
+ this.v = v;
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ if (this.v == null || this.v.length() == 0) {
+ throw new InvalidXmlDefinition("attribute v is mandatory for " + TAG + " element.");
+ }
+ if (this.date == null) {
+ throw new InvalidXmlDefinition("attribute date is mandatory for " + TAG + " element.");
+ }
+ }
+
+ @Override
+ public ReleaseModel clone() {
+ final ReleaseModel rm = new ReleaseModel(QN);
+ rm.v = this.v;
+ rm.date = (Date) this.date.clone();
+ return rm;
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(final String uri, final String localName, final String qName, final Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
}
package fr.gouv.finances.cp.xemelios.updater.config;
import java.util.ArrayList;
-import java.util.Iterator;
+
+import javax.xml.namespace.QName;
import org.xml.sax.Attributes;
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 RequireModel implements XmlMarshallable {
public static final transient String TAG = "requires";
- public static final transient QName QN = new QName(TAG);
-
+ public static final transient QName QN = new QName(TAG);
+
private ArrayList<ComponentRefModel> components;
- public RequireModel(QName tag) {
+ public RequireModel(final QName tag) {
super();
- components = new ArrayList<ComponentRefModel>();
+ this.components = new ArrayList<ComponentRefModel>();
}
- public void addCharacterData(String cData) throws SAXException {
+ @Override
+ public void addCharacterData(final String cData) throws SAXException {
}
- public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
- components.add((ComponentRefModel)child);
+ @Override
+ public void addChild(final XmlMarshallable child, final QName tagName) throws SAXException {
+ this.components.add((ComponentRefModel) child);
}
- public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ @Override
+ public XmlMarshallable getAttributes(final XmlAttributes attributes) throws SAXException {
return this;
}
- public void marshall(XmlOutputter output) {
+ @Override
+ public void marshall(final XmlOutputter output) {
output.startTag(TAG);
- for(int i=0;i<components.size();i++) components.get(i).marshall(output);
+ for (int i = 0; i < this.components.size(); i++) {
+ this.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();
+ for (final ComponentRefModel componentRefModel : this.components) {
+ componentRefModel.validate();
+ }
}
+
+ @Override
public RequireModel clone() {
- RequireModel rm = new RequireModel(QN);
- for(Iterator<ComponentRefModel> it=components.iterator();it.hasNext();)
- rm.components.add(it.next());
+ final RequireModel rm = new RequireModel(QN);
+ for (final ComponentRefModel componentRefModel : this.components) {
+ rm.components.add(componentRefModel);
+ }
return rm;
}
public ArrayList<ComponentRefModel> getComponents() {
- return components;
+ return this.components;
}
- public void setComponents(ArrayList<ComponentRefModel> components) {
+ public void setComponents(final ArrayList<ComponentRefModel> components) {
this.components = components;
}
- public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
- return null;
- }
+ @Override
+ public XmlMarshallable getChildToModify(final String uri, final String localName, final String qName, final Attributes atts) {
+ return null;
+ }
- public QName getQName() {
- return QN;
- }
+ @Override
+ public QName getQName() {
+ return QN;
+ }
}
package fr.gouv.finances.cp.xemelios.updater.config;
-import fr.gouv.finances.dgfip.xemelios.common.config.TexteModel;
+import javax.xml.namespace.QName;
+
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;
+import fr.gouv.finances.dgfip.xemelios.common.config.TexteModel;
public class SiteModel extends TexteModel {
public static final transient String TAG = "site";
- public static final transient QName QN = new QName(TAG);
+ public static final transient QName QN = new QName(TAG);
private String name;
- public SiteModel(QName tagName) {
+ public SiteModel(final QName tagName) {
super(tagName);
}
@Override
- public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
- name=attributes.getValue("name");
+ public XmlMarshallable getAttributes(final XmlAttributes attributes) throws SAXException {
+ this.name = attributes.getValue("name");
return this;
}
@Override
- public void marshall(XmlOutputter output) {
+ public void marshall(final XmlOutputter output) {
output.startTag(TAG);
- output.addAttribute("name",name);
- output.addCharacterData(getText());
+ output.addAttribute("name", this.name);
+ output.addCharacterData(this.getText());
output.endTag(TAG);
}
@Override
public SiteModel clone() {
// TODO Auto-generated method stub
- SiteModel sm = new SiteModel(QN);
- sm.name=this.name;
+ final SiteModel sm = new SiteModel(QN);
+ sm.name = this.name;
try {
- sm.addCharacterData(getText());
- } catch(Throwable t) {}
+ sm.addCharacterData(this.getText());
+ } catch (final Throwable t) {
+ }
return sm;
}
public String getName() {
- return name;
+ return this.name;
}
- public void setName(String name) {
+ public void setName(final String name) {
this.name = name;
}
-
}
package fr.gouv.finances.cp.xemelios.updater.config;
-import fr.gouv.finances.dgfip.xemelios.common.config.TexteModel;
import java.util.HashMap;
+import javax.xml.namespace.QName;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshalParser;
import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
-import javax.xml.namespace.QName;
+import fr.gouv.finances.dgfip.xemelios.common.config.TexteModel;
public class UpdateParser extends XmlMarshalParser {
public UpdateParser() throws SAXException, ParserConfigurationException, FactoryConfigurationError {
- super(new Mapping(),true,FactoryProvider.getSaxParserFactory());
+ super(new Mapping(), true, FactoryProvider.getSaxParserFactory());
}
- private static class Mapping extends HashMap<QName,Class> {
+
+ 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);
+ this.put(ComponentModel.QN, ComponentModel.class);
+ this.put(ComponentRefModel.QN, ComponentRefModel.class);
+ this.put(FileListModel.QN, FileListModel.class);
+ this.put(FileModel.QN, FileModel.class);
+ this.put(ForeignSitesModel.QN, ForeignSitesModel.class);
+ this.put(ReleaseModel.QN, ReleaseModel.class);
+ this.put(RequireModel.QN, RequireModel.class);
+ this.put(SiteModel.QN, SiteModel.class);
+ this.put(XemeliosUpdateModel.QN, XemeliosUpdateModel.class);
+ this.put(ORIGINAL_LOCATION, TexteModel.class);
+ this.put(DESCRIPTION, TexteModel.class);
+ this.put(XEMELIOS_UPDATES, UpdatePartModel.class);
+ this.put(CONFIG_UPDATES, UpdatePartModel.class);
+ this.put(FEATURES_UPDATES, UpdatePartModel.class);
+ this.put(DeleteModel.QN, DeleteModel.class);
+ this.put(ConfigurationModel.QN, ConfigurationModel.class);
+ this.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");
+
+ 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");
}
package fr.gouv.finances.cp.xemelios.updater.config;
import java.util.ArrayList;
-import java.util.Iterator;
+
+import javax.xml.namespace.QName;
import org.xml.sax.Attributes;
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 UpdatePartModel implements XmlMarshallable {
- private String tag;
- private QName qn;
+ private final String tag;
+ private final QName qn;
private ArrayList<ComponentModel> components;
- public UpdatePartModel(QName tagName) {
+
+ public UpdatePartModel(final QName tagName) {
super();
- this.qn=tagName;
- this.tag=qn.getLocalPart();
- components = new ArrayList<ComponentModel>();
+ this.qn = tagName;
+ this.tag = this.qn.getLocalPart();
+ this.components = new ArrayList<ComponentModel>();
}
- public void addCharacterData(String cData) throws SAXException {
+ @Override
+ public void addCharacterData(final String cData) throws SAXException {
}
- public void addChild(XmlMarshallable child, QName tagName) throws SAXException {
- components.add((ComponentModel)child);
+ @Override
+ public void addChild(final XmlMarshallable child, final QName tagName) throws SAXException {
+ this.components.add((ComponentModel) child);
}
- public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ @Override
+ public XmlMarshallable getAttributes(final 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);
+ @Override
+ public void marshall(final XmlOutputter output) {
+ output.startTag(this.tag);
+ for (final ComponentModel componentModel : this.components) {
+ componentModel.marshall(output);
+ }
+ output.endTag(this.tag);
}
+ @Override
public void validate() throws InvalidXmlDefinition {
}
+
+ @Override
public UpdatePartModel clone() {
- UpdatePartModel upm = new UpdatePartModel(getQName());
- for(Iterator<ComponentModel> it=components.iterator();it.hasNext();)
- upm.components.add(it.next());
+ final UpdatePartModel upm = new UpdatePartModel(this.getQName());
+ for (final ComponentModel componentModel : this.components) {
+ upm.components.add(componentModel);
+ }
return upm;
}
public ArrayList<ComponentModel> getComponents() {
- return components;
+ return this.components;
}
- public void setComponents(ArrayList<ComponentModel> components) {
+ public void setComponents(final ArrayList<ComponentModel> components) {
this.components = components;
}
- public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
- return null;
- }
+ @Override
+ public XmlMarshallable getChildToModify(final String uri, final String localName, final String qName, final Attributes atts) {
+ return null;
+ }
- public QName getQName() {
- return qn;
- }
+ @Override
+ public QName getQName() {
+ return this.qn;
+ }
}
package fr.gouv.finances.cp.xemelios.updater.config;
-import fr.gouv.finances.dgfip.xemelios.common.config.TexteModel;
+import javax.xml.namespace.QName;
+
import org.xml.sax.Attributes;
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;
+import fr.gouv.finances.dgfip.xemelios.common.config.TexteModel;
public class XemeliosUpdateModel implements XmlMarshallable {
public static final transient String TAG = "xemelios-update";
- public static final transient QName QN = new QName(TAG);
-
+ 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) {
+ public XemeliosUpdateModel(final QName tag) {
super();
}
- public void addCharacterData(String cData) throws SAXException {
+ @Override
+ public void addCharacterData(final 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;
+ @Override
+ public void addChild(final XmlMarshallable child, final QName tagName) throws SAXException {
+ if (ReleaseModel.QN.equals(tagName)) {
+ this.release = (ReleaseModel) child;
+ } else if (UpdateParser.ORIGINAL_LOCATION.equals(tagName)) {
+ this.originalLocation = (TexteModel) child;
+ } else if (UpdateParser.XEMELIOS_UPDATES.equals(tagName)) {
+ this.xemeliosUpdates = (UpdatePartModel) child;
+ } else if (UpdateParser.CONFIG_UPDATES.equals(tagName)) {
+ this.configUpdates = (UpdatePartModel) child;
+ } else if (UpdateParser.FEATURES_UPDATES.equals(tagName)) {
+ this.featuresUpdates = (UpdatePartModel) child;
+ } else if (ForeignSitesModel.QN.equals(tagName)) {
+ this.foreignSites = (ForeignSitesModel) child;
+ }
}
- public XmlMarshallable getAttributes(XmlAttributes attributes) throws SAXException {
+ @Override
+ public XmlMarshallable getAttributes(final XmlAttributes attributes) throws SAXException {
return this;
}
- public void marshall(XmlOutputter output) {
+ @Override
+ public void marshall(final 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);
+ if (this.release != null) {
+ this.release.marshall(output);
+ }
+ if (this.originalLocation != null) {
+ this.originalLocation.marshall(output);
+ }
+ if (this.xemeliosUpdates != null) {
+ this.xemeliosUpdates.marshall(output);
+ }
+ if (this.configUpdates != null) {
+ this.configUpdates.marshall(output);
+ }
+ if (this.featuresUpdates != null) {
+ this.featuresUpdates.marshall(output);
+ }
+ if (this.foreignSites != null) {
+ this.foreignSites.marshall(output);
+ }
output.endTag(TAG);
}
+ @Override
public void validate() throws InvalidXmlDefinition {
- if(release==null) throw new InvalidXmlDefinition("element release is mandatory for element "+TAG);
+ if (this.release == null) {
+ throw new InvalidXmlDefinition("element release is mandatory for element " + TAG);
+ }
}
+
+ @Override
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();
+ final XemeliosUpdateModel xu = new XemeliosUpdateModel(QN);
+ xu.release = this.release.clone();
+ if (this.originalLocation != null) {
+ xu.originalLocation = this.originalLocation.clone();
+ }
+ if (this.xemeliosUpdates != null) {
+ xu.xemeliosUpdates = this.xemeliosUpdates.clone();
+ }
+ if (this.configUpdates != null) {
+ xu.configUpdates = this.configUpdates.clone();
+ }
+ if (this.featuresUpdates != null) {
+ xu.featuresUpdates = this.featuresUpdates.clone();
+ }
+ if (this.foreignSites != null) {
+ xu.foreignSites = this.foreignSites.clone();
+ }
return xu;
}
public UpdatePartModel getConfigUpdates() {
- return configUpdates;
+ return this.configUpdates;
}
- public void setConfigUpdates(UpdatePartModel configUpdates) {
+ public void setConfigUpdates(final UpdatePartModel configUpdates) {
this.configUpdates = configUpdates;
}
public UpdatePartModel getFeaturesUpdates() {
- return featuresUpdates;
+ return this.featuresUpdates;
}
- public void setFeaturesUpdates(UpdatePartModel featuresUpdates) {
+ public void setFeaturesUpdates(final UpdatePartModel featuresUpdates) {
this.featuresUpdates = featuresUpdates;
}
public ForeignSitesModel getForeignSites() {
- return foreignSites;
+ return this.foreignSites;
}
- public void setForeignSites(ForeignSitesModel foreignSites) {
+ public void setForeignSites(final ForeignSitesModel foreignSites) {
this.foreignSites = foreignSites;
}
public TexteModel getOriginalLocation() {
- return originalLocation;
+ return this.originalLocation;
}
- public void setOriginalLocation(TexteModel originalLocation) {
+ public void setOriginalLocation(final TexteModel originalLocation) {
this.originalLocation = originalLocation;
}
public ReleaseModel getRelease() {
- return release;
+ return this.release;
}
- public void setRelease(ReleaseModel release) {
+ public void setRelease(final ReleaseModel release) {
this.release = release;
}
public UpdatePartModel getXemeliosUpdates() {
- return xemeliosUpdates;
+ return this.xemeliosUpdates;
}
- public void setXemeliosUpdates(UpdatePartModel xemeliosUpdates) {
+ public void setXemeliosUpdates(final UpdatePartModel xemeliosUpdates) {
this.xemeliosUpdates = xemeliosUpdates;
}
- public XmlMarshallable getChildToModify(String uri, String localName, String qName, Attributes atts) {
- return null;
- }
+ @Override
+ public XmlMarshallable getChildToModify(final String uri, final String localName, final String qName, final Attributes atts) {
+ return null;
+ }
- public QName getQName() {
- return QN;
- }
+ @Override
+ public QName getQName() {
+ return QN;
+ }
}
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.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;
+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;
+
public class InstalledModel implements XmlMarshallable {
- private static Logger logger = Logger.getLogger(InstalledModel.class);
+ 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 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) {} }
- }
+ private String fileLocation;
+ public static final transient String ALLREADY_EXISTS = "ALLREADY_EXISTS";
+
+ public InstalledModel(final ArrayList<ComponentModel> components, final ArrayList<ProfilModel> profils) {
+ super();
+ this.components = components;
+ this.profils = profils;
+ }
+
+ public InstalledModel(final QName tagName) {
+ super();
+ this.profils = new ArrayList<ProfilModel>();
+ this.components = new ArrayList<ComponentModel>();
+ }
+
+ public static InstalledModel readFromFile(final String fileLocation) throws SAXException, ParserConfigurationException, IOException, Exception {
+ if (fileLocation == null) {
+ throw new Exception("fichier non renseigné");
+ }
+ final InstalledParser ip = new InstalledParser();
+ ip.parse(fileLocation);
+ final 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(final String fileLocation, final ProfilModel pm) throws SAXException, ParserConfigurationException, IOException, Exception {
+ final InstalledModel im = InstalledModel.readFromFile(fileLocation);
+ // check si profil déja abonné, on return si c'est le cas
+ // sans throw une exception utilisateur
+ for (final ProfilModel p : im.getProfils()) {
+ if (p.getId().equals(pm.getId())) {
+ return;
+ }
+ }
+ im.profils.add(pm);
+ im.saveInstalledModel(fileLocation);
+ }
+
+ public void addProfil(final ProfilModel pm) {
+ for (final ProfilModel p : this.profils) {
+ if (p.getId().equals(pm.getId())) {
+ return;
+ }
+ }
+ this.profils.add(pm);
+ }
+
+ public void setFileLocation(final String fileLocation) {
+ this.fileLocation = fileLocation;
+ }
+
+ public String getFileLocation() {
+ return this.fileLocation;
+ }
+
+ public ArrayList<ComponentModel> getComponents() {
+ return this.components;
+ }
+
+ public ArrayList<ProfilModel> getProfils() {
+ return this.profils;
+ }
+
+ public void setComponents(final ArrayList<ComponentModel> components) {
+ this.components = components;
+ }
+
+ public void setProfils(final ArrayList<ProfilModel> profils) {
+ this.profils = profils;
+ }
+
+ @Override
+ public void addCharacterData(final String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(final XmlMarshallable child, final QName tag) throws SAXException {
+ if (ComponentModel.QN.equals(tag)) {
+ this.components.add((ComponentModel) child);
+ }
+ if (ProfilModel.QN.equals(tag)) {
+ this.profils.add((ProfilModel) child);
+ }
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(final XmlAttributes attributes) throws SAXException {
+ return this;
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(final String uri, final String localName, final String qName, final Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public void marshall(final XmlOutputter output) {
+ output.startTag(TAG);
+ for (final ComponentModel cm : this.components) {
+ cm.marshall(output);
+ }
+ for (final ProfilModel pm : this.profils) {
+ pm.marshall(output);
+ }
+ output.endTag(TAG);
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ for (final ComponentModel cm : this.components) {
+ cm.validate();
+ }
+ for (final ProfilModel pm : this.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(final String id) {
+ if (id == null) {
+ return NOT_FOUND;
+ }
+ for (int idx = 0; idx < this.profils.size(); idx++) {
+ if (this.profils.get(idx).getId().equals(id)) {
+ return idx;
+ }
+ }
+ return NOT_FOUND;
+ }
+
+ public ComponentModel getComponent(final String URI) {
+ if (URI == null) {
+ return null;
+ }
+ for (final ComponentModel cm : this.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(final String URI) {
+ if (URI == null) {
+ return NOT_FOUND;
+ }
+ for (int idx = 0; idx < this.components.size(); idx++) {
+ if (this.components.get(idx).getUri().equals(URI)) {
+ return idx;
+ }
+ }
+ return NOT_FOUND;
+ }
+
+ public int getComponentIdx(final UUID uuid) {
+ if (uuid == null) {
+ return NOT_FOUND;
+ }
+ for (int idx = 0; idx < this.components.size(); idx++) {
+ if (this.components.get(idx).getUUID().equals(uuid)) {
+ return idx;
+ }
+ }
+ return NOT_FOUND;
+ }
+
+ public boolean removeComponent(final UUID uuid) {
+ if (uuid == null) {
+ return false;
+ }
+ for (int idx = 0; idx < this.components.size(); idx++) {
+ if (this.components.get(idx).getUUID().equals(uuid)) {
+ this.components.remove(idx);
+ return true;
+ }
+ }
+ return true;
+ }
+
+ public boolean removeComponent(final String URI) {
+ if (URI == null) {
+ return false;
+ }
+ for (int idx = 0; idx < this.components.size(); idx++) {
+ if (this.components.get(idx).getUri().equals(URI)) {
+ this.components.remove(idx);
+ }
+ }
+ return true;
+ }
+
+ public boolean removeProfil(final String id) {
+ if (id == null) {
+ return false;
+ }
+ for (int idx = 0; idx < this.profils.size(); idx++) {
+ if (this.profils.get(idx).getId().equals(id)) {
+ this.profils.remove(idx);
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Ajoute le composant passé en paramètre
+ *
+ * @param cm
+ * @throws Exception
+ */
+ public void addComponent(final ComponentModel cm) throws Exception {
+ for (int idx = 0; idx < this.components.size(); idx++) {
+ if (this.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(final ComponentModel cm) {
+ for (int idx = 0; idx < this.components.size(); idx++) {
+ if (this.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 (this.fileLocation == null) {
+ throw new Exception("fichier de sortie non renseigné.");
+ }
+ this.saveInstalledModel(this.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(final String fileLocation) throws IOException {
+ final Charset cs = Charset.forName("ISO-8859-1");
+ final File fo = new File(fileLocation);
+ this.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(final String fo, final String cs) throws IOException {
+ this.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(final File fo, final Charset cs) throws IOException {
+ FileOutputStream fos = null;
+ try {
+ fos = new FileOutputStream(fo);
+ final OutputStreamWriter osw = new OutputStreamWriter(fos, cs);
+ final XmlOutputter xo = new XmlOutputter(osw, cs.name());
+ this.marshall(xo);
+ osw.flush();
+ osw.close();
+ } catch (final IOException ex) {
+ logger.debug(ex);
+ throw ex;
+ } finally {
+ try {
+ fos.close();
+ } catch (final Throwable t) {
+ }
+ }
+ }
}
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;
+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;
+
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);
- }
- }
+ public InstalledParser(final 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() {
+ this.put(InstalledModel.QN, InstalledModel.class);
+ this.put(ProfilModel.QN, ProfilModel.class);
+ this.put(ComponentModel.QN, ComponentModel.class);
+ }
+ }
}
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 fr.gouv.finances.cp.xemelios.updater.UpdateUtil;
import java.util.UUID;
+import javax.xml.namespace.QName;
+
+import org.apache.log4j.Logger;
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.UpdateUtil;
//~--- 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;
- }
-
- public boolean isNewerOrEqualThan(String otherVersion) {
- return UpdateUtil.compareReleases(version, otherVersion)>=0;
- }
+ 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();
+ this.internal_uuid = UUID.randomUUID();
+ }
+
+ public ComponentModel(final QName QN) {
+ super();
+ this.internal_uuid = UUID.randomUUID();
+ }
+
+ public ComponentModel(final String uri) {
+ this(QN);
+ this.uri = uri;
+ this.internal_uuid = UUID.randomUUID();
+ }
+
+ public ComponentModel(final String uri, final String version, final String description, final boolean editable) {
+ this(QN);
+ this.uri = uri;
+ this.version = version;
+ this.description = description;
+ this.editable = (editable ? "true" : "false");
+ this.internal_uuid = UUID.randomUUID();
+ }
+
+ public UUID getUUID() {
+ return this.internal_uuid;
+ }
+
+ public String getUri() {
+ return this.uri;
+ }
+
+ public String getDescription() {
+ return this.description;
+ }
+
+ public String getVersion() {
+ return this.version;
+ }
+
+ public void setDescription(final String description) {
+ this.description = description;
+ }
+
+ public void setUri(final String uri) {
+ this.uri = uri;
+ }
+
+ public void setVersion(final String version) {
+ this.version = version;
+ }
+
+ public boolean isEditable() {
+ return "true".equals(this.editable);
+ }
+
+ public void setEditable(final boolean editable) {
+ this.editable = (editable ? "true" : "false");
+ }
+
+ @Override
+ public void addCharacterData(final String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(final XmlMarshallable child, final QName tag) throws SAXException {
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(final XmlAttributes attributes) throws SAXException {
+ this.uri = attributes.getValue("uri");
+ this.version = attributes.getValue("version");
+ this.description = attributes.getValue("description");
+ this.editable = attributes.getValue("editable");
+ return this;
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(final String uri, final String localName, final String qName, final Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public void marshall(final XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("uri", this.uri);
+ if (this.version != null) {
+ output.addAttribute("version", this.version);
+ }
+ if (this.description != null) {
+ output.addAttribute("description", this.description);
+ }
+ if (this.editable != null) {
+ output.addAttribute("editable", this.editable);
+ }
+ output.endTag(TAG);
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ if (this.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(final Object other) {
+ if (other instanceof ComponentModel) {
+ return this.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;
+ }
+
+ public boolean isNewerOrEqualThan(final String otherVersion) {
+ return UpdateUtil.compareReleases(this.version, otherVersion) >= 0;
+ }
}
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.ArrayList;
+import javax.xml.namespace.QName;
+
+import org.apache.log4j.Logger;
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;
//~--- 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;
- }
-
+ 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(final QName tagName) {
+ super();
+ this.required = false;
+ this.disabled = false;
+ this.visible = true;
+ this.components = new ArrayList<ComponentModel>();
+ this.dontWriteOptionalAttributes = false;
+ }
+
+ public ProfilModel(final String id, final String description, final boolean required, final boolean disabled, final boolean visible, final 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(final String id, final 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(final boolean dontWriteOptionalAttributes) {
+ this.dontWriteOptionalAttributes = dontWriteOptionalAttributes;
+ }
+
+ @Override
+ public void addCharacterData(final String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(final XmlMarshallable child, final QName tagName) throws SAXException {
+ final ComponentModel cm = (ComponentModel) child;
+ this.components.add(cm);
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(final XmlAttributes attributes) throws SAXException {
+ this.id = attributes.getValue("id");
+ this.description = attributes.getValue("description");
+ this.required = ((attributes.getValue("required") != null) ? attributes.getValue("required").equals("true") : false);
+ this.disabled = ((attributes.getValue("disabled") != null) ? attributes.getValue("disabled").equals("true") : false);
+ this.visible = ((attributes.getValue("visible") != null) ? attributes.getValue("visible").equals("true") : true);
+
+ return this;
+ }
+
+ @Override
+ public void marshall(final XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("id", this.id);
+ output.addAttribute("description", this.description);
+ if (!this.dontWriteOptionalAttributes) {
+ output.addAttribute("required", (this.required ? "true" : "false"));
+ output.addAttribute("disabled", (this.disabled ? "true" : "false"));
+ output.addAttribute("visible", (this.visible ? "true" : "false"));
+ }
+ for (final ComponentModel cm : this.components) {
+ cm.marshall(output);
+ }
+ output.endTag(TAG);
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ if (this.id == null) {
+ throw new InvalidXmlDefinition("id attribute is mandatory for element " + TAG);
+ }
+ for (final ComponentModel cm : this.components) {
+ cm.validate();
+ }
+ }
+
+ @Override
+ public ProfilModel clone() {
+ final ProfilModel m = new ProfilModel(QN);
+ m.description = this.description;
+ m.disabled = this.disabled;
+ m.id = this.id;
+ m.required = this.required;
+ m.visible = this.visible;
+ for (final ComponentModel cm : this.components) {
+ m.components.add(cm.clone());
+ }
+ return m;
+ }
+
+ public ArrayList<ComponentModel> getComponents() {
+ return this.components;
+ }
+
+ public String getDescription() {
+ return this.description;
+ }
+
+ public String getId() {
+ return this.id;
+ }
+
+ public boolean isDisabled() {
+ return this.disabled;
+ }
+
+ public boolean isRequired() {
+ return this.required;
+ }
+
+ public boolean isVisible() {
+ return this.visible;
+ }
+
+ public void setComponents(final ArrayList<ComponentModel> components) {
+ this.components = components;
+ }
+
+ public void setDescription(final String description) {
+ this.description = description;
+ }
+
+ public void setDisabled(final boolean disabled) {
+ this.disabled = disabled;
+ }
+
+ public void setId(final String id) {
+ this.id = id;
+ }
+
+ public void setRequired(final boolean required) {
+ this.required = required;
+ }
+
+ public void setVisible(final boolean visible) {
+ this.visible = visible;
+ }
+
+ @Override
+ public boolean equals(final Object o) {
+ if (o instanceof ProfilModel) {
+ final ProfilModel m = (ProfilModel) o;
+ return m.getId().equals(this.getId());
+ }
+ return false;
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(final String uri, final String localName, final String qName, final Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
+
+ @Override
+ public String toString() {
+ return "id=" + this.id + "/description=" + this.description + "/disabled=" + this.disabled + "/required=" + this.required + "/visible=" + this.visible;
+ }
}
*/
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 {
+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;
- 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;
- }
+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 final ArrayList<ProfilModel> profils;
+ private boolean dontWriteOptionalAttributes = false;
+
+ public ProfilsModel(final QName tagName) {
+ super();
+ this.profils = new ArrayList<ProfilModel>();
+ }
+
+ private ProfilsModel() {
+ super();
+ this.profils = new ArrayList<ProfilModel>();
+ }
+
+ public void setDontWriteOptionalAttributes(final boolean dontWriteOptionalAttributes) {
+ this.dontWriteOptionalAttributes = dontWriteOptionalAttributes;
+ }
+
+ @Override
+ public void addCharacterData(final String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(final XmlMarshallable child, final QName tag) throws SAXException {
+ final ProfilModel pm = (ProfilModel) child;
+ this.profils.add(pm);
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(final XmlAttributes attributes) throws SAXException {
+ return this;
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(final String uri, final String localName, final String qName, final Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public void marshall(final XmlOutputter output) {
+ output.startTag(TAG);
+ for (final ProfilModel pm : this.profils) {
+ pm.setDontWriteOptionalAttributes(this.dontWriteOptionalAttributes);
+ pm.marshall(output);
+ }
+ output.endTag(TAG);
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ for (final ProfilModel pm : this.profils) {
+ pm.validate();
+ }
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
+
+ @Override
+ public ProfilsModel clone() {
+ return this;
+ }
+
+ public ArrayList<ProfilModel> getProfils() {
+ return this.profils;
+ }
+
+ public int getIdxById(final String id) {
+ for (int idx = 0; idx < this.profils.size(); idx++) {
+ if (this.profils.get(idx).getId().equals(id)) {
+ return idx;
+ }
+ }
+ return NOT_FOUND;
+ }
+
+ public static ProfilsModel loadModel(final String urlLocation, final HttpClient client) throws Exception {
+ ProfilsModel pms = new ProfilsModel();
+ try {
+ logger.debug("urlLocation=" + urlLocation);
+ final GetMethod meth = new GetMethod(urlLocation);
+ meth.addRequestHeader("Pragma", "no-cache");
+ final int httpRet = client.executeMethod(meth);
+ if (httpRet > 300) {
+ throw new Exception("URL urlLocation " + urlLocation + " : " + meth.getStatusText());
+ }
+ final InputStream is = meth.getResponseBodyAsStream();
+ final ProfilsParser pp = new ProfilsParser();
+ pp.parse(is);
+ is.close();
+ pms = (ProfilsModel) pp.getMarshallable();
+ return pms;
+ } catch (final Exception ex) {
+ logger.error(ex);
+ throw ex;
+ }
+ }
+
+ public static ProfilsModel loadModel(final String urlLocation) throws Exception {
+ return loadModel(urlLocation, NetAccess.getHttpClient(MainWindow.getInstance().getEnvProperties()));
+ }
+
+ @Override
+ public String toString() {
+ String strReturn = "";
+ for (final ProfilModel pm : this.profils) {
+ strReturn = strReturn.concat("\n" + pm.toString());
+ }
+ return strReturn;
+ }
}
* 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;
+import org.xml.sax.SAXException;
+
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshalParser;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
+//~--- JDK imports ------------------------------------------------------------
+
/**
*
*
*/
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);
- }
- }
+ public static final transient QName XEMELIOS_PROFILS = new QName("xemelios-profils");
+
+ public ProfilsParser(final 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() {
+ this.put(XEMELIOS_PROFILS, ProfilsModel.class);
+ this.put(ProfilModel.QN, ProfilModel.class);
+ this.put(ComponentModel.QN, ComponentModel.class);
+ }
+ }
}
import fr.gouv.finances.cp.xemelios.updater.config.FileListModel;
/**
- *
- * @author chm
+ *
+ * @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
-
+ private final ComponentModel cm;
+
+ /** Creates new form NewJDialog */
+ public DlgComponentDetail(final JDialog parent, final ComponentModel cm) {
+ super(parent, false);
+ this.cm = cm;
+ this.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() {
+ this.lblName = new javax.swing.JLabel();
+ this.vlName = new javax.swing.JLabel();
+ this.lblId = new javax.swing.JLabel();
+ this.lblVersion = new javax.swing.JLabel();
+ this.lblDesc = new javax.swing.JLabel();
+ this.jScrollPane1 = new javax.swing.JScrollPane();
+ this.txtDesc = new javax.swing.JTextArea();
+ this.lblDepends = new javax.swing.JLabel();
+ this.jScrollPane2 = new javax.swing.JScrollPane();
+ this.lstDepends = new javax.swing.JList();
+ this.vlId = new javax.swing.JLabel();
+ this.vlVersion = new javax.swing.JLabel();
+ this.lblFiles = new javax.swing.JLabel();
+ this.jScrollPane3 = new javax.swing.JScrollPane();
+ this.lstFiles = new javax.swing.JList();
+ this.pbClose = new javax.swing.JButton();
+
+ this.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+ this.lblName.setText("Nom");
+
+ this.vlName.setFont(new java.awt.Font("Dialog", 0, 12));
+ this.vlName.setText(this.cm.getName());
+
+ this.lblId.setText("ID");
+
+ this.lblVersion.setText("Version");
+
+ this.lblDesc.setText("Description");
+
+ this.jScrollPane1.setBackground(javax.swing.UIManager.getDefaults().getColor("PropSheet.setBackground"));
+ this.jScrollPane1.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
+ this.txtDesc.setBackground(javax.swing.UIManager.getDefaults().getColor("ComboBox.background"));
+ this.txtDesc.setColumns(20);
+ this.txtDesc.setEditable(false);
+ this.txtDesc.setLineWrap(true);
+ this.txtDesc.setWrapStyleWord(true);
+ this.txtDesc.setRows(5);
+ this.txtDesc.setText(this.cm.getDescription().getText());
+ this.jScrollPane1.setViewportView(this.txtDesc);
+ this.lblConfig = new javax.swing.JLabel();
+ this.dfConfiguration = new javax.swing.JTextField();
+
+ this.lblDepends.setText("Dépendances");
+
+ this.lstDepends.setFont(new java.awt.Font("Dialog", 0, 12));
+ if (this.cm.getRequires() != null && this.cm.getRequires().getComponents() != null) {
+ this.lstDepends.setListData(this.cm.getRequires().getComponents().toArray());
+ }
+ this.jScrollPane2.setViewportView(this.lstDepends);
+
+ this.vlId.setFont(new java.awt.Font("Dialog", 0, 12));
+ this.vlId.setText(this.cm.getId());
+
+ this.vlVersion.setFont(new java.awt.Font("Dialog", 0, 12));
+ this.vlVersion.setText(this.cm.getRelease().getV());
+
+ this.lblFiles.setText("Fichiers");
+
+ this.lstFiles.setFont(new java.awt.Font("Dialog", 0, 12));
+ final Vector<XmlMarshallable> files = new Vector<XmlMarshallable>();
+ for (final FileListModel flm : this.cm.getFileLists()) {
+ for (final XmlMarshallable fm : flm.getFiles()) {
+ files.add(fm);
+ }
+ }
+ this.lstFiles.setListData(files);
+ this.jScrollPane3.setViewportView(this.lstFiles);
+
+ this.pbClose.setText("Fermer");
+ this.pbClose.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ DlgComponentDetail.this.setVisible(false);
+ }
+ });
+
+ this.lblConfig.setText("Configurateur");
+
+ this.dfConfiguration.setEditable(false);
+ this.dfConfiguration.setText(this.cm.getConfiguration() != null && this.cm.getConfiguration().getClassName() != null ? this.cm.getConfiguration().getClassName() : "N/A");
+
+ final org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this.getContentPane());
+ this.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(this.lblName).add(this.lblId).add(this.lblVersion))
+ .add(17, 17, 17)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(this.jScrollPane3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE).add(this.jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE)
+ .add(this.jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE).add(this.vlVersion).add(this.vlId).add(this.vlName).add(this.dfConfiguration, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE)).addContainerGap())
+ .add(layout.createSequentialGroup().addContainerGap().add(this.lblConfig).addContainerGap(244, Short.MAX_VALUE)).add(layout.createSequentialGroup().addContainerGap().add(this.lblFiles).addContainerGap(283, Short.MAX_VALUE))
+ .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup().add(130, 130, 130).add(this.pbClose).add(136, 136, 136)).add(layout.createSequentialGroup().add(12, 12, 12).add(this.lblDesc).addContainerGap(259, Short.MAX_VALUE))
+ .add(layout.createSequentialGroup().addContainerGap().add(this.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(this.lblName).add(this.vlName)).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE).add(this.lblId).add(this.vlId)).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE).add(this.lblVersion).add(this.vlVersion)).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.lblDesc).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(this.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(this.lblDepends)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 89, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.lblFiles)
+ .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(this.jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 93, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE).add(8, 8, 8).add(this.lblConfig).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
+ .add(this.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(this.pbClose)
+ .addContainerGap()));
+ this.pack();
+ this.setLocationRelativeTo(this.getOwner());
+ this.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
+
}
*/
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.JFrame;
+import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
+
+import org.apache.log4j.Logger;
import org.w3c.dom.Document;
+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;
+
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
+ private AbstractAction escapeAction;
+ private final ComponentModel cm;
+ private UpdateModel um;
+ private static Logger logger = Logger.getLogger(DlgComposantEdition.class);
+ private String InstalledModelFileLocation;
+ private String environement;
+ private InstalledModel im;
+
+ public DlgComposantEdition(final JFrame parent, final ComponentModel cm) {
+ super(parent, true);
+ this.cm = cm;
+ this.initComponents();
+ this.jTextFieldSite.setText(cm.getUri());
+ this.jLabelDescription.setText(cm.getDescription());
+ this.jButtonEnregistrer.setEnabled(false);
+ }
+
+ @Override
+ protected JRootPane createRootPane() {
+ final KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
+ final JRootPane rp = new JRootPane();
+ this.escapeAction = new AbstractAction("Fermer") {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ DlgComposantEdition.this.jButtonFermerActionPerformed(evt);
+ }
+ };
+ rp.registerKeyboardAction(this.escapeAction, "TOTOTOTO", ks, JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
+ }
+
+ public void setInstalledModelFileLocation(final String InstalledModelFileLocation) {
+ this.InstalledModelFileLocation = InstalledModelFileLocation;
+ try {
+ this.im = InstalledModel.readFromFile(InstalledModelFileLocation);
+ this.im.setFileLocation(InstalledModelFileLocation);
+ } catch (final Exception ex) {
+ logger.error("while loading installedComponents", ex);
+ }
+ }
+
+ public void setEnvironement(final 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() {
+
+ this.jLabel1 = new javax.swing.JLabel();
+ this.jLabel3 = new javax.swing.JLabel();
+ this.jButtonEnregistrer = new javax.swing.JButton();
+ this.jButtonFermer = new javax.swing.JButton();
+ this.jTextFieldSite = new javax.swing.JTextField();
+ this.jButtonRechercher = new javax.swing.JButton();
+ this.jLabelDescription = new javax.swing.JLabel();
+ this.pbSearchExistingComponent = new javax.swing.JButton();
+
+ this.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+
+ this.jLabel1.setFont(this.jLabel1.getFont());
+ this.jLabel1.setText("Site");
+
+ this.jLabel3.setFont(this.jLabel3.getFont());
+ this.jLabel3.setText("Description");
+
+ this.jButtonEnregistrer.setText("Enregistrer");
+ this.jButtonEnregistrer.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgComposantEdition.this.jButtonEnregistrerActionPerformed(evt);
+ }
+ });
+
+ this.jButtonFermer.setText("Fermer");
+ this.jButtonFermer.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgComposantEdition.this.jButtonFermerActionPerformed(evt);
+ }
+ });
+
+ this.jTextFieldSite.setFont(this.jTextFieldSite.getFont());
+
+ this.jButtonRechercher.setText("Rechercher");
+ this.jButtonRechercher.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgComposantEdition.this.jButtonRechercherActionPerformed(evt);
+ }
+ });
+
+ this.jLabelDescription.setText("Description");
+
+ this.pbSearchExistingComponent.setText("...");
+ this.pbSearchExistingComponent.setToolTipText("Rechercher un composant connu");
+ this.pbSearchExistingComponent.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgComposantEdition.this.pbSearchExistingComponentActionPerformed(evt);
+ }
+ });
+
+ final javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this.getContentPane());
+ this.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(this.jLabel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addComponent(this.jLabel3))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(this.jLabelDescription, javax.swing.GroupLayout.DEFAULT_SIZE, 354, Short.MAX_VALUE)
+ .addGroup(layout.createSequentialGroup().addComponent(this.jTextFieldSite, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE).addGap(0, 0, 0).addComponent(this.pbSearchExistingComponent)))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(this.jButtonRechercher))
+ .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addComponent(this.jButtonEnregistrer).addGap(18, 18, 18).addComponent(this.jButtonFermer))).addContainerGap()));
+ layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
+ layout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(this.jLabel1).addComponent(this.jTextFieldSite, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addComponent(this.jButtonRechercher).addComponent(this.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(this.jLabel3).addComponent(this.jLabelDescription)).addGap(44, 44, 44))
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(this.jButtonFermer).addComponent(this.jButtonEnregistrer))).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
+
+ this.pack();
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void jButtonFermerActionPerformed(final 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(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButtonRechercherActionPerformed
+ try {
+ // TODO add your handling code here:
+ final String URI = this.jTextFieldSite.getText();
+ final ComponentModel cml = new ComponentModel(URI);
+ this.um = UpdateModel.loadModel(cml, this.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 (this.cm.getUri() == null) {
+ try {
+ if (this.im.exists(new ComponentModel(URI))) {
+ final String msg = "Composant '" + this.um.getDescription() + "' déjà existant dans la liste des abonnements";
+ JOptionPane.showMessageDialog(this, msg, "Attention", JOptionPane.WARNING_MESSAGE);
+ return;
+ }
+ } catch (final Exception ex) {
+ logger.error(ex);
+ final DisplayExceptionDlg exdlg = new DisplayExceptionDlg(ex);
+ return;
+ }
+ }
+ // TOUT est OK, on prépare les controles pour l'enregistrement
+ this.jLabelDescription.setText(this.um.getDescription());
+ this.jButtonEnregistrer.setEnabled(true);
+ final String msg = "Composant '" + this.um.getDescription() + "' (" + this.um.getLast_version() + ") trouvé";
+ JOptionPane.showMessageDialog(this, msg, "Succès", JOptionPane.INFORMATION_MESSAGE);
+ } catch (final 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(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButtonEnregistrerActionPerformed
+ InstalledModel newInstalledComponents;
+ try {
+ // TODO add your handling code here:
+ newInstalledComponents = InstalledModel.readFromFile(this.InstalledModelFileLocation);
+ newInstalledComponents.setFileLocation(this.InstalledModelFileLocation);
+ } catch (final Exception ex) {
+ logger.error(ex);
+ final DisplayExceptionDlg exdlg = new DisplayExceptionDlg(ex);
+ return;
+ }
+
+ final ComponentModel newcm = new ComponentModel();
+ newcm.setUri(this.jTextFieldSite.getText());
+ newcm.setDescription(this.um.getDescription());
+ newcm.setEditable(true);
+
+ if (this.cm.getUri() != null) {
+ // MODE EDITION, on efface l'ancienne entrée
+ final int old_cm_idx = newInstalledComponents.getComponentIdx(this.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(this.cm.getUri());
+ }
+
+ try {
+ newInstalledComponents.addComponent(newcm);
+ newInstalledComponents.saveInstalledModel();
+ this.setVisible(false);
+ } catch (final Exception ex) {
+ if (!InstalledModel.ALLREADY_EXISTS.equals(ex.getMessage())) {
+ logger.error(ex);
+ final DisplayExceptionDlg exdlg = new DisplayExceptionDlg(ex);
+ }
+ }
+ }// GEN-LAST:event_jButtonEnregistrerActionPerformed
+
+ private void pbSearchExistingComponentActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbSearchExistingComponentActionPerformed
+ final DocumentBuilderFactory domFactory = FactoryProvider.getDocumentBuilderFactory();
+ try {
+ final DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
+ final InputStream is = new URL("http://xemelios.org/updatesV5/existing-components.xml").openStream();
+ final Document dom = domBuilder.parse(is);
+ final DlgExistingComponents dlg = new DlgExistingComponents(this, dom, this.im);
+ if (dlg.run()) {
+ final String url = dlg.getRetUrl();
+ this.jTextFieldSite.setText(url);
+ this.jButtonRechercher.doClick();
+ }
+ is.close();
+ } catch (final 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
}
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;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+
/**
- *
+ *
* @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;
+ private AbstractAction escapeAction;
+
+ public DlgComposants(final java.awt.Frame parent, final boolean modal) {
+ super(parent, modal);
+ this.initComponents();
+ this.setLocationRelativeTo(parent);
+ }
+
+ @Override
+ protected JRootPane createRootPane() {
+ final KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
+ final JRootPane rp = new JRootPane();
+ this.escapeAction = new AbstractAction("Fermer") {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ DlgComposants.this.jButtonFermerActionPerformed(evt);
+ }
+ };
+ rp.registerKeyboardAction(this.escapeAction, "TOTOTOTO", ks, JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
+ }
+
+ private void initComponents() {
+
+ this.jPanel1 = new PnlComposants(MainWindow.getInstance().getEnvProperties());
+ this.jSeparator1 = new javax.swing.JSeparator();
+ this.jButtonFermer = new javax.swing.JButton();
+
+ this.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+
+ final javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(this.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));
+
+ this.jButtonFermer.setText("Fermer");
+ this.jButtonFermer.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgComposants.this.jButtonFermerActionPerformed(evt);
+ }
+ });
+
+ final javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this.getContentPane());
+ this.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(this.jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addComponent(this.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(this.jButtonFermer).addContainerGap()));
+ layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
+ javax.swing.GroupLayout.Alignment.TRAILING,
+ layout.createSequentialGroup().addGap(0, 0, 0).addComponent(this.jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addGap(0, 0, 0)
+ .addComponent(this.jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(this.jButtonFermer).addContainerGap()));
+
+ this.pack();
+ }// </editor-fold>
+
+ private void jButtonFermerActionPerformed(final java.awt.event.ActionEvent evt) {
+ this.setVisible(false);
+ }
+
+ private javax.swing.JButton jButtonFermer;
+ private javax.swing.JPanel jPanel1;
+ private javax.swing.JSeparator jSeparator1;
}
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.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;
+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;
+
/**
* 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();
- }
- }
+ private static final transient Logger logger = Logger.getLogger(DlgExistingComponents.class);
+ ExistingComponentsTableModel model = null;
+ private boolean retAction = false;
+ private String retUrl;
+ private final InstalledModel installed;
+ private final ListSelectionListener listSelectionListener;
+
+ /** Creates new form DlgExistingComponents */
+ public DlgExistingComponents(final JDialog parent, final Document existingComponents, final InstalledModel installed) {
+ super(parent, true);
+ this.installed = installed;
+ this.model = new ExistingComponentsTableModel(this.constructExistingComponents(existingComponents));
+ this.listSelectionListener = new ListSelectionListener() {
+
+ @Override
+ public void valueChanged(final ListSelectionEvent e) {
+ final int row = DlgExistingComponents.this.jXTable1.getSelectedRow();
+ if (row >= 0) {
+ DlgExistingComponents.this.pbSelect.setEnabled(!DlgExistingComponents.this.model.comps.get(row).installed);
+ } else {
+ DlgExistingComponents.this.pbSelect.setEnabled(false);
+ }
+ }
+ };
+ this.initComponents();
+ this.model.fireTableDataChanged();
+ this.setLocationRelativeTo(this.getParent());
+ }
+
+ private ArrayList<ExistingComponent> constructExistingComponents(final Document doc) {
+ final ArrayList<ExistingComponent> ret = new ArrayList<ExistingComponent>();
+ try {
+ final XPath xpath = FactoryProvider.getXPathFactory().newXPath();
+ final NodeList nl = (NodeList) xpath.evaluate("/existing-components/component", doc, XPathConstants.NODESET);
+ for (int i = 0; i < nl.getLength(); i++) {
+ final Element el = (Element) nl.item(i);
+ final ExistingComponent ec = new ExistingComponent(el);
+ ec.installed = this.installed.exists(new ComponentModel(ec.url));
+ ret.add(ec);
+ }
+ } catch (final Exception ex) {
+ logger.error("while constructing model", ex);
+ }
+ return ret;
+ }
+
+ public boolean run() {
+ this.setVisible(true);
+ return this.retAction;
+ }
+
+ @Override
+ protected JRootPane createRootPane() {
+ final KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
+ final JRootPane rp = new JRootPane();
+ final AbstractAction escapeAction = new AbstractAction("Fermer") {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ DlgExistingComponents.this.pbCancelActionPerformed(evt);
+ }
+ };
+ rp.registerKeyboardAction(escapeAction, "TOTOTOTO", ks, JComponent.WHEN_IN_FOCUSED_WINDOW);
+ return rp;
+ }
+
+ public String getRetUrl() {
+ return this.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() {
+
+ this.pbCancel = new javax.swing.JButton();
+ this.pbSelect = new javax.swing.JButton();
+ this.jScrollPane1 = new javax.swing.JScrollPane();
+ this.jXTable1 = this.createTable();
+
+ this.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+
+ this.pbCancel.setText("Fermer");
+ this.pbCancel.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgExistingComponents.this.pbCancelActionPerformed(evt);
+ }
+ });
+
+ this.pbSelect.setText("Sélectionner");
+ this.pbSelect.setEnabled(false);
+ this.pbSelect.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgExistingComponents.this.pbSelectActionPerformed(evt);
+ }
+ });
+
+ this.jXTable1.setModel(this.model);
+ this.jScrollPane1.setViewportView(this.jXTable1);
+
+ final javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this.getContentPane());
+ this.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(this.jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 452, Short.MAX_VALUE)
+ .addGroup(layout.createSequentialGroup().addComponent(this.pbSelect).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(this.pbCancel))).addContainerGap()));
+ layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
+ javax.swing.GroupLayout.Alignment.TRAILING,
+ layout.createSequentialGroup().addGap(13, 13, 13).addComponent(this.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(this.pbCancel).addComponent(this.pbSelect)).addContainerGap()));
+
+ this.pack();
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void pbCancelActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbCancelActionPerformed
+ this.setVisible(false);
+ }// GEN-LAST:event_pbCancelActionPerformed
+
+ private void pbSelectActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pbSelectActionPerformed
+ final int row = this.jXTable1.getSelectedRow();
+ if (row >= 0) {
+ final ExistingComponent ec = this.model.comps.get(row);
+ if (!ec.installed) {
+ this.retAction = true;
+ this.retUrl = ec.url;
+ this.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() {
+ final JXTable table = new JXTable() {
+ @Override
+ public void valueChanged(final ListSelectionEvent e) {
+ super.valueChanged(e);
+ DlgExistingComponents.this.listSelectionListener.valueChanged(e);
+ }
+ };
+ return table;
+ }
+
+ private class ExistingComponentsTableModel extends DefaultTableModel {
+ private final ArrayList<ExistingComponent> comps;
+
+ public ExistingComponentsTableModel(final ArrayList<ExistingComponent> comps) {
+ super();
+ this.comps = comps;
+ }
+
+ @Override
+ public int getRowCount() {
+ if (this.comps == null) {
+ return 0;
+ }
+ return this.comps.size();
+ }
+
+ @Override
+ public Class<?> getColumnClass(final int columnIndex) {
+ if (columnIndex == 0) {
+ return Boolean.class;
+ } else {
+ return String.class;
+ }
+ }
+
+ @Override
+ public String getColumnName(final int column) {
+ switch (column) {
+ case 0:
+ return "Installé";
+ case 1:
+ return "Description";
+ default:
+ return "URL";
+ }
+ }
+
+ @Override
+ public Object getValueAt(final int row, final int column) {
+ final ExistingComponent ec = this.comps.get(row);
+ switch (column) {
+ case 0:
+ return ec.installed;
+ case 1:
+ return ec.description;
+ default:
+ return ec.url;
+ }
+ }
+
+ @Override
+ public boolean isCellEditable(final int row, final int column) {
+ return false;
+ }
+
+ @Override
+ public int getColumnCount() {
+ return 3;
+ }
+
+ }
+
+ private class ExistingComponent {
+ private final String url;
+ private final String description;
+ private boolean installed;
+
+ public ExistingComponent(final Element el) {
+ this.url = el.getElementsByTagName("url").item(0).getTextContent();
+ this.description = el.getElementsByTagName("description").item(0).getTextContent();
+ }
+ }
}
*/
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;
+import fr.gouv.finances.cp.xemelios.updater.profils.ComponentModel;
+import fr.gouv.finances.cp.xemelios.updater.profils.ProfilModel;
+
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
+ private static Logger logger = Logger.getLogger(DlgProfilDetail.class);
+ private final ComposantsTableModel cTableModel = new ComposantsTableModel();
+ private AbstractAction escapeAction;
+
+ public DlgProfilDetail(final Frame owner, final ProfilModel pm) {
+ super(owner, pm.getDescription(), true);
+ this.cTableModel.setComposants(pm.getComponents());
+ this.initComponents();
+ this.jXTableComposants.setShowGrid(false);
+
+ this.jLabelTitre.setText("Liste des composants du profil \"" + pm.getDescription() + "\"");
+ this.setLocationRelativeTo(owner);
+ }
+
+ @Override
+ protected JRootPane createRootPane() {
+ final KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
+ final JRootPane rp = new JRootPane();
+ this.escapeAction = new AbstractAction("Fermer") {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void actionPerformed(final ActionEvent evt) {
+ DlgProfilDetail.this.jButtonFermerActionPerformed(evt);
+ }
+ };
+ rp.registerKeyboardAction(this.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 this.composants.size();
+ }
+
+ @Override
+ public int getColumnCount() {
+ return 1;
+ }
+
+ @Override
+ public Object getValueAt(final int rowIndex, final int columnIndex) {
+ return this.composants.get(rowIndex).getDescription();
+ }
+
+ @Override
+ public Class<?> getColumnClass(final int columnIndex) {
+ return String.class;
+ }
+
+ @Override
+ public String getColumnName(final int column) {
+ return "Description";
+ }
+
+ @Override
+ public boolean isCellEditable(final int rowIndex, final int columnIndex) {
+ return false;
+ }
+
+ public void setComposants(final 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() {
+
+ this.jLabelTitre = new javax.swing.JLabel();
+ this.jScrollPane1 = new javax.swing.JScrollPane();
+ this.jXTableComposants = new org.jdesktop.swingx.JXTable();
+ this.jButtonFermer = new javax.swing.JButton();
+
+ this.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
+
+ this.jLabelTitre.setFont(this.jLabelTitre.getFont().deriveFont(this.jLabelTitre.getFont().getStyle() | java.awt.Font.BOLD));
+ this.jLabelTitre.setText("Liste des composants du profil");
+
+ this.jXTableComposants.setModel(this.cTableModel);
+ this.jScrollPane1.setViewportView(this.jXTableComposants);
+
+ this.jButtonFermer.setText("Fermer");
+ this.jButtonFermer.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ DlgProfilDetail.this.jButtonFermerActionPerformed(evt);
+ }
+ });
+
+ final javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this.getContentPane());
+ this.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(this.jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 417, Short.MAX_VALUE).addComponent(this.jLabelTitre)
+ .addComponent(this.jButtonFermer, javax.swing.GroupLayout.Alignment.TRAILING)).addContainerGap()));
+ layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
+ layout.createSequentialGroup().addContainerGap().addComponent(this.jLabelTitre).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(this.jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 334, Short.MAX_VALUE).addGap(11, 11, 11)
+ .addComponent(this.jButtonFermer).addContainerGap()));
+
+ this.pack();
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void jButtonFermerActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButtonFermerActionPerformed
+ // TODO add your handling code here:
+ this.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
}
*/
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;
+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;
+
/**
* 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 viewRow = jxTableComposants.getSelectedRow();
- if(viewRow != -1) {
- int row = jxTableComposants.convertRowIndexToModel(viewRow);
- // 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 2;
- }
-
- @Override
- public Object getValueAt(int rowIndex, int columnIndex) {
- ComponentModel cm = composants.get(rowIndex);
- switch(columnIndex) {
- case 0: return cm.getDescription();
- default: return cm.getVersion();
- }
-
- }
-
- @Override
- public Class<?> getColumnClass(int columnIndex) {
- return String.class;
- }
-
- @Override
- public String getColumnName(int column) {
- switch(column) {
- case 0: return "Description";
- default: return "Version";
- }
- }
-
- @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 viewRow = jxTableComposants.getSelectedRow();
- int row = jxTableComposants.convertRowIndexToModel(viewRow);
- 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 viewRow = jxTableComposants.getSelectedRow();
- int row = jxTableComposants.convertRowIndexToModel(viewRow);
- 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
+ private static Logger logger = Logger.getLogger(PnlComposants.class);
+ private final PropertiesExpansion applicationProperties;
+ private final ComposantsTableModel cTableModel;
+ private InstalledModel im;
+ private final String installedFileLocation;
+
+ /**
+ *
+ * @param applicationProperties
+ */
+ public PnlComposants(final PropertiesExpansion applicationProperties) {
+ this.applicationProperties = applicationProperties;
+ this.installedFileLocation = applicationProperties.getProperty(Constants.SYS_PROP_INSTALLED_FILENAME);
+ this.cTableModel = new ComposantsTableModel();
+ try {
+ this.im = InstalledModel.readFromFile(this.installedFileLocation);
+ logger.debug("installedFileLocation=" + this.installedFileLocation);
+ logger.debug("im.fileLocation=" + this.im.getFileLocation());
+ this.cTableModel.setComposants(this.im.getComponents());
+ this.initComponents();
+
+ // jLabelSite.setFont(new java.awt.Font("Tahoma", 0, 11));
+
+ this.jButtonEditer.setEnabled(false);
+ this.jButtonSupprimer.setEnabled(false);
+
+ this.jxTableComposants.setShowGrid(false);
+ this.jxTableComposants.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
+ this.jxTableComposants.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
+
+ @Override
+ public void valueChanged(final ListSelectionEvent e) {
+ boolean bEditable = false;
+ final int viewRow = PnlComposants.this.jxTableComposants.getSelectedRow();
+ if (viewRow != -1) {
+ final int row = PnlComposants.this.jxTableComposants.convertRowIndexToModel(viewRow);
+ // Site
+ PnlComposants.this.jLabelSite.setText(PnlComposants.this.im.getComponents().get(row).getUri());
+ // bouton Editer et Supprimer disabled si composant issu d'un profil
+ // enabled si composant ajouté manuellement
+ bEditable = PnlComposants.this.im.getComponents().get(row).isEditable();
+ }
+ PnlComposants.this.jButtonEditer.setEnabled(bEditable);
+ PnlComposants.this.jButtonSupprimer.setEnabled(bEditable);
+ }
+ });
+ } catch (final Exception ex) {
+ logger.error(ex);
+ final 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 this.composants.size();
+ }
+
+ @Override
+ public int getColumnCount() {
+ return 2;
+ }
+
+ @Override
+ public Object getValueAt(final int rowIndex, final int columnIndex) {
+ final ComponentModel cm = this.composants.get(rowIndex);
+ switch (columnIndex) {
+ case 0:
+ return cm.getDescription();
+ default:
+ return cm.getVersion();
+ }
+
+ }
+
+ @Override
+ public Class<?> getColumnClass(final int columnIndex) {
+ return String.class;
+ }
+
+ @Override
+ public String getColumnName(final int column) {
+ switch (column) {
+ case 0:
+ return "Description";
+ default:
+ return "Version";
+ }
+ }
+
+ @Override
+ public boolean isCellEditable(final int rowIndex, final int columnIndex) {
+ return false;
+ }
+
+ public void setComposants(final 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() {
+
+ this.jLabel1 = new javax.swing.JLabel();
+ this.jLabel2 = new javax.swing.JLabel();
+ this.jLabelSite = new javax.swing.JLabel();
+ this.jButtonAjouter = new javax.swing.JButton();
+ this.jButtonEditer = new javax.swing.JButton();
+ this.jButtonSupprimer = new javax.swing.JButton();
+ this.jScrollPane1 = new javax.swing.JScrollPane();
+ this.jxTableComposants = new org.jdesktop.swingx.JXTable();
+
+ this.setPreferredSize(new java.awt.Dimension(472, 465));
+ this.setRequestFocusEnabled(false);
+
+ this.jLabel1.setFont(this.jLabel1.getFont().deriveFont(this.jLabel1.getFont().getStyle() | java.awt.Font.BOLD));
+ this.jLabel1.setText("Liste d'abonnements aux composants");
+
+ this.jLabel2.setFont(this.jLabel2.getFont().deriveFont(this.jLabel2.getFont().getStyle() | java.awt.Font.BOLD));
+ this.jLabel2.setText("Site");
+
+ this.jButtonAjouter.setText("Ajouter");
+ this.jButtonAjouter.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PnlComposants.this.jButtonAjouterActionPerformed(evt);
+ }
+ });
+
+ this.jButtonEditer.setText("Editer");
+ this.jButtonEditer.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PnlComposants.this.jButtonEditerActionPerformed(evt);
+ }
+ });
+
+ this.jButtonSupprimer.setText("Supprimer");
+ this.jButtonSupprimer.addActionListener(new java.awt.event.ActionListener() {
+ @Override
+ public void actionPerformed(final java.awt.event.ActionEvent evt) {
+ PnlComposants.this.jButtonSupprimerActionPerformed(evt);
+ }
+ });
+
+ this.jxTableComposants.setModel(this.cTableModel);
+ this.jScrollPane1.setViewportView(this.jxTableComposants);
+
+ final 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(this.jLabel1)
+ .addGroup(
+ layout.createSequentialGroup()
+ .addComponent(this.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(this.jButtonSupprimer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addComponent(this.jButtonEditer, javax.swing.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE).addComponent(this.jButtonAjouter, javax.swing.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE)))
+ .addGroup(layout.createSequentialGroup().addGap(32, 32, 32).addComponent(this.jLabelSite)).addComponent(this.jLabel2)).addContainerGap()));
+ layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
+ layout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(this.jLabel1)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(
+ layout.createSequentialGroup().addComponent(this.jButtonAjouter).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(this.jButtonEditer).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(this.jButtonSupprimer))
+ .addGroup(
+ layout.createSequentialGroup().addComponent(this.jScrollPane1).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(this.jLabel2).addComponent(this.jLabelSite)))).addGap(26, 26, 26)));
+ }// </editor-fold>//GEN-END:initComponents
+
+ private void jButtonAjouterActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButtonAjouterActionPerformed
+ // TODO add your handling code here:
+ final DlgComposantEdition nd = new DlgComposantEdition(MainWindow.getInstance(), new ComponentModel());
+ nd.setTitle("Ajout d'un composant");
+ nd.setLocationRelativeTo(MainWindow.getInstance());
+ nd.setInstalledModelFileLocation(this.installedFileLocation);
+ nd.setEnvironement(this.applicationProperties.getProperty(Constants.SYS_PROP_MAJ_CONFIG));
+ nd.setVisible(true);
+
+ try {
+ this.im = InstalledModel.readFromFile(this.installedFileLocation);
+ this.cTableModel.setComposants(this.im.getComponents());
+ this.cTableModel.fireTableDataChanged();
+ } catch (final Exception ex) {
+ logger.error(ex);
+ final DisplayExceptionDlg exdlg = new DisplayExceptionDlg(ex);
+ }
+ }// GEN-LAST:event_jButtonAjouterActionPerformed
+
+ private void jButtonEditerActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButtonEditerActionPerformed
+ // TODO add your handling code here:
+ final int viewRow = this.jxTableComposants.getSelectedRow();
+ final int row = this.jxTableComposants.convertRowIndexToModel(viewRow);
+ final ComponentModel cm = this.im.getComponents().get(row);
+ final DlgComposantEdition nd = new DlgComposantEdition(MainWindow.getInstance(), cm);
+ nd.setTitle("Edition d'un composant");
+ nd.setLocationRelativeTo(MainWindow.getInstance());
+ nd.setInstalledModelFileLocation(this.installedFileLocation);
+ nd.setEnvironement(this.applicationProperties.getProperty(Constants.SYS_PROP_MAJ_CONFIG));
+ nd.setVisible(true);
+ try {
+ this.im = InstalledModel.readFromFile(this.installedFileLocation);
+ this.cTableModel.setComposants(this.im.getComponents());
+ this.cTableModel.fireTableDataChanged();
+ } catch (final Exception ex) {
+ logger.error(ex);
+ final DisplayExceptionDlg exdlg = new DisplayExceptionDlg(ex);
+ }
+ }// GEN-LAST:event_jButtonEditerActionPerformed
+
+ private void jButtonSupprimerActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButtonSupprimerActionPerformed
+ // TODO add your handling code here:
+ // im.getComponents().remove(jxTableComposants.getSelectedRow());
+ final int viewRow = this.jxTableComposants.getSelectedRow();
+ final int row = this.jxTableComposants.convertRowIndexToModel(viewRow);
+ this.im.removeComponent(this.im.getComponents().get(row).getUUID());
+ try {
+ this.im.saveInstalledModel();
+ this.im = InstalledModel.readFromFile(this.installedFileLocation); // pas spécialement nécessaire
+ this.cTableModel.setComposants(this.im.getComponents());
+ this.cTableModel.fireTableRowsDeleted(row, row);
+ // cTableModel.fireTableDataChanged();
+ } catch (final Exception ex) {
+ logger.error(ex);
+ final 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
}
*/
package fr.gouv.finances.cp.xemelios.updater.update;
+import javax.xml.namespace.QName;
+
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
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;
- }
+ public static final transient String TAG = "component-ref";
+ public static final transient QName QN = new QName(TAG);
+ private String uri, version;
+
+ public ComponentRefModel(final QName tag) {
+ super();
+ }
+
+ @Override
+ public void addCharacterData(final String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(final XmlMarshallable child, final QName tagName) throws SAXException {
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(final XmlAttributes attributes) throws SAXException {
+ this.uri = attributes.getValue("uri");
+ this.version = attributes.getValue("version");
+ return this;
+ }
+
+ @Override
+ public void marshall(final XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("uri", this.uri);
+ output.addAttribute("version", this.version);
+ output.endTag(TAG);
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ if (this.uri == null) {
+ throw new InvalidXmlDefinition("uri attribute is mandatory for element " + TAG);
+ }
+ if (this.version == null) {
+ throw new InvalidXmlDefinition("version attribute is mandatory for element " + TAG);
+ }
+ }
+
+ @Override
+ public ComponentRefModel clone() {
+ final ComponentRefModel cr = new ComponentRefModel(QN);
+ cr.uri = this.uri;
+ cr.version = this.version;
+ return cr;
+ }
+
+ public void setUri(final String uri) {
+ this.uri = uri;
+ }
+
+ public String getUri() {
+ return this.uri;
+ }
+
+ public String getVersion() {
+ return this.version;
+ }
+
+ public void setVersion(final String version) {
+ this.version = version;
+ }
+
+ @Override
+ public String toString() {
+ return this.uri + " (" + this.version + ")";
+ }
+
+ public boolean equals(final ComponentRefModel crm) {
+ return crm.getUri().equals(this.uri);
+ }
+
+ public boolean equals(final ComponentModel crm) {
+ return crm.getUri().equals(this.uri);
+ }
+
+ public boolean equals(final String id) {
+ return this.uri.equals(id);
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(final String uri, final String localName, final String qName, final Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
}
*/
package fr.gouv.finances.cp.xemelios.updater.update;
+import javax.xml.namespace.QName;
+
import org.xml.sax.Attributes;
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 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;
- }
+ 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(final QName tagName) {
+ super();
+ // params = new ArrayList<ParamModel>();
+ }
+
+ @Override
+ public void addCharacterData(final String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(final XmlMarshallable child, final QName tagName) throws SAXException {
+ // if(ParamModel.QN.equals(tagName)) params.add((ParamModel)child);
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(final XmlAttributes attributes) throws SAXException {
+ this.className = attributes.getValue("class");
+ return this;
+ }
+
+ @Override
+ public void marshall(final XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("class", this.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() {
+ final 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 this.className;
+ }
+
+ public void setClassName(final String className) {
+ this.className = className;
+ }
+
+ /*
+ * public ArrayList<ParamModel> getParams() { return params; }
+ *
+ * public void setParams(ArrayList<ParamModel> params) { this.params = params; }
+ */
+ @Override
+ public XmlMarshallable getChildToModify(final String uri, final String localName, final String qName, final Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
}
*/
package fr.gouv.finances.cp.xemelios.updater.update;
+import javax.xml.namespace.QName;
+
import org.xml.sax.Attributes;
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 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;
- }
+ public static final transient String TAG = "delete";
+ public static final transient QName QN = new QName(TAG);
+ private String name;
+
+ public DeleteModel(final QName tag) {
+ super();
+ }
+
+ public DeleteModel() {
+ super();
+ }
+
+ @Override
+ public void addCharacterData(final String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(final XmlMarshallable child, final QName tagName) throws SAXException {
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(final XmlAttributes attributes) throws SAXException {
+ this.name = attributes.getValue("name");
+ return this;
+ }
+
+ @Override
+ public void marshall(final XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("name", this.name);
+ output.endTag(TAG);
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ }
+
+ @Override
+ public DeleteModel clone() {
+ final DeleteModel dm = new DeleteModel(QN);
+ dm.name = this.name;
+ return dm;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ public void setName(final String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String toString() {
+ return this.getName();
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(final String uri, final String localName, final String qName, final Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
}
import java.util.ArrayList;
+import javax.xml.namespace.QName;
+
import org.xml.sax.Attributes;
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 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;
- }
+ 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();
+ this.files = new ArrayList<FileModel>();
+ this.deletes = new ArrayList<DeleteModel>();
+ }
+
+ public FileListModel(final QName tag) {
+ super();
+ this.files = new ArrayList<FileModel>();
+ this.deletes = new ArrayList<DeleteModel>();
+ }
+
+ @Override
+ public void addCharacterData(final String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(final XmlMarshallable child, final QName tagName) throws SAXException {
+ if (child instanceof FileModel) {
+ this.files.add((FileModel) child);
+ } else if (child instanceof DeleteModel) {
+ this.deletes.add((DeleteModel) child);
+ }
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(final XmlAttributes attributes) throws SAXException {
+ this.root = attributes.getValue("root");
+ return this;
+ }
+
+ @Override
+ public void marshall(final XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("root", this.root);
+ for (final FileModel fm : this.files) {
+ fm.marshall(output);
+ }
+ for (final DeleteModel dm : this.deletes) {
+ dm.marshall(output);
+ }
+ output.endTag(TAG);
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ }
+
+ @Override
+ public FileListModel clone() {
+ final FileListModel flm = new FileListModel(QN);
+ flm.root = this.root;
+ for (final FileModel fm : this.files) {
+ flm.files.add(fm);
+ }
+ for (final DeleteModel dm : this.deletes) {
+ flm.deletes.add(dm);
+ }
+ return flm;
+ }
+
+ public ArrayList<FileModel> getFiles() {
+ return this.files;
+ }
+
+ public void setFiles(final ArrayList<FileModel> files) {
+ this.files = files;
+ }
+
+ public ArrayList<DeleteModel> getDeletes() {
+ return this.deletes;
+ }
+
+ public void setDeletes(final ArrayList<DeleteModel> deletes) {
+ this.deletes = deletes;
+ }
+
+ public String getRoot() {
+ return this.root;
+ }
+
+ public void setRoot(final String root) {
+ this.root = root;
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(final String uri, final String localName, final String qName, final Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
}
*/
package fr.gouv.finances.cp.xemelios.updater.update;
+import javax.xml.namespace.QName;
+
import org.xml.sax.Attributes;
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 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;
- }
+ 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(final QName tag) {
+ super();
+ }
+
+ @Override
+ public void addCharacterData(final String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(final XmlMarshallable child, final QName tagName) throws SAXException {
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(final XmlAttributes attributes) throws SAXException {
+ this.name = attributes.getValue("name");
+ this.source = attributes.getValue("source");
+ this.dest = attributes.getValue("dest");
+ this.md5 = attributes.getValue("md5");
+ this.unpackedMd5 = attributes.getValue("unpacked-md5");
+ return this;
+ }
+
+ @Override
+ public void marshall(final XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("name", this.name);
+ output.addAttribute("source", this.source);
+ output.addAttribute("dest", this.dest);
+ output.addAttribute("md5", this.md5);
+ output.addAttribute("unpacked-md5", this.unpackedMd5);
+ output.endTag(TAG);
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ }
+
+ @Override
+ public FileModel clone() {
+ final FileModel fm = new FileModel(QN);
+ fm.name = this.name;
+ fm.source = this.source;
+ fm.dest = this.dest;
+ return fm;
+ }
+
+ public String getDest() {
+ return this.dest;
+ }
+
+ public void setDest(final String dest) {
+ this.dest = dest;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ public void setName(final String name) {
+ this.name = name;
+ }
+
+ public String getSource() {
+ return this.source;
+ }
+
+ public void setSource(final String source) {
+ this.source = source;
+ }
+
+ @Override
+ public String toString() {
+ return this.getName();
+ }
+
+ public String getMd5() {
+ return this.md5;
+ }
+
+ public void setMd5(final String md5) {
+ this.md5 = md5;
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(final String uri, final String localName, final String qName, final Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
+
+ public String getUnpackedMd5() {
+ return this.unpackedMd5;
+ }
+
+ public void setUnpackedMd5(final String unpackedMd5) {
+ this.unpackedMd5 = unpackedMd5;
+ }
}
package fr.gouv.finances.cp.xemelios.updater.update;
-import fr.gouv.finances.dgfip.xemelios.common.config.TexteModel;
import javax.xml.namespace.QName;
+import fr.gouv.finances.dgfip.xemelios.common.config.TexteModel;
+
/**
- *
+ *
* @author cmarchand
*/
public class NoteModel extends TexteModel {
- public static final transient QName QN = new QName("note");
+ public static final transient QName QN = new QName("note");
- public NoteModel(QName qn) {
- super(qn);
- }
+ public NoteModel(final QName qn) {
+ super(qn);
+ }
}
*/
package fr.gouv.finances.cp.xemelios.updater.update;
+import javax.xml.namespace.QName;
+
import org.xml.sax.Attributes;
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 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;
- }
+ public static final transient String TAG = "param";
+ public static final transient QName QN = new QName(TAG);
+ private String name;
+ private StringBuilder paramValue;
+
+ public ParamModel(final QName tagName) {
+ super();
+ this.paramValue = new StringBuilder();
+ }
+
+ @Override
+ public void addCharacterData(final String cData) throws SAXException {
+ this.paramValue.append(cData);
+ }
+
+ @Override
+ public void addChild(final XmlMarshallable child, final QName tagName) throws SAXException {
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(final XmlAttributes attributes) throws SAXException {
+ this.name = attributes.getValue("name");
+ return this;
+ }
+
+ @Override
+ public void marshall(final XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("name", this.name);
+ output.addCharacterData(this.getParamValue());
+ output.endTag(TAG);
+
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ }
+
+ @Override
+ public ParamModel clone() {
+ final ParamModel pm = new ParamModel(QN);
+ pm.name = this.name;
+ pm.paramValue.append(this.getParamValue());
+ return pm;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ public void setName(final String name) {
+ this.name = name;
+ }
+
+ public String getParamValue() {
+ return this.paramValue.toString();
+ }
+
+ public void setParamValue(final StringBuilder paramValue) {
+ this.paramValue = paramValue;
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(final String uri, final String localName, final String qName, final Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
}
package fr.gouv.finances.cp.xemelios.updater.update;
import java.util.ArrayList;
-import java.util.Iterator;
+
+import javax.xml.namespace.QName;
import org.xml.sax.Attributes;
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 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;
- }
+ public static final transient String TAG = "requires";
+ public static final transient QName QN = new QName(TAG);
+ private ArrayList<ComponentRefModel> components;
+
+ public RequireModel() {
+ super();
+ this.components = new ArrayList<ComponentRefModel>();
+ }
+
+ public RequireModel(final QName tag) {
+ super();
+ this.components = new ArrayList<ComponentRefModel>();
+ }
+
+ @Override
+ public void addCharacterData(final String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(final XmlMarshallable child, final QName tagName) throws SAXException {
+ this.components.add((ComponentRefModel) child);
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(final XmlAttributes attributes) throws SAXException {
+ return this;
+ }
+
+ @Override
+ public void marshall(final XmlOutputter output) {
+ output.startTag(TAG);
+ for (int i = 0; i < this.components.size(); i++) {
+ this.components.get(i).marshall(output);
+ }
+ output.endTag(TAG);
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ for (final ComponentRefModel componentRefModel : this.components) {
+ componentRefModel.validate();
+ }
+ }
+
+ @Override
+ public RequireModel clone() {
+ final RequireModel rm = new RequireModel(QN);
+ for (final ComponentRefModel crm : this.components) {
+ rm.components.add(crm);
+ }
+ return rm;
+ }
+
+ public ArrayList<ComponentRefModel> getComponents() {
+ return this.components;
+ }
+
+ public void setComponents(final ArrayList<ComponentRefModel> components) {
+ this.components = components;
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(final String uri, final String localName, final String qName, final Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
}
*/
package fr.gouv.finances.cp.xemelios.updater.update;
+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;
+
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.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);
+ 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;
+ 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 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
+ 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;
- }
-
+ public UpdateModel() {
+ super();
+ this.versions = new ArrayList<VersionModel>();
+ }
+
+ /**
+ *
+ * @param description
+ * @param type
+ * @param last_version
+ * @param original_location
+ * @param generate_date
+ * @param environment_type
+ */
+ public UpdateModel(final String description, final String type, final String last_version, final String original_location, final String generate_date, final 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(final QName QN) {
+ super();
+ this.versions = new ArrayList<VersionModel>();
+ }
+
+ public static UpdateModel loadModel(final ComponentModel cm, final String environment) throws Exception {
+ UpdateModel um = new UpdateModel();
+ um.ComponentUri = cm.getUri();
+ try {
+ final String urlLocation = cm.getUri() + "/" + environment + "/update.xml";
+ logger.debug("urlLocation=" + urlLocation);
+
+ final HttpClient client = NetAccess.getHttpClient(MainWindow.getInstance().getEnvProperties());
+ final GetMethod meth = new GetMethod(urlLocation);
+ meth.addRequestHeader("Pragma", "no-cache");
+ final int httpRet = client.executeMethod(meth);
+ if (httpRet > 300) {
+ throw new Exception("URL urlLocation " + urlLocation + " : " + meth.getStatusText());
+ }
+ final InputStream is = meth.getResponseBodyAsStream();
+ final 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 (final Exception ex) {
+ logger.error(ex);
+ throw new Exception(ex);
+ }
+ }
+
+ public String getComponentUri() {
+ return this.ComponentUri;
+ }
+
+ public String getDescription() {
+ return this.description;
+ }
+
+ public String getEnvironment_type() {
+ return this.environment_type;
+ }
+
+ public String getGenerate_date() {
+ return this.generate_date;
+ }
+
+ public String getLast_version() {
+ return this.last_version;
+ }
+
+ public String getOriginal_location() {
+ return this.original_location;
+ }
+
+ public String getType() {
+ return this.type;
+ }
+
+ public ArrayList<VersionModel> getVersions() {
+ return this.versions;
+ }
+
+ public VersionModel getVersionModel(final String version) {
+ for (final VersionModel vm : this.versions) {
+ if (vm.getVersion().equals(version)) {
+ return vm;
+ }
+ }
+ return null;
+ }
+
+ public VersionModel getLastVersionModel() {
+ for (final VersionModel vm : this.versions) {
+ if (vm.getVersion().equals(this.last_version)) {
+ return vm;
+ }
+ }
+ return null;
+ }
+
+ public int getVersionModelIdx(final String version) {
+ for (int i = 0; i < this.versions.size(); i++) {
+ if (this.versions.get(i).getVersion().equals(version)) {
+ return i;
+ }
+ }
+ return NOT_FOUND;
+ }
+
+ public int getLastVersionModelIdx() {
+ for (int i = 0; i < this.versions.size(); i++) {
+ if (this.versions.get(i).getVersion().equals(this.last_version)) {
+ return i;
+ }
+ }
+ return NOT_FOUND;
+ }
+
+ public void setDescription(final String description) {
+ this.description = description;
+ }
+
+ public void setEnvironment_type(final String environment_type) {
+ this.environment_type = environment_type;
+ }
+
+ public void setGenerate_date(final String generate_date) {
+ this.generate_date = generate_date;
+ }
+
+ public void setLast_version(final String last_version) {
+ this.last_version = last_version;
+ }
+
+ public void setOriginal_location(final String original_location) {
+ this.original_location = original_location;
+ }
+
+ public void setType(final String type) {
+ this.type = type;
+ }
+
+ public void setVersions(final ArrayList<VersionModel> versions) {
+ this.versions = versions;
+ }
+
+ @Override
+ public void addCharacterData(final String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(final XmlMarshallable child, final QName tag) throws SAXException {
+ this.versions.add((VersionModel) child);
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(final XmlAttributes attributes) throws SAXException {
+ this.description = attributes.getValue("description");
+ this.type = attributes.getValue("type");
+ this.last_version = attributes.getValue("last-version");
+ this.original_location = attributes.getValue("original-location");
+ this.generate_date = attributes.getValue("generate-date");
+ this.environment_type = attributes.getValue("environment-type");
+ return this;
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(final String uri, final String localName, final String qName, final Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public void marshall(final XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("description", this.description);
+ output.addAttribute("type", this.type);
+ output.addAttribute("last-version", this.last_version);
+ output.addAttribute("original-location", this.original_location);
+ output.addAttribute("environment-type", this.environment_type);
+ for (final VersionModel vm : this.versions) {
+ vm.marshall(output);
+ }
+ output.endTag(TAG);
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ if (this.description == null) {
+ throw new InvalidXmlDefinition("description attribute is mandatory for element " + TAG);
+ }
+ if (this.type == null) {
+ throw new InvalidXmlDefinition("type attribute is mandatory for element " + TAG);
+ }
+ if (this.last_version == null) {
+ throw new InvalidXmlDefinition("last-version attribute is mandatory for element " + TAG);
+ }
+ if (this.original_location == null) {
+ throw new InvalidXmlDefinition("original-location attribute is mandatory for element " + TAG);
+ }
+ if (this.environment_type == null) {
+ throw new InvalidXmlDefinition("environment-type attribute is mandatory for element " + TAG);
+ }
+ for (final VersionModel vm : this.versions) {
+ vm.validate();
+ }
+ }
+
+ /**
+ *
+ * @return
+ */
+ @Override
+ public QName getQName() {
+ return QN;
+ }
+
+ @Override
+ public UpdateModel clone() {
+ final UpdateModel u = new UpdateModel(this.description, this.type, this.last_version, this.original_location, this.generate_date, this.environment_type);
+ for (final VersionModel vm : this.versions) {
+ u.versions.add(vm);
+ }
+ return u;
+ }
+
+ @Override
+ public String toString() {
+ return this.description + "/" + this.environment_type + "/" + this.generate_date + "/" + this.last_version + "/" + this.original_location + "/" + this.type;
+ }
}
*/
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;
+import fr.gouv.finances.cp.utils.xml.marshal.XmlMarshalParser;
+import fr.gouv.finances.dgfip.utils.xml.FactoryProvider;
+
/**
- * Modèle de l'élèment "update.xml"
- * Contient l'ensemble des composants d'un profil.
+ * 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");
-
+ 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(final HashMap mapping) throws SAXException, ParserConfigurationException, FactoryConfigurationError {
+ super(mapping, FactoryProvider.getSaxParserFactory());
+ }
- public UpdateParser() throws SAXException, ParserConfigurationException, FactoryConfigurationError {
- super(new Mapping(),true, 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);
- }
- }
+ private static class Mapping extends HashMap<QName, Class> {
+ public Mapping() {
+ this.put(XEMELIOS_UPDATE, UpdateModel.class);
+ this.put(VersionModel.QN, VersionModel.class);
+ this.put(FileListModel.QN, FileListModel.class);
+ this.put(FileModel.QN, FileModel.class);
+ this.put(DeleteModel.QN, DeleteModel.class);
+ this.put(RequireModel.QN, RequireModel.class);
+ this.put(ComponentRefModel.QN, ComponentRefModel.class);
+ this.put(ConfigurationModel.QN, ConfigurationModel.class);
+ this.put(NoteModel.QN, NoteModel.class);
+ }
+ }
}
*/
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;
+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;
+
/**
- *
+ *
* @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;
- }
-
+ 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();
+ this.files = new FileListModel();
+ this.requires = new RequireModel();
+ this.configurators = new ArrayList<ConfigurationModel>();
+ this.notes = new ArrayList<NoteModel>();
+ }
+
+ public VersionModel(final QName tag) {
+ this();
+ }
+
+ public VersionModel(final String version, final String date, final FileListModel files, final RequireModel requires, final ArrayList<ConfigurationModel> configurators) {
+ this();
+ this.version = version;
+ this.date = date;
+ this.files = files;
+ this.requires = requires;
+ this.configurators = configurators;
+ }
+
+ public ArrayList<ConfigurationModel> getConfigurators() {
+ return this.configurators;
+ }
+
+ public String getVersion() {
+ return this.version;
+ }
+
+ public String getDate() {
+ return this.date;
+ }
+
+ public FileListModel getFiles() {
+ return this.files;
+ }
+
+ public RequireModel getRequires() {
+ return this.requires;
+ }
+
+ public void setConfigurators(final ArrayList<ConfigurationModel> configurators) {
+ this.configurators = configurators;
+ }
+
+ public void setDate(final String date) {
+ this.date = date;
+ }
+
+ public void setFiles(final FileListModel files) {
+ this.files = files;
+ }
+
+ public void setRequires(final RequireModel requires) {
+ this.requires = requires;
+ }
+
+ public void setVersion(final String version) {
+ this.version = version;
+ }
+
+ @Override
+ public void addCharacterData(final String cData) throws SAXException {
+ }
+
+ @Override
+ public void addChild(final XmlMarshallable child, final QName tag) throws SAXException {
+ if (child instanceof ConfigurationModel) {
+ this.configurators.add((ConfigurationModel) child);
+ } else if (child instanceof RequireModel) {
+ this.requires = ((RequireModel) child);
+ } else if (child instanceof FileListModel) {
+ this.files = ((FileListModel) child);
+ // cela pourrait être omis
+ } else if (child instanceof NoteModel) {
+ this.notes.add((NoteModel) child);
+ }
+ }
+
+ @Override
+ public XmlMarshallable getAttributes(final XmlAttributes attributes) throws SAXException {
+ this.version = attributes.getValue("version");
+ this.date = attributes.getValue("date");
+ return this;
+ }
+
+ @Override
+ public XmlMarshallable getChildToModify(final String uri, final String localName, final String qName, final Attributes atts) {
+ return null;
+ }
+
+ @Override
+ public void marshall(final XmlOutputter output) {
+ output.startTag(TAG);
+ output.addAttribute("version", this.version);
+ output.addAttribute("date", this.date);
+ this.files.marshall(output);
+ this.requires.marshall(output);
+ for (final ConfigurationModel cm : this.configurators) {
+ cm.marshall(output);
+ }
+ // volontairement, on ne marshall pas les notes.
+ output.endTag(TAG);
+ }
+
+ @Override
+ public void validate() throws InvalidXmlDefinition {
+ if (this.version == null) {
+ throw new InvalidXmlDefinition("version attribute is mandatory for element " + TAG);
+ }
+ }
+
+ @Override
+ public QName getQName() {
+ return QN;
+ }
+
+ @Override
+ public VersionModel clone() {
+ final ArrayList<ConfigurationModel> cf = new ArrayList<ConfigurationModel>();
+ for (final ConfigurationModel cm : this.configurators) {
+ cf.add(cm);
+ }
+ final VersionModel vm = new VersionModel(this.version, this.date, this.files.clone(), this.requires.clone(), cf);
+ vm.notes = this.notes;
+ return this;
+ }
+
+ @Override
+ public String toString() {
+ return this.version + "/" + this.date;
+ }
}
private StringBuilder builder;
public ConfigurationReportBuilder() {
- builder = new StringBuilder();
+ this.builder = new StringBuilder();
}
public void reset() {
- builder = new StringBuilder();
- builder.append("############## Xemelios Configuration Report ##############\n");
+ this.builder = new StringBuilder();
+ this.builder.append("############## Xemelios Configuration Report ##############\n");
}
public String getReport() {
- return builder.toString();
+ return this.builder.toString();
}
- public void addJarsDescription(Collection<JarDescription> jarsDescription) {
- builder.append("-------------- JARs --------------\n");
+ public void addJarsDescription(final Collection<JarDescription> jarsDescription) {
+ this.builder.append("-------------- JARs --------------\n");
- for (JarDescription jd : jarsDescription) {
- Set<Entry<Object, Object>> mfAttrs = jd.getManifestAttribute().entrySet();
+ for (final JarDescription jd : jarsDescription) {
+ final Set<Entry<Object, Object>> mfAttrs = jd.getManifestAttribute().entrySet();
- builder.append("JAR URL : ").append(jd.getLocation()).append("\n");
- for (Map.Entry<Object, Object> attr : mfAttrs) {
- builder.append("\t").append(attr.getKey()).append(" : ").append(attr.getValue()).append("\n");
+ this.builder.append("JAR URL : ").append(jd.getLocation()).append("\n");
+ for (final Map.Entry<Object, Object> attr : mfAttrs) {
+ this.builder.append("\t").append(attr.getKey()).append(" : ").append(attr.getValue()).append("\n");
}
-
- builder.append("\n");
+
+ this.builder.append("\n");
}
- builder.append("\n");
+ this.builder.append("\n");
}
- public void addFileContent(File propertiesFile, String title) {
- addFileContent(propertiesFile, FILE_DEFAULT_ENCODING, title);
+ public void addFileContent(final File propertiesFile, final String title) {
+ this.addFileContent(propertiesFile, FILE_DEFAULT_ENCODING, title);
}
- public void addFileContent(File f, String encoding, String title) {
- builder.append("-------------- ").append(title).append("(").append(f.getAbsolutePath()).append(") --------------\n");
+ public void addFileContent(final File f, final String encoding, final String title) {
+ this.builder.append("-------------- ").append(title).append("(").append(f.getAbsolutePath()).append(") --------------\n");
try {
- builder.append(FileUtils.readTextFile(f, encoding)).append("\n");
- } catch (IOException e) {
+ this.builder.append(FileUtils.readTextFile(f, encoding)).append("\n");
+ } catch (final IOException e) {
logger.error(e, e);
- builder.append("Error : ").append(e.getMessage());
+ this.builder.append("Error : ").append(e.getMessage());
}
- builder.append("\n");
+ this.builder.append("\n");
}
- public void addParameters(Map<String, String> parameters, String title) {
- builder.append("-------------- ").append(title).append(" --------------\n");
+ public void addParameters(final Map<String, String> parameters, final String title) {
+ this.builder.append("-------------- ").append(title).append(" --------------\n");
- for (Map.Entry<String, String> p : parameters.entrySet()) {
- builder.append(p.getKey()).append(" : ").append(p.getValue()).append("\n");
+ for (final Map.Entry<String, String> p : parameters.entrySet()) {
+ this.builder.append(p.getKey()).append(" : ").append(p.getValue()).append("\n");
}
- builder.append("\n");
+ this.builder.append("\n");
}
- public void addDataLayer(DataImpl dataLayer) {
- builder.append("-------------- Xemelios DataLayer --------------\n");
- builder.append(dataLayer.getDatalayerConfiguration());
- builder.append("\n");
+ public void addDataLayer(final DataImpl dataLayer) {
+ this.builder.append("-------------- Xemelios DataLayer --------------\n");
+ this.builder.append(dataLayer.getDatalayerConfiguration());
+ this.builder.append("\n");
}
}
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)
- *
+ * 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;
- }
- }
+ private static final String DefaultIndentBuffer;
+ private String defaultEncoding = "ISO-8859-1";
+ static {
+ final StringBuffer sb = new StringBuffer(256);
+ for (int i = 0; i < 256; i++) {
+ sb.append(' ');
+ }
+ DefaultIndentBuffer = sb.toString();
+ }
+
+ private final Node node;
+ private boolean produceHTML;
+ private boolean prettyPrint;
+ private int indentSize = 4;
+ private int indentLevel = 0;
+ private String indentTemplate = DefaultIndentBuffer;
+ private final StringBuffer textBuffer = new StringBuffer();
+
+ public TextWriter(final Node node, final boolean produceHTML, final boolean prettyPrint, final int indentSize) {
+ this.node = node;
+ this.produceHTML = produceHTML;
+ this.prettyPrint = prettyPrint;
+ this.indentSize = indentSize;
+ }
+
+ public TextWriter(final Node node, final boolean produceHTML, final boolean prettyPrint) {
+ this.node = node;
+ this.produceHTML = produceHTML;
+ this.prettyPrint = prettyPrint;
+ }
+
+ public TextWriter(final Node node, final boolean produceHTML) {
+ this.node = node;
+ this.produceHTML = produceHTML;
+ }
+
+ public TextWriter(final Node node) {
+ this.node = node;
+ }
+
+ public TextWriter(final Node node, final String encoding) {
+ this.node = node;
+ if (encoding != null) {
+ this.defaultEncoding = encoding;
+ }
+ }
+
+ public boolean isProduceHTML() {
+ return this.produceHTML;
+ }
+
+ public void setProduceHTML(final boolean produceHTML) {
+ this.produceHTML = produceHTML;
+ }
+
+ public boolean isPrettyPrint() {
+ return this.prettyPrint;
+ }
+
+ public void setPrettyPrint(final boolean prettyPrint) {
+ this.prettyPrint = prettyPrint;
+ }
+
+ private void writeNode(final Writer writer, final Node node) throws IOException {
+ final short type = node.getNodeType();
+ switch (type) {
+
+ case Node.DOCUMENT_NODE:
+ this.document(writer, (Document) node);
+ break;
+
+ case Node.DOCUMENT_FRAGMENT_NODE:
+ this.documentFragment(writer, (DocumentFragment) node);
+ break;
+
+ case Node.DOCUMENT_TYPE_NODE:
+ this.documentType(writer, (DocumentType) node);
+ break;
+
+ case Node.ELEMENT_NODE:
+ this.element(writer, (Element) node);
+ break;
+
+ case Node.ATTRIBUTE_NODE:
+ this.attribute(writer, (Attr) node);
+ break;
+
+ case Node.ENTITY_REFERENCE_NODE:
+ this.entityReference(writer, (EntityReference) node);
+ break;
+
+ case Node.ENTITY_NODE:
+ this.entity(writer, (Entity) node);
+ break;
+
+ case Node.NOTATION_NODE:
+ this.notation(writer, (Notation) node);
+ break;
+
+ case Node.PROCESSING_INSTRUCTION_NODE:
+ this.procInst(writer, (ProcessingInstruction) node);
+ break;
+
+ case Node.TEXT_NODE:
+ this.text(writer, (Text) node);
+ break;
+
+ case Node.CDATA_SECTION_NODE:
+ this.cDataSection(writer, (CDATASection) node);
+ break;
+
+ case Node.COMMENT_NODE:
+ this.comment(writer, (Comment) node);
+ break;
+ }
+ }
+
+ private String getChildText(final Node node) {
+ final StringBuffer sb = new StringBuffer();
+ final NodeList l = node.getChildNodes();
+ final int size = l.getLength();
+ for (int i = 0; i < size; i++) {
+ final Node n = l.item(i);
+ if (n.getNodeType() == Node.TEXT_NODE) {
+ final Text t = (Text) n;
+ sb.append(t.getData());
+ } else {
+ return null;
+ }
+ }
+ return sb.toString();
+ }
+
+ private void writeChildren(final Writer writer, final Node node) throws IOException {
+ final NodeList l = node.getChildNodes();
+ final int size = l.getLength();
+ for (int i = 0; i < size; i++) {
+ final Node n = l.item(i);
+ this.writeNode(writer, n);
+ }
+ }
+
+ private void document(final Writer writer, final Document doc) throws IOException {
+ if (!this.produceHTML) {
+ writer.write("<?xml version=\"1.0\" encoding=\"");
+ writer.write(this.defaultEncoding);
+ writer.write("\"?>\n");
+ }
+ this.writeChildren(writer, doc);
+ }
+
+ private void documentFragment(final Writer writer, final DocumentFragment fragment) throws IOException {
+ this.writeChildren(writer, fragment);
+ }
+
+ private void documentType(final Writer writer, final DocumentType docType) throws IOException {
+ writer.write("<!DOCTYPE ");
+ writer.write(docType.getName());
+ final String pubID = docType.getPublicId();
+ final 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);
+ }
+
+ final String is = docType.getInternalSubset();
+ if (is != null) {
+ writer.write(" [");
+ writer.write(is);
+ writer.write("]");
+ }
+ writer.write(">\n");
+ }
+
+ private void element(final Writer writer, final Element elem) throws IOException {
+ if (this.prettyPrint) {
+ this.checkTextBuffer(writer);
+ this.indent(writer);
+ }
+
+ final String n = elem.getTagName();
+ writer.write('<');
+ this.writeText(writer, n);
+
+ final NamedNodeMap a = elem.getAttributes();
+ final int size = a.getLength();
+ for (int i = 0; i < size; i++) {
+ final Attr att = (Attr) a.item(i);
+ writer.write(' ');
+ this.writeNode(writer, att);
+ }
+
+ if (elem.hasChildNodes()) {
+ writer.write('>');
+
+ if (this.prettyPrint) {
+ final String text = this.getChildText(elem);
+ if (text != null) {
+ this.writeEscapedText(writer, this.normalizeString(text), false);
+ } else {
+ writer.write('\n');
+ this.indentLevel++;
+ this.writeChildren(writer, elem);
+ this.checkTextBuffer(writer);
+ this.indentLevel--;
+ this.indent(writer);
+ }
+ } else {
+ this.writeChildren(writer, elem);
+ }
+
+ writer.write("</");
+ this.writeText(writer, n);
+ writer.write('>');
+ } else {
+ if (this.produceHTML) {
+ writer.write(">");
+ } else {
+ writer.write("/>");
+ }
+ }
+
+ if (this.prettyPrint) {
+ writer.write('\n');
+ }
+ }
+
+ private void attribute(final Writer writer, final Attr attr) throws IOException {
+ this.writeText(writer, attr.getName());
+ writer.write("=\"");
+ // writeEscapedText(writer, attr.getValue(), true);
+ writer.write(StringEscapeUtils.escapeXml(attr.getValue()));
+ writer.write("\"");
+ }
+
+ private void entityReference(final Writer writer, final EntityReference entityRef) throws IOException {
+ }
+
+ private void entity(final Writer writer, final Entity entity) throws IOException {
+ }
+
+ private void notation(final Writer writer, final Notation notation) throws IOException {
+ if (this.prettyPrint) {
+ this.checkTextBuffer(writer);
+ this.indent(writer);
+ }
+
+ writer.write("<!NOTATION ");
+ writer.write(notation.getNodeName());
+ final String pubID = notation.getPublicId();
+ final 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(final Writer writer, final ProcessingInstruction pi) throws IOException {
+ if (this.prettyPrint) {
+ this.checkTextBuffer(writer);
+ this.indent(writer);
+ }
+
+ writer.write("<?");
+ this.writeText(writer, pi.getTarget());
+ writer.write(" ");
+ this.writeText(writer, pi.getData());
+ writer.write("?>\n");
+ }
+
+ private void text(final Writer writer, final Text text) throws IOException {
+ if (this.prettyPrint) {
+ this.textBuffer.append(text.getData());
+ } else {
+ this.writeEscapedText(writer, text.getData(), false);
+ }
+ }
+
+ private void cDataSection(final Writer writer, final CDATASection cdata) throws IOException {
+ if (this.prettyPrint) {
+ this.checkTextBuffer(writer);
+ this.indent(writer);
+ }
+
+ writer.write("<![CDATA[");
+ writer.write(cdata.getData());
+ writer.write("]]>");
+
+ if (this.prettyPrint) {
+ writer.write('\n');
+ }
+ }
+
+ private void comment(final Writer writer, final Comment comment) throws IOException {
+ if (this.prettyPrint) {
+ this.checkTextBuffer(writer);
+ this.indent(writer);
+ }
+
+ writer.write("<!--");
+ this.writeText(writer, comment.getData());
+ writer.write("-->");
+
+ if (this.prettyPrint) {
+ writer.write('\n');
+ }
+ }
+
+ private void writeText(final Writer writer, final String text) throws IOException {
+ if (text != null) {
+ writer.write(text);
+ }
+ }
+
+ private void writeEscapedText(final Writer writer, final String text, final boolean attr) throws IOException {
+ if (text != null) {
+ final char[] value = text.toCharArray();
+ String outval = null;
+ int start = 0;
+ int len = 0;
+ for (int i = 0; i < value.length; i++) {
+ final char c = value[i];
+ switch (c) {
+ case '\"':
+ outval = """;
+ break;
+
+ case '<':
+ outval = "<";
+ break;
+
+ case '>':
+ outval = ">";
+ break;
+
+ case '&':
+ if (this.produceHTML && attr) {
+ len++;
+ } else {
+ outval = "&";
+ }
+ break;
+
+ case '\'':
+ if (this.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) {
+ final 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(final Writer writer) throws IOException {
+ if (this.textBuffer.length() > 0) {
+ final String val = this.normalizeString(this.textBuffer.toString());
+ this.textBuffer.setLength(0);
+ if (val.length() > 0) {
+ this.indent(writer);
+ this.writeEscapedText(writer, val, false);
+ writer.write('\n');
+ }
+ }
+ }
+
+ private void indent(final Writer writer) throws IOException {
+ this.indent(writer, this.indentLevel);
+ }
+
+ private void indent(final Writer writer, final int level) throws IOException {
+ final int size = level * this.indentSize;
+ if (size > 0) {
+ if (this.indentTemplate.length() < size) {
+ final StringBuffer sb = new StringBuffer(this.indentTemplate);
+ for (int i = this.indentTemplate.length(); i < size; i++) {
+ sb.append(' ');
+ }
+ this.indentTemplate = sb.toString();
+ }
+ writer.write(this.indentTemplate.substring(0, size));
+ }
+ }
+
+ private String normalizeString(final String value) {
+ final char[] c = value.toCharArray();
+ final char[] n = new char[c.length];
+ boolean white = true;
+ int pos = 0;
+ for (final char element : c) {
+ if (" \t\n\r".indexOf(element) != -1) {
+ if (!white) {
+ n[pos++] = ' ';
+ white = true;
+ }
+ } else {
+ n[pos++] = element;
+ 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(final Node node, final 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(final Node node, final 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(final Node node, final 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(final Node node, final 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(final Writer writer) throws IOException {
+ try {
+ final BufferedWriter buf = new BufferedWriter(writer, 4096);
+ this.writeNode(buf, this.node);
+ buf.flush();
+ } catch (final 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(final Node node, final 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(final Node node, final 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(final Node node, final 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(final Node node, final 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(final OutputStream output) throws IOException {
+ try {
+ final OutputStreamWriter o = new OutputStreamWriter(output, "UTF8");
+ final BufferedWriter buf = new BufferedWriter(o, 4096);
+ this.writeNode(buf, this.node);
+ buf.flush();
+ } catch (final 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(final Node node) {
+ return new TextWriter(node).toString();
+ }
+
+ public static String toString(final Node node, final 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(final 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(final 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(final Node node) {
+ return new TextWriter(node, true, true).toString();
+ }
+
+ /**
+ * toString returns the node as a String.
+ *
+ * @return The String value
+ */
+ @Override
+ public String toString() {
+ final StringWriter writer = new StringWriter();
+ try {
+ this.write(writer);
+ return writer.toString();
+ } catch (final Exception e) {
+ e.printStackTrace(System.err);
+ return null;
+ }
+ }
}
-
-
package fr.gouv.finances.cp.xemelios.widgets;
+import fr.gouv.finances.cp.xemelios.ui.resulttable.EtatResultTableModel;
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);
+ private final WidgetModel wm;
+ private final ElementModel em;
+
+ /** Creates a new instance of Widget */
+ public AbstractWidget(final WidgetModel wm, final ElementModel em) {
+ super();
+ this.wm = wm;
+ this.em = em;
+ }
+
+ public final WidgetModel getWidgetModel() {
+ return this.wm;
+ }
+
+ public final ElementModel getElementModel() {
+ return this.em;
+ }
+
+ public abstract void run(EtatResultTableModel etrm, int row);
}
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.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
+
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+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.common.config.ElementModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.WidgetModel;
+import fr.gouv.finances.dgfip.xemelios.data.DataHandler;
+
/**
- *
+ *
* @author chm
*/
public class SaveAs extends AbstractWidget {
- private static Logger logger = Logger.getLogger(SaveAs.class);
- private static final String DEFAULT_ENCODING = "ISO-8859-1";
-
-
- /** 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();
- if(encoding==null) encoding=DEFAULT_ENCODING;
- 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);
- }
+ private static Logger logger = Logger.getLogger(SaveAs.class);
+ private static final String DEFAULT_ENCODING = "ISO-8859-1";
+
+ /** Creates a new instance of SaveAs */
+ public SaveAs(final WidgetModel wm, final ElementModel em) {
+ super(wm, em);
+ }
+
+ @Override
+ public void run(final EtatResultTableModel etrm, final int row) {
+ try {
+ final DataHandler dh = etrm.getRowAt(row, 0);
+ final Document doc = dh.getDocument();
+ String encoding = dh.getDocumentEncoding();
+ final TransformerFactory tf = FactoryProvider.getTransformerFactory();
+ final Transformer t = tf.newTransformer();
+ if (encoding == null) {
+ encoding = DEFAULT_ENCODING;
+ }
+ t.setOutputProperty(OutputKeys.ENCODING, encoding);
+ final JFileChooser chooser = new JFileChooser();
+ chooser.setDialogTitle("Enregistrer " + ("male".equals(this.getWidgetModel().getParam("gender").getValue()) ? "le" : "la") + " " + this.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(final 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();
+ final int len = fileName.length();
+ if (fileName.substring(len - 4).indexOf('.') < 0) {
+ fileName = fileName + ".xml";
+ f = new File(fileName);
+ }
+ if (f.exists()) {
+ final 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");
+ final FileOutputStream fos = new FileOutputStream(saveTo, false);
+ final StreamResult sr = new StreamResult(fos);
+ t.transform(new DOMSource(doc), sr);
+ fos.flush();
+ fos.close();
+ }
+ } catch (final Exception ex) {
+ logger.error("in run: ", ex);
+ }
+ }
+
+ private static class LocalFileFilter extends FileFilter {
+ private String ext, description;
+
+ @Override
+ public boolean accept(final File f) {
+ return f.isDirectory() || f.getName().toUpperCase().equals(this.ext);
+ }
- @Override
- public String getDescription() { return description; }
- }
+ @Override
+ public String getDescription() {
+ return this.description;
+ }
+ }
}
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;
+import fr.gouv.finances.cp.xemelios.ui.MainWindow;
+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.common.Constants;
+import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
+import fr.gouv.finances.dgfip.xemelios.common.config.WidgetModel;
+import fr.gouv.finances.dgfip.xemelios.data.DataHandler;
+import fr.gouv.finances.dgfip.xemelios.utils.FileUtils;
+
/**
- *
+ *
* @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);
- }
+ private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(ViewCode.class);
+
+ public ViewCode(final WidgetModel wm, final 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
- }
- }
+ @Override
+ public void run(final EtatResultTableModel etrm, final int row) {
+ try {
+ final DataHandler dh = etrm.getRowAt(row, 0);
+ final Document doc = dh.getDocument();
+ final String encoding = dh.getDocumentEncoding();
+ final TransformerFactory tf = FactoryProvider.getTransformerFactory();
+ final Transformer t = tf.newTransformer(new StreamSource(new File(new File(MainWindow.instance.getEnvProperties().replace("${" + Constants.SYS_PROP_RESOURCES_LOCATION + "}")), "XMLPrettyPrint.xsl")));
+ final File tmp = File.createTempFile("xemelios-data-", ".xml", FileUtils.getTempDir());
+ final FileOutputStream fos = new FileOutputStream(tmp, false);
+ final StreamResult sr = new StreamResult(fos);
+ t.setParameter("title", this.getElementModel().getParent().getParent().getTitre());
+ t.transform(new DOMSource(doc), sr);
+ fos.flush();
+ fos.close();
+ MainWindow.instance.displayHtmlStream(tmp, this.getElementModel().getParent());
+ final Transformer t2 = tf.newTransformer();
+ final ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ t2.transform(new DOMSource(doc), new StreamResult(baos));
+ baos.flush();
+ baos.close();
+ logger.debug(baos.toString());
+ } catch (final Exception ex) {
+ // TODO
+ }
+ }
}