OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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