OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Rev 90 | Rev 144 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
17 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 /*
15
 * ExceptionHandler created on 7 mai 2004
16
 */
17
package org.openconcerto.utils;
18
 
83 ilm 19
import org.openconcerto.utils.SystemInfo.Info;
20
import org.openconcerto.utils.cc.IFactory;
73 ilm 21
import org.openconcerto.utils.io.PercentEncoder;
22
 
17 ilm 23
import java.awt.Component;
24
import java.awt.Desktop;
25
import java.awt.Desktop.Action;
26
import java.awt.Dialog;
27
import java.awt.Dimension;
28
import java.awt.Font;
29
import java.awt.Frame;
30
import java.awt.GraphicsEnvironment;
31
import java.awt.GridBagConstraints;
32
import java.awt.GridBagLayout;
33
import java.awt.Insets;
34
import java.awt.Toolkit;
35
import java.awt.Window;
36
import java.awt.datatransfer.Clipboard;
37
import java.awt.datatransfer.StringSelection;
38
import java.awt.event.ActionEvent;
39
import java.awt.event.ActionListener;
40
import java.awt.event.WindowAdapter;
41
import java.awt.event.WindowEvent;
73 ilm 42
import java.io.BufferedReader;
43
import java.io.InputStreamReader;
44
import java.io.OutputStream;
45
import java.net.HttpURLConnection;
17 ilm 46
import java.net.URI;
73 ilm 47
import java.net.URL;
48
import java.nio.charset.Charset;
83 ilm 49
import java.util.Map;
65 ilm 50
import java.util.concurrent.Future;
51
import java.util.concurrent.FutureTask;
52
import java.util.logging.Level;
17 ilm 53
import java.util.logging.Logger;
73 ilm 54
import java.util.regex.Pattern;
17 ilm 55
 
56
import javax.swing.AbstractAction;
57
import javax.swing.ImageIcon;
58
import javax.swing.JButton;
59
import javax.swing.JDialog;
60
import javax.swing.JLabel;
73 ilm 61
import javax.swing.JOptionPane;
17 ilm 62
import javax.swing.JPanel;
63
import javax.swing.JScrollPane;
64
import javax.swing.JSeparator;
65
import javax.swing.JTextArea;
66
import javax.swing.ScrollPaneConstants;
67
import javax.swing.SwingUtilities;
68
import javax.swing.UIManager;
73 ilm 69
import javax.swing.text.JTextComponent;
17 ilm 70
 
71
/**
72
 * Allow to display an exception both on the GUI and on the console.
73
 *
74
 * @author ILM Informatique 7 mai 2004
75
 */
76
public class ExceptionHandler extends RuntimeException {
77
 
73 ilm 78
    private static final Pattern NL_PATTERN = Pattern.compile("\r?\n");
17 ilm 79
    private static final String ILM_CONTACT = "http://www.ilm-informatique.fr/contact";
80
    private static String ForumURL = null;
132 ilm 81
    private static boolean showProbably = false;
83 ilm 82
    private static IFactory<String> SOFTWARE_INFOS = null;
17 ilm 83
 
84
    public static void setForumURL(String url) {
85
        ForumURL = url;
86
    }
87
 
132 ilm 88
    public synchronized static void setShowProbably(boolean showProbably) {
89
        ExceptionHandler.showProbably = showProbably;
90
    }
91
 
92
    public synchronized static boolean isShowProbably() {
93
        return ExceptionHandler.showProbably;
94
    }
95
 
83 ilm 96
    public synchronized static void setSoftwareInformations(final IFactory<String> f) {
97
        SOFTWARE_INFOS = f;
98
    }
99
 
100
    public synchronized static String computeSoftwareInformations() {
101
        if (SOFTWARE_INFOS == null)
102
            return "";
103
        return SOFTWARE_INFOS.createChecked();
104
    }
105
 
17 ilm 106
    static private void copyToClipboard(final String s) {
107
        final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
108
        final StringSelection data = new StringSelection(s);
109
        clipboard.setContents(data, data);
110
    }
111
 
25 ilm 112
    /**
113
     * Display the passed message. Note: this method doesn't block.
114
     *
115
     * @param comp the modal parent of the error window.
116
     * @param msg the message to display.
117
     * @param originalExn the cause, can be <code>null</code>.
118
     * @return an exception.
119
     */
65 ilm 120
    static public ExceptionHandler handle(Component comp, String msg, Throwable originalExn) {
17 ilm 121
        return new ExceptionHandler(comp, msg, originalExn, false);
122
    }
123
 
124
    static public RuntimeException handle(String msg, Throwable originalExn) {
125
        return handle(null, msg, originalExn);
126
    }
127
 
128
    static public RuntimeException handle(String msg) {
129
        return handle(msg, null);
130
    }
131
 
25 ilm 132
    /**
133
     * Display the passed message and quit. Note: this method blocks until the user closes the
134
     * window (then exits).
135
     *
136
     * @param msg the message to display.
137
     * @param originalExn the cause, can be <code>null</code>.
138
     * @return an exception.
139
     */
17 ilm 140
    static public RuntimeException die(String msg, Throwable originalExn) {
141
        return new ExceptionHandler(null, msg, originalExn);
142
    }
143
 
144
    static public RuntimeException die(String msg) {
145
        return die(msg, null);
146
    }
147
 
148
    private static Logger getLogger() {
149
        return Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
150
    }
151
 
152
    // the comp on which to display the popup, may be null
153
    private final Component comp;
65 ilm 154
    private final Future<?> future;
17 ilm 155
    private static boolean forceUI;
156
 
157
    public static void setForceUI(boolean forceUI) {
158
        ExceptionHandler.forceUI = forceUI;
159
    }
160
 
65 ilm 161
    private Future<?> display(final boolean error) {
17 ilm 162
        final String msg = this.getMessage();
80 ilm 163
        // write out the message as soon as possible
164
        getLogger().log(error ? Level.SEVERE : Level.INFO, null, this);
165
        // then show it to the user
17 ilm 166
        if (!GraphicsEnvironment.isHeadless() || forceUI) {
167
            if (SwingUtilities.isEventDispatchThread()) {
80 ilm 168
                showMsgHardened(msg, error);
25 ilm 169
            } else {
65 ilm 170
                final FutureTask<?> run = new FutureTask<Object>(new Runnable() {
17 ilm 171
                    public void run() {
80 ilm 172
                        showMsgHardened(msg, error);
17 ilm 173
                    }
65 ilm 174
                }, null);
25 ilm 175
                if (error) {
176
                    try {
177
                        SwingUtilities.invokeAndWait(run);
178
                    } catch (Exception e) {
179
                        e.printStackTrace();
180
                        System.exit(1);
181
                    }
182
                } else {
183
                    SwingUtilities.invokeLater(run);
184
                }
65 ilm 185
                return run;
25 ilm 186
            }
17 ilm 187
        }
65 ilm 188
        return null;
17 ilm 189
    }
190
 
65 ilm 191
    public final Future<?> getDialogFuture() {
192
        return this.future;
193
    }
194
 
80 ilm 195
    protected final void showMsgHardened(final String msg, final boolean error) {
196
        try {
197
            showMsg(msg, error);
198
        } catch (Throwable e) {
199
            // sometimes the VM cannot display the dialog, in that case don't crash the EDT as the
200
            // message has already been logged. Further if this class is used in
201
            // Thread.setDefaultUncaughtExceptionHandler(), it will create an infinite loop.
202
            e = new Exception("Couldn't display message", e);
203
            e.printStackTrace();
204
            try {
205
                // last ditch effort
206
                JOptionPane.showMessageDialog(null, e.getMessage() + " : " + msg);
207
            } catch (Throwable e2) {
208
            }
209
        }
210
    }
211
 
17 ilm 212
    protected final void showMsg(final String msg, final boolean quit) {
213
        final JPanel p = new JPanel();
214
        p.setLayout(new GridBagLayout());
215
        final GridBagConstraints c = new GridBagConstraints();
216
        c.insets = new Insets(10, 10, 10, 10);
217
        c.gridx = 0;
218
        c.gridy = 0;
219
        c.fill = GridBagConstraints.BOTH;
80 ilm 220
        final JImage im = new JImage(new ImageIcon(ExceptionHandler.class.getResource("error.png")));
17 ilm 221
        final JLabel l = new JLabel("Une erreur est survenue");
222
        l.setFont(l.getFont().deriveFont(Font.BOLD));
223
 
224
        final JTextArea textArea = new JTextArea();
225
        textArea.setFont(textArea.getFont().deriveFont(11f));
226
 
227
        c.gridheight = 3;
228
        p.add(im, c);
229
        c.insets = new Insets(2, 4, 2, 4);
230
        c.gridheight = 1;
231
        c.gridx++;
232
        c.weightx = 1;
132 ilm 233
        c.gridwidth = 1;
17 ilm 234
        p.add(l, c);
235
        c.gridy++;
73 ilm 236
 
237
        final JLabel lError = new JLabel("<html>" + NL_PATTERN.matcher(msg).replaceAll("<br>") + "</html>");
17 ilm 238
        p.add(lError, c);
73 ilm 239
        c.gridy++;
17 ilm 240
 
132 ilm 241
        if (isShowProbably()) {
242
            p.add(new JLabel("Il s'agit probablement d'une mauvaise configuration ou installation du logiciel."), c);
243
            c.gridy++;
244
        }
17 ilm 245
 
246
        c.gridx = 0;
247
        c.weighty = 0;
132 ilm 248
        c.gridwidth = 2;
17 ilm 249
 
132 ilm 250
        final JPanel btnPanel = new JPanel();
17 ilm 251
        final Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
252
        final boolean browseSupported = desktop != null && desktop.isSupported(Action.BROWSE);
253
        if (ForumURL != null) {
254
            final javax.swing.Action communityAction;
255
            if (browseSupported) {
256
                communityAction = new AbstractAction("Consulter le forum") {
257
                    @Override
258
                    public void actionPerformed(ActionEvent e) {
73 ilm 259
                        if (desktop != null) {
260
                            try {
261
                                desktop.browse(new URI(ForumURL));
262
                            } catch (Exception e1) {
263
                                e1.printStackTrace();
264
                            }
17 ilm 265
                        }
266
                    }
267
                };
268
            } else {
269
                communityAction = new AbstractAction("Copier l'adresse du forum") {
270
                    @Override
271
                    public void actionPerformed(ActionEvent e) {
272
                        copyToClipboard(ForumURL);
273
                    }
274
                };
275
            }
132 ilm 276
            btnPanel.add(new JButton(communityAction));
17 ilm 277
        }
278
 
279
        final javax.swing.Action supportAction;
132 ilm 280
        if (browseSupported) {
17 ilm 281
            supportAction = new AbstractAction("Contacter l'assistance") {
282
                @Override
283
                public void actionPerformed(ActionEvent e) {
73 ilm 284
                    if (desktop != null) {
285
                        try {
286
                            desktop.browse(URI.create(ILM_CONTACT));
287
                        } catch (Exception e1) {
288
                            e1.printStackTrace();
289
                        }
17 ilm 290
                    }
291
 
292
                }
293
            };
132 ilm 294
        } else {
17 ilm 295
            supportAction = new AbstractAction("Copier l'adresse de l'assistance") {
296
                @Override
297
                public void actionPerformed(ActionEvent e) {
298
                    copyToClipboard(ILM_CONTACT);
299
                }
300
            };
132 ilm 301
        }
302
        btnPanel.add(new JButton(supportAction));
17 ilm 303
 
132 ilm 304
        btnPanel.add(new JButton(new AbstractAction("Copier l'erreur") {
305
            @Override
306
            public void actionPerformed(ActionEvent e) {
307
                copyToClipboard(textArea.getText());
308
            }
309
        }));
73 ilm 310
 
311
        final javax.swing.Action submitAction = new AbstractAction("Soumettre l'erreur") {
312
            @Override
313
            public void actionPerformed(ActionEvent e) {
314
                submitError(p, textArea);
315
            }
316
 
317
            private void submitError(final JPanel p, final JTextComponent textArea) {
318
                final Charset cs = StringUtils.UTF8;
319
                try {
320
                    ProductInfo productInfo = ProductInfo.getInstance();
321
 
322
                    String name = "", version = "";
323
                    if (productInfo != null) {
324
                        name = productInfo.getName();
325
                        version = productInfo.getProperty(ProductInfo.VERSION, version);
326
                    }
83 ilm 327
 
328
                    final Map<Info, String> systemInfos = SystemInfo.get(false);
329
                    final String os = systemInfos.remove(Info.OS);
330
                    final String java = systemInfos.toString();
132 ilm 331
                    final String encodedData = "java=" + PercentEncoder.encode(java, cs) + "&os=" + PercentEncoder.encode(os, cs) + "&software=" + PercentEncoder.encode(name + version, cs) + "&stack="
332
                            + PercentEncoder.encode(computeSoftwareInformations() + "\n\n" + textArea.getText(), cs);
73 ilm 333
                    final String request = "http://bugreport.ilm-informatique.fr:5000/bugreport";
334
                    final URL url = new URL(request);
335
                    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
336
                    connection.setDoOutput(true);
337
                    connection.setRequestMethod("POST");
338
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
339
                    connection.setRequestProperty("charset", cs.name());
340
                    final byte[] bytes = encodedData.getBytes(cs);
341
                    connection.setRequestProperty("Content-Length", String.valueOf(bytes.length));
342
 
343
                    final OutputStream outputStream = connection.getOutputStream();
344
                    outputStream.write(bytes);
345
                    outputStream.flush();
346
 
347
                    // Get the response
348
                    final StringBuffer answer = new StringBuffer();
349
                    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
350
                    String line;
351
                    while ((line = reader.readLine()) != null) {
352
                        answer.append(line);
353
                    }
354
                    outputStream.close();
355
                    reader.close();
356
                    connection.disconnect();
357
 
358
                    JOptionPane.showMessageDialog(p, "Merci d'avoir envoyé le rapport d'erreur au service technique.\nIl sera analysé prochainement.");
359
                } catch (Exception ex) {
360
                    ex.printStackTrace();
361
                }
362
            }
363
        };
364
 
132 ilm 365
        btnPanel.add(new JButton(submitAction));
73 ilm 366
 
132 ilm 367
        c.fill = GridBagConstraints.NONE;
368
        c.anchor = GridBagConstraints.EAST;
369
        p.add(btnPanel, c);
370
 
17 ilm 371
        c.gridy++;
372
        c.gridx = 0;
132 ilm 373
        c.gridwidth = 2;
17 ilm 374
        c.fill = GridBagConstraints.BOTH;
375
        c.insets = new Insets(0, 0, 0, 0);
376
        p.add(new JSeparator(), c);
377
 
378
        c.gridx = 0;
379
        c.gridy++;
380
        c.insets = new Insets(2, 4, 2, 4);
381
        p.add(new JLabel("Détails de l'erreur:"), c);
382
        c.insets = new Insets(0, 0, 0, 0);
383
        c.gridy++;
384
        String message = this.getCause() == null ? null : this.getCause().getMessage();
385
        if (message == null) {
386
            message = msg;
387
        } else {
388
            message = msg + "\n\n" + message;
389
        }
390
        message += "\n";
391
        message += getTrace();
392
        textArea.setText(message);
393
        textArea.setEditable(false);
394
        // Scroll
395
        JScrollPane scroll = new JScrollPane(textArea);
396
        scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
397
        scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
398
        scroll.getViewport().setMinimumSize(new Dimension(200, 300));
399
        c.weighty = 1;
400
        c.gridx = 0;
401
        c.gridy++;
402
        p.add(scroll, c);
403
 
404
        c.gridy++;
405
        c.fill = GridBagConstraints.NONE;
406
        c.weighty = 0;
407
        c.insets = new Insets(2, 4, 2, 4);
408
        final JButton buttonClose = new JButton("Fermer");
409
        p.add(buttonClose, c);
410
 
411
        final Window window = this.comp == null ? null : SwingUtilities.getWindowAncestor(this.comp);
412
        final JDialog f;
413
        if (window instanceof Frame) {
414
            f = new JDialog((Frame) window, "Erreur", true);
415
        } else {
416
            f = new JDialog((Dialog) window, "Erreur", true);
417
        }
418
        f.setContentPane(p);
419
        f.pack();
420
        f.setSize(580, 680);
421
        f.setMinimumSize(new Dimension(380, 380));
422
        f.setLocationRelativeTo(this.comp);
423
        final ActionListener al = new ActionListener() {
424
 
425
            @Override
426
            public void actionPerformed(ActionEvent e) {
427
                if (quit) {
428
                    System.exit(1);
429
                } else {
430
                    f.dispose();
431
                }
432
 
433
            }
434
        };
435
        buttonClose.addActionListener(al);
436
        // cannot set EXIT_ON_CLOSE on JDialog
437
        f.addWindowListener(new WindowAdapter() {
438
            @Override
439
            public void windowClosing(WindowEvent e) {
440
                al.actionPerformed(null);
441
            }
442
        });
90 ilm 443
 
444
        f.setVisible(true);
17 ilm 445
    }
446
 
447
    private String getTrace() {
448
        return ExceptionUtils.getStackTrace(this);
449
    }
450
 
451
    /**
452
     * Affiche l'erreur et quitte.
453
     *
454
     * @param comp the component upon which to display the popup.
455
     * @param msg le message d'erreur à afficher.
456
     * @param cause la cause de l'exception (peut être <code>null</code>).
457
     */
458
    private ExceptionHandler(Component comp, String msg, Throwable cause) {
459
        this(comp, msg, cause, true);
460
    }
461
 
462
    /**
463
     * Affiche l'erreur et quitte suivant l'option passée.
464
     *
465
     * @param comp the component upon which to display the popup.
466
     * @param msg the error message to display.
467
     * @param cause the cause of the exception (maybe <code>null</code>).
468
     * @param quit if the VM must exit.
469
     */
470
    private ExceptionHandler(Component comp, String msg, Throwable cause, boolean quit) {
471
        super(msg, cause);
472
        this.comp = comp;
65 ilm 473
        this.future = this.display(quit);
17 ilm 474
    }
475
 
476
    public static void main(String[] args) throws Exception {
477
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
73 ilm 478
        ExceptionHandler.handle("Fichier de configuration corrompu\n\nmulti\nline", new IllegalStateException("Id manquant"));
17 ilm 479
    }
480
}