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

Last change on this file since 7783 was 7419, checked in by Don-vip, 10 years ago

fix #7708 - pre-formatting of manual bug reports

  • Property svn:eol-style set to native
File size: 13.0 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 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 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(Main.parent, pluginDownloadTask);
130 }
131 }
132 });
133 }
134 }
135
136 @Override
137 public void uncaughtException(Thread t, Throwable e) {
138 handleException(e);
139 }
140
141 /**
142 * Handles the given throwable object
143 * @param t The throwable object
144 */
145 public void handle(Throwable t) {
146 handleException(t);
147 }
148
149 /**
150 * Handles the given exception
151 * @param e the exception
152 */
153 public static void handleException(final Throwable e) {
154 if (handlingInProgress || suppressExceptionDialogs)
155 return; // we do not handle secondary exceptions, this gets too messy
156 if (bugReporterThread != null && bugReporterThread.isAlive())
157 return;
158 handlingInProgress = true;
159 exceptionCounter++;
160 try {
161 Main.error(e);
162 if (Main.parent != null) {
163 if (e instanceof OutOfMemoryError) {
164 // do not translate the string, as translation may raise an exception
165 JOptionPane.showMessageDialog(Main.parent, "JOSM is out of memory. " +
166 "Strange things may happen.\nPlease restart JOSM with the -Xmx###M option,\n" +
167 "where ### is the number of MB assigned to JOSM (e.g. 256).\n" +
168 "Currently, " + Runtime.getRuntime().maxMemory()/1024/1024 + " MB are available to JOSM.",
169 "Error",
170 JOptionPane.ERROR_MESSAGE
171 );
172 return;
173 }
174
175 bugReporterThread = new BugReporterThread(e);
176 bugReporterThread.start();
177 }
178 } finally {
179 handlingInProgress = false;
180 }
181 }
182
183 private static void askForBugReport(final Throwable e) {
184 try {
185 final int maxlen = 6000;
186 StringWriter stack = new StringWriter();
187 e.printStackTrace(new PrintWriter(stack));
188
189 String text = ShowStatusReportAction.getReportHeader() + stack.getBuffer().toString();
190 String urltext = text.replaceAll("\r","");
191 if (urltext.length() > maxlen) {
192 urltext = urltext.substring(0,maxlen);
193 int idx = urltext.lastIndexOf('\n');
194 // cut whole line when not loosing too much
195 if (maxlen-idx < 200) {
196 urltext = urltext.substring(0,idx+1);
197 }
198 urltext += "...<snip>...\n";
199 }
200
201 JPanel p = new JPanel(new GridBagLayout());
202 p.add(new JMultilineLabel(
203 tr("You have encountered an error in JOSM. Before you file a bug report " +
204 "make sure you have updated to the latest version of JOSM here:")),
205 GBC.eol().fill(GridBagConstraints.HORIZONTAL));
206 p.add(new UrlLabel(Main.getJOSMWebsite(),2), GBC.eop().insets(8,0,0,0));
207 p.add(new JMultilineLabel(
208 tr("You should also update your plugins. If neither of those help please " +
209 "file a bug report in our bugtracker using this link:")),
210 GBC.eol().fill(GridBagConstraints.HORIZONTAL));
211 p.add(getBugReportUrlLabel(urltext), GBC.eop().insets(8,0,0,0));
212 p.add(new JMultilineLabel(
213 tr("There the error information provided below should already be " +
214 "filled in for you. Please include information on how to reproduce " +
215 "the error and try to supply as much detail as possible.")),
216 GBC.eop().fill(GridBagConstraints.HORIZONTAL));
217 p.add(new JMultilineLabel(
218 tr("Alternatively, if that does not work you can manually fill in the information " +
219 "below at this URL:")), GBC.eol().fill(GridBagConstraints.HORIZONTAL));
220 p.add(new UrlLabel(Main.getJOSMWebsite()+"/newticket",2), GBC.eop().insets(8,0,0,0));
221
222 // Wiki formatting for manual copy-paste
223 text = "{{{\n"+text+"}}}";
224
225 if (Utils.copyToClipboard(text)) {
226 p.add(new JLabel(tr("(The text has already been copied to your clipboard.)")),
227 GBC.eop().fill(GridBagConstraints.HORIZONTAL));
228 }
229
230 JosmTextArea info = new JosmTextArea(text, 18, 60);
231 info.setCaretPosition(0);
232 info.setEditable(false);
233 p.add(new JScrollPane(info), GBC.eop().fill());
234
235 for (Component c: p.getComponents()) {
236 if (c instanceof JMultilineLabel) {
237 ((JMultilineLabel)c).setMaxWidth(400);
238 }
239 }
240
241 JOptionPane.showMessageDialog(Main.parent, p, tr("You have encountered a bug in JOSM"), JOptionPane.ERROR_MESSAGE);
242 } catch (Exception e1) {
243 Main.error(e1);
244 }
245 }
246
247 /**
248 * Determines if an exception is currently being handled
249 * @return {@code true} if an exception is currently being handled, {@code false} otherwise
250 */
251 public static boolean exceptionHandlingInProgress() {
252 return handlingInProgress;
253 }
254
255 /**
256 * Replies the URL to create a JOSM bug report with the given debug text
257 * @param debugText The debug text to provide us
258 * @return The URL to create a JOSM bug report with the given debug text
259 * @since 5849
260 */
261 public static URL getBugReportUrl(String debugText) {
262 try (
263 ByteArrayOutputStream out = new ByteArrayOutputStream();
264 GZIPOutputStream gzip = new GZIPOutputStream(out)
265 ) {
266 gzip.write(debugText.getBytes(StandardCharsets.UTF_8));
267 gzip.finish();
268
269 return new URL(Main.getJOSMWebsite()+"/josmticket?" +
270 "gdata="+Base64.encode(ByteBuffer.wrap(out.toByteArray()), true));
271 } catch (IOException e) {
272 Main.error(e);
273 return null;
274 }
275 }
276
277 /**
278 * Replies the URL label to create a JOSM bug report with the given debug text
279 * @param debugText The debug text to provide us
280 * @return The URL label to create a JOSM bug report with the given debug text
281 * @since 5849
282 */
283 public static final UrlLabel getBugReportUrlLabel(String debugText) {
284 URL url = getBugReportUrl(debugText);
285 if (url != null) {
286 return new UrlLabel(url.toString(), Main.getJOSMWebsite()+"/josmticket?...", 2);
287 }
288 return null;
289 }
290}
Note: See TracBrowser for help on using the repository browser.