OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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