source: josm/trunk/src/org/openstreetmap/josm/tools/BugReportExceptionHandler.java@ 9990

Last change on this file since 9990 was 8840, checked in by Don-vip, 9 years ago

sonar - squid:S3052 - Fields should not be initialized to default values

  • Property svn:eol-style set to native
File size: 13.2 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.tools;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.Component;
7import java.awt.GridBagConstraints;
8import java.awt.GridBagLayout;
9import java.io.ByteArrayOutputStream;
10import java.io.IOException;
11import java.io.PrintWriter;
12import java.io.StringWriter;
13import java.net.URL;
14import java.nio.ByteBuffer;
15import java.nio.charset.StandardCharsets;
16import java.util.zip.GZIPOutputStream;
17
18import javax.swing.JCheckBox;
19import javax.swing.JLabel;
20import javax.swing.JOptionPane;
21import javax.swing.JPanel;
22import javax.swing.JScrollPane;
23import javax.swing.SwingUtilities;
24
25import org.openstreetmap.josm.Main;
26import org.openstreetmap.josm.actions.ShowStatusReportAction;
27import org.openstreetmap.josm.data.Version;
28import org.openstreetmap.josm.gui.ExtendedDialog;
29import org.openstreetmap.josm.gui.preferences.plugin.PluginPreference;
30import org.openstreetmap.josm.gui.widgets.JMultilineLabel;
31import org.openstreetmap.josm.gui.widgets.JosmTextArea;
32import org.openstreetmap.josm.gui.widgets.UrlLabel;
33import org.openstreetmap.josm.plugins.PluginDownloadTask;
34import org.openstreetmap.josm.plugins.PluginHandler;
35
36/**
37 * An exception handler that asks the user to send a bug report.
38 *
39 * @author imi
40 */
41public final class BugReportExceptionHandler implements Thread.UncaughtExceptionHandler {
42
43 private static boolean handlingInProgress;
44 private static volatile BugReporterThread bugReporterThread;
45 private static int exceptionCounter;
46 private static boolean suppressExceptionDialogs;
47
48 private static class BugReporterThread extends Thread {
49
50 private final class BugReporterWorker implements Runnable {
51 private final PluginDownloadTask pluginDownloadTask;
52
53 private BugReporterWorker(PluginDownloadTask pluginDownloadTask) {
54 this.pluginDownloadTask = pluginDownloadTask;
55 }
56
57 @Override
58 public void run() {
59 // Then ask for submitting a bug report, for exceptions thrown from a plugin too, unless updated to a new version
60 if (pluginDownloadTask == null) {
61 String[] buttonTexts = new String[] {tr("Do nothing"), tr("Report Bug")};
62 String[] buttonIcons = new String[] {"cancel", "bug"};
63 int defaultButtonIdx = 1;
64 String message = tr("An unexpected exception occurred.<br>" +
65 "This is always a coding error. If you are running the latest<br>" +
66 "version of JOSM, please consider being kind and file a bug report."
67 );
68 // Check user is running current tested version, the error may already be fixed
69 int josmVersion = Version.getInstance().getVersion();
70 if (josmVersion != Version.JOSM_UNKNOWN_VERSION) {
71 try {
72 int latestVersion = Integer.parseInt(new WikiReader().
73 read(Main.getJOSMWebsite()+"/wiki/TestedVersion?format=txt").trim());
74 if (latestVersion > josmVersion) {
75 buttonTexts = new String[] {tr("Do nothing"), tr("Update JOSM"), tr("Report Bug")};
76 buttonIcons = new String[] {"cancel", "download", "bug"};
77 defaultButtonIdx = 2;
78 message = tr("An unexpected exception occurred. This is always a coding error.<br><br>" +
79 "However, you are running an old version of JOSM ({0}),<br>" +
80 "instead of using the current tested version (<b>{1}</b>).<br><br>"+
81 "<b>Please update JOSM</b> before considering to file a bug report.",
82 String.valueOf(josmVersion), String.valueOf(latestVersion));
83 }
84 } catch (IOException | NumberFormatException e) {
85 Main.warn("Unable to detect latest version of JOSM: "+e.getMessage());
86 }
87 }
88 // Show dialog
89 ExtendedDialog ed = new ExtendedDialog(Main.parent, tr("Unexpected Exception"), buttonTexts);
90 ed.setButtonIcons(buttonIcons);
91 ed.setIcon(JOptionPane.ERROR_MESSAGE);
92 ed.setCancelButton(1);
93 ed.setDefaultButton(defaultButtonIdx);
94 JPanel pnl = new JPanel(new GridBagLayout());
95 pnl.add(new JLabel("<html>" + message + "</html>"), GBC.eol());
96 JCheckBox cbSuppress = null;
97 if (exceptionCounter > 1) {
98 cbSuppress = new JCheckBox(tr("Suppress further error dialogs for this session."));
99 pnl.add(cbSuppress, GBC.eol());
100 }
101 ed.setContent(pnl);
102 ed.setFocusOnDefaultButton(true);
103 ed.showDialog();
104 if (cbSuppress != null && cbSuppress.isSelected()) {
105 suppressExceptionDialogs = true;
106 }
107 if (ed.getValue() <= 1) {
108 // "Do nothing"
109 return;
110 } else if (ed.getValue() < buttonTexts.length) {
111 // "Update JOSM"
112 try {
113 Main.platform.openUrl(Main.getJOSMWebsite());
114 } catch (IOException e) {
115 Main.warn("Unable to access JOSM website: "+e.getMessage());
116 }
117 } else {
118 // "Report bug"
119 askForBugReport(e);
120 }
121 } else {
122 // Ask for restart to install new plugin
123 PluginPreference.notifyDownloadResults(
124 Main.parent, pluginDownloadTask, !pluginDownloadTask.getDownloadedPlugins().isEmpty());
125 }
126 }
127 }
128
129 private final Throwable e;
130
131 /**
132 * Constructs a new {@code BugReporterThread}.
133 * @param t the exception
134 */
135 BugReporterThread(Throwable t) {
136 super("Bug Reporter");
137 this.e = t;
138 }
139
140 @Override
141 public void run() {
142 // Give the user a chance to deactivate the plugin which threw the exception (if it was thrown from a plugin)
143 SwingUtilities.invokeLater(new BugReporterWorker(PluginHandler.updateOrdisablePluginAfterException(e)));
144 }
145 }
146
147 @Override
148 public void uncaughtException(Thread t, Throwable e) {
149 handleException(e);
150 }
151
152 /**
153 * Handles the given throwable object
154 * @param t The throwable object
155 */
156 public void handle(Throwable t) {
157 handleException(t);
158 }
159
160 /**
161 * Handles the given exception
162 * @param e the exception
163 */
164 public static void handleException(final Throwable e) {
165 if (handlingInProgress || suppressExceptionDialogs)
166 return; // we do not handle secondary exceptions, this gets too messy
167 if (bugReporterThread != null && bugReporterThread.isAlive())
168 return;
169 handlingInProgress = true;
170 exceptionCounter++;
171 try {
172 Main.error(e);
173 if (Main.parent != null) {
174 if (e instanceof OutOfMemoryError) {
175 // do not translate the string, as translation may raise an exception
176 JOptionPane.showMessageDialog(Main.parent, "JOSM is out of memory. " +
177 "Strange things may happen.\nPlease restart JOSM with the -Xmx###M option,\n" +
178 "where ### is the number of MB assigned to JOSM (e.g. 256).\n" +
179 "Currently, " + Runtime.getRuntime().maxMemory()/1024/1024 + " MB are available to JOSM.",
180 "Error",
181 JOptionPane.ERROR_MESSAGE
182 );
183 return;
184 }
185
186 bugReporterThread = new BugReporterThread(e);
187 bugReporterThread.start();
188 }
189 } finally {
190 handlingInProgress = false;
191 }
192 }
193
194 private static void askForBugReport(final Throwable e) {
195 try {
196 final int maxlen = 6000;
197 StringWriter stack = new StringWriter();
198 e.printStackTrace(new PrintWriter(stack));
199
200 String text = ShowStatusReportAction.getReportHeader() + stack.getBuffer().toString();
201 String urltext = text.replaceAll("\r", "");
202 if (urltext.length() > maxlen) {
203 urltext = urltext.substring(0, maxlen);
204 int idx = urltext.lastIndexOf('\n');
205 // cut whole line when not loosing too much
206 if (maxlen-idx < 200) {
207 urltext = urltext.substring(0, idx+1);
208 }
209 urltext += "...<snip>...\n";
210 }
211
212 JPanel p = new JPanel(new GridBagLayout());
213 p.add(new JMultilineLabel(
214 tr("You have encountered an error in JOSM. Before you file a bug report " +
215 "make sure you have updated to the latest version of JOSM here:")),
216 GBC.eol().fill(GridBagConstraints.HORIZONTAL));
217 p.add(new UrlLabel(Main.getJOSMWebsite(), 2), GBC.eop().insets(8, 0, 0, 0));
218 p.add(new JMultilineLabel(
219 tr("You should also update your plugins. If neither of those help please " +
220 "file a bug report in our bugtracker using this link:")),
221 GBC.eol().fill(GridBagConstraints.HORIZONTAL));
222 p.add(getBugReportUrlLabel(urltext), GBC.eop().insets(8, 0, 0, 0));
223 p.add(new JMultilineLabel(
224 tr("There the error information provided below should already be " +
225 "filled in for you. Please include information on how to reproduce " +
226 "the error and try to supply as much detail as possible.")),
227 GBC.eop().fill(GridBagConstraints.HORIZONTAL));
228 p.add(new JMultilineLabel(
229 tr("Alternatively, if that does not work you can manually fill in the information " +
230 "below at this URL:")), GBC.eol().fill(GridBagConstraints.HORIZONTAL));
231 p.add(new UrlLabel(Main.getJOSMWebsite()+"/newticket", 2), GBC.eop().insets(8, 0, 0, 0));
232
233 // Wiki formatting for manual copy-paste
234 text = "{{{\n"+text+"}}}";
235
236 if (Utils.copyToClipboard(text)) {
237 p.add(new JLabel(tr("(The text has already been copied to your clipboard.)")),
238 GBC.eop().fill(GridBagConstraints.HORIZONTAL));
239 }
240
241 JosmTextArea info = new JosmTextArea(text, 18, 60);
242 info.setCaretPosition(0);
243 info.setEditable(false);
244 p.add(new JScrollPane(info), GBC.eop().fill());
245
246 for (Component c: p.getComponents()) {
247 if (c instanceof JMultilineLabel) {
248 ((JMultilineLabel) c).setMaxWidth(400);
249 }
250 }
251
252 JOptionPane.showMessageDialog(Main.parent, p, tr("You have encountered a bug in JOSM"), JOptionPane.ERROR_MESSAGE);
253 } catch (Exception e1) {
254 Main.error(e1);
255 }
256 }
257
258 /**
259 * Determines if an exception is currently being handled
260 * @return {@code true} if an exception is currently being handled, {@code false} otherwise
261 */
262 public static boolean exceptionHandlingInProgress() {
263 return handlingInProgress;
264 }
265
266 /**
267 * Replies the URL to create a JOSM bug report with the given debug text
268 * @param debugText The debug text to provide us
269 * @return The URL to create a JOSM bug report with the given debug text
270 * @since 5849
271 */
272 public static URL getBugReportUrl(String debugText) {
273 try (
274 ByteArrayOutputStream out = new ByteArrayOutputStream();
275 GZIPOutputStream gzip = new GZIPOutputStream(out)
276 ) {
277 gzip.write(debugText.getBytes(StandardCharsets.UTF_8));
278 gzip.finish();
279
280 return new URL(Main.getJOSMWebsite()+"/josmticket?" +
281 "gdata="+Base64.encode(ByteBuffer.wrap(out.toByteArray()), true));
282 } catch (IOException e) {
283 Main.error(e);
284 return null;
285 }
286 }
287
288 /**
289 * Replies the URL label to create a JOSM bug report with the given debug text
290 * @param debugText The debug text to provide us
291 * @return The URL label to create a JOSM bug report with the given debug text
292 * @since 5849
293 */
294 public static UrlLabel getBugReportUrlLabel(String debugText) {
295 URL url = getBugReportUrl(debugText);
296 if (url != null) {
297 return new UrlLabel(url.toString(), Main.getJOSMWebsite()+"/josmticket?...", 2);
298 }
299 return null;
300 }
301}
Note: See TracBrowser for help on using the repository browser.