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

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

code style - Unnecessary Final Modifier

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