source: josm/trunk/src/org/openstreetmap/josm/actions/ShowStatusReportAction.java@ 10933

Last change on this file since 10933 was 10933, checked in by Don-vip, 8 years ago

rework status report to avoid additional comma at the end of display screens

  • Property svn:eol-style set to native
File size: 13.5 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.actions;
3
4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
5import static org.openstreetmap.josm.tools.I18n.tr;
6
7import java.awt.Dimension;
8import java.awt.DisplayMode;
9import java.awt.GraphicsEnvironment;
10import java.awt.event.ActionEvent;
11import java.awt.event.KeyEvent;
12import java.lang.management.ManagementFactory;
13import java.util.ArrayList;
14import java.util.Arrays;
15import java.util.Collection;
16import java.util.HashSet;
17import java.util.List;
18import java.util.ListIterator;
19import java.util.Locale;
20import java.util.Map;
21import java.util.Map.Entry;
22import java.util.Set;
23import java.util.stream.Collectors;
24
25import org.openstreetmap.josm.Main;
26import org.openstreetmap.josm.data.Version;
27import org.openstreetmap.josm.data.osm.DataSet;
28import org.openstreetmap.josm.data.osm.DatasetConsistencyTest;
29import org.openstreetmap.josm.data.preferences.Setting;
30import org.openstreetmap.josm.gui.ExtendedDialog;
31import org.openstreetmap.josm.gui.preferences.SourceEditor;
32import org.openstreetmap.josm.gui.preferences.map.MapPaintPreference;
33import org.openstreetmap.josm.gui.preferences.map.TaggingPresetPreference;
34import org.openstreetmap.josm.gui.preferences.validator.ValidatorTagCheckerRulesPreference;
35import org.openstreetmap.josm.gui.util.GuiHelper;
36import org.openstreetmap.josm.io.OsmApi;
37import org.openstreetmap.josm.plugins.PluginHandler;
38import org.openstreetmap.josm.tools.PlatformHookUnixoid;
39import org.openstreetmap.josm.tools.Shortcut;
40import org.openstreetmap.josm.tools.Utils;
41import org.openstreetmap.josm.tools.bugreport.BugReportSender;
42import org.openstreetmap.josm.tools.bugreport.DebugTextDisplay;
43
44/**
45 * @author xeen
46 *
47 * Opens a dialog with useful status information like version numbers for Java, JOSM and plugins
48 * Also includes preferences with stripped username and password
49 */
50public final class ShowStatusReportAction extends JosmAction {
51
52 /**
53 * Constructs a new {@code ShowStatusReportAction}
54 */
55 public ShowStatusReportAction() {
56 super(
57 tr("Show Status Report"),
58 "clock",
59 tr("Show status report with useful information that can be attached to bugs"),
60 Shortcut.registerShortcut("help:showstatusreport", tr("Help: {0}",
61 tr("Show Status Report")), KeyEvent.CHAR_UNDEFINED, Shortcut.NONE), false);
62
63 putValue("help", ht("/Action/ShowStatusReport"));
64 putValue("toolbar", "help/showstatusreport");
65 Main.toolbar.register(this);
66 }
67
68 private static boolean isRunningJavaWebStart() {
69 try {
70 // See http://stackoverflow.com/a/16200769/2257172
71 return Class.forName("javax.jnlp.ServiceManager") != null;
72 } catch (ClassNotFoundException e) {
73 return false;
74 }
75 }
76
77 /**
78 * Replies the report header (software and system info)
79 * @return The report header (software and system info)
80 */
81 public static String getReportHeader() {
82 StringBuilder text = new StringBuilder(256);
83 String runtimeVersion = System.getProperty("java.runtime.version");
84 text.append(Version.getInstance().getReleaseAttributes())
85 .append("\nIdentification: ").append(Version.getInstance().getAgentString())
86 .append("\nMemory Usage: ")
87 .append(Runtime.getRuntime().totalMemory()/1024/1024)
88 .append(" MB / ")
89 .append(Runtime.getRuntime().maxMemory()/1024/1024)
90 .append(" MB (")
91 .append(Runtime.getRuntime().freeMemory()/1024/1024)
92 .append(" MB allocated, but free)\nJava version: ")
93 .append(runtimeVersion != null ? runtimeVersion : System.getProperty("java.version")).append(", ")
94 .append(System.getProperty("java.vendor")).append(", ")
95 .append(System.getProperty("java.vm.name")).append('\n');
96
97 text.append("Screen: ");
98 if (!GraphicsEnvironment.isHeadless()) {
99 text.append(Arrays.stream(GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()).map(gd -> {
100 StringBuilder b = new StringBuilder(gd.getIDstring());
101 DisplayMode dm = gd.getDisplayMode();
102 if (dm != null) {
103 b.append(' ').append(dm.getWidth()).append('x').append(dm.getHeight());
104 }
105 return b.toString();
106 }).collect(Collectors.joining(", ")));
107 }
108 Dimension maxScreenSize = GuiHelper.getMaximumScreenSize();
109 text.append("\nMaximum Screen Size: ")
110 .append((int) maxScreenSize.getWidth()).append('x')
111 .append((int) maxScreenSize.getHeight()).append('\n');
112
113 if (Main.platform.getClass() == PlatformHookUnixoid.class) {
114 // Add Java package details
115 String packageDetails = ((PlatformHookUnixoid) Main.platform).getJavaPackageDetails();
116 if (packageDetails != null) {
117 text.append("Java package: ")
118 .append(packageDetails)
119 .append('\n');
120 }
121 // Add WebStart package details if run from JNLP
122 if (isRunningJavaWebStart()) {
123 String webStartDetails = ((PlatformHookUnixoid) Main.platform).getWebStartPackageDetails();
124 if (webStartDetails != null) {
125 text.append("WebStart package: ")
126 .append(webStartDetails)
127 .append('\n');
128 }
129 }
130 // Add Gnome Atk wrapper details if found
131 String atkWrapperDetails = ((PlatformHookUnixoid) Main.platform).getAtkWrapperPackageDetails();
132 if (atkWrapperDetails != null) {
133 text.append("Java ATK Wrapper package: ")
134 .append(atkWrapperDetails)
135 .append('\n');
136 }
137 }
138 try {
139 // Build a new list of VM parameters to modify it below if needed (default implementation returns an UnmodifiableList instance)
140 List<String> vmArguments = new ArrayList<>(ManagementFactory.getRuntimeMXBean().getInputArguments());
141 for (ListIterator<String> it = vmArguments.listIterator(); it.hasNext();) {
142 String value = it.next();
143 if (value.contains("=")) {
144 String[] param = value.split("=");
145 // Hide some parameters for privacy concerns
146 if (param[0].toLowerCase(Locale.ENGLISH).startsWith("-dproxy")) {
147 it.set(param[0]+"=xxx");
148 } else {
149 // Replace some paths for readability and privacy concerns
150 String val = paramCleanup(param[1]);
151 if (!val.equals(param[1])) {
152 it.set(param[0] + '=' + val);
153 }
154 }
155 } else if (value.startsWith("-X")) {
156 // Remove arguments like -Xbootclasspath/a, -Xverify:remote, that can be very long and unhelpful
157 it.remove();
158 }
159 }
160 if (!vmArguments.isEmpty()) {
161 text.append("VM arguments: ").append(vmArguments.toString().replace("\\\\", "\\")).append('\n');
162 }
163 } catch (SecurityException e) {
164 Main.trace(e);
165 }
166 List<String> commandLineArgs = Main.getCommandLineArgs();
167 if (!commandLineArgs.isEmpty()) {
168 text.append("Program arguments: ").append(Arrays.toString(paramCleanup(commandLineArgs).toArray())).append('\n');
169 }
170 if (Main.main != null) {
171 DataSet dataset = Main.getLayerManager().getEditDataSet();
172 if (dataset != null) {
173 String result = DatasetConsistencyTest.runTests(dataset);
174 if (result.isEmpty()) {
175 text.append("Dataset consistency test: No problems found\n");
176 } else {
177 text.append("\nDataset consistency test:\n").append(result).append('\n');
178 }
179 }
180 }
181 text.append("\n");
182 appendCollection(text, "Plugins", Utils.transform(PluginHandler.getBugReportInformation(), i -> "+ " + i));
183 appendCollection(text, "Tagging presets", getCustomUrls(TaggingPresetPreference.PresetPrefHelper.INSTANCE));
184 appendCollection(text, "Map paint styles", getCustomUrls(MapPaintPreference.MapPaintPrefHelper.INSTANCE));
185 appendCollection(text, "Validator rules", getCustomUrls(ValidatorTagCheckerRulesPreference.RulePrefHelper.INSTANCE));
186 appendCollection(text, "Last errors/warnings", Utils.transform(Main.getLastErrorAndWarnings(), i -> "- " + i));
187
188 String osmApi = OsmApi.getOsmApi().getServerUrl();
189 if (!OsmApi.DEFAULT_API_URL.equals(osmApi.trim())) {
190 text.append("OSM API: ").append(osmApi).append("\n\n");
191 }
192
193 return text.toString();
194 }
195
196 private static Collection<String> getCustomUrls(SourceEditor.SourcePrefHelper helper) {
197 final Set<String> defaultUrls = helper.getDefault().stream()
198 .map(i -> i.url)
199 .collect(Collectors.toSet());
200 return helper.get().stream()
201 .filter(i -> !defaultUrls.contains(i.url))
202 .map(i -> (i.active ? "+ " : "- ") + i.url)
203 .collect(Collectors.toList());
204 }
205
206 private static List<String> paramCleanup(Collection<String> params) {
207 List<String> result = new ArrayList<>(params.size());
208 for (String param : params) {
209 result.add(paramCleanup(param));
210 }
211 return result;
212 }
213
214 /**
215 * Shortens and removes private informations from a parameter used for status report.
216 * @param param parameter to cleanup
217 * @return shortened/anonymized parameter
218 */
219 private static String paramCleanup(String param) {
220 final String envJavaHome = System.getenv("JAVA_HOME");
221 final String envJavaHomeAlt = Main.isPlatformWindows() ? "%JAVA_HOME%" : "${JAVA_HOME}";
222 final String propJavaHome = System.getProperty("java.home");
223 final String propJavaHomeAlt = "<java.home>";
224 final String prefDir = Main.pref.getPreferencesDirectory().toString();
225 final String prefDirAlt = "<josm.pref>";
226 final String userDataDir = Main.pref.getUserDataDirectory().toString();
227 final String userDataDirAlt = "<josm.userdata>";
228 final String userCacheDir = Main.pref.getCacheDirectory().toString();
229 final String userCacheDirAlt = "<josm.cache>";
230 final String userHomeDir = System.getProperty("user.home");
231 final String userHomeDirAlt = Main.isPlatformWindows() ? "%UserProfile%" : "${HOME}";
232 final String userName = System.getProperty("user.name");
233 final String userNameAlt = "<user.name>";
234
235 String val = param;
236 val = paramReplace(val, envJavaHome, envJavaHomeAlt);
237 val = paramReplace(val, envJavaHome, envJavaHomeAlt);
238 val = paramReplace(val, propJavaHome, propJavaHomeAlt);
239 val = paramReplace(val, prefDir, prefDirAlt);
240 val = paramReplace(val, userDataDir, userDataDirAlt);
241 val = paramReplace(val, userCacheDir, userCacheDirAlt);
242 val = paramReplace(val, userHomeDir, userHomeDirAlt);
243 if (userName.length() >= 3) {
244 val = paramReplace(val, userName, userNameAlt);
245 }
246 return val;
247 }
248
249 private static String paramReplace(String str, String target, String replacement) {
250 return target == null ? str : str.replace(target, replacement);
251 }
252
253 private static void appendCollection(StringBuilder text, String label, Collection<String> col) {
254 if (!col.isEmpty()) {
255 text.append(label).append(":\n");
256 for (String o : col) {
257 text.append(paramCleanup(o)).append('\n');
258 }
259 text.append('\n');
260 }
261 }
262
263 @Override
264 public void actionPerformed(ActionEvent e) {
265 StringBuilder text = new StringBuilder();
266 String reportHeader = getReportHeader();
267 text.append(reportHeader);
268 try {
269 Map<String, Setting<?>> settings = Main.pref.getAllSettings();
270 Set<String> keys = new HashSet<>(settings.keySet());
271 for (String key : keys) {
272 // Remove sensitive information from status report
273 if (key.startsWith("marker.show") || key.contains("username") || key.contains("password") || key.contains("access-token")) {
274 settings.remove(key);
275 }
276 }
277 for (Entry<String, Setting<?>> entry : settings.entrySet()) {
278 text.append(paramCleanup(entry.getKey()))
279 .append('=')
280 .append(paramCleanup(entry.getValue().getValue().toString())).append('\n');
281 }
282 } catch (Exception x) {
283 Main.error(x);
284 }
285
286 DebugTextDisplay ta = new DebugTextDisplay(text.toString());
287
288 ExtendedDialog ed = new ExtendedDialog(Main.parent,
289 tr("Status Report"),
290 new String[] {tr("Copy to clipboard and close"), tr("Report bug"), tr("Close") });
291 ed.setButtonIcons(new String[] {"copy", "bug", "cancel" });
292 ed.setContent(ta, false);
293 ed.setMinimumSize(new Dimension(380, 200));
294 ed.setPreferredSize(new Dimension(700, Main.parent.getHeight()-50));
295
296 switch (ed.showDialog().getValue()) {
297 case 1: ta.copyToClippboard(); break;
298 case 2: BugReportSender.reportBug(reportHeader); break;
299 default: // Do nothing
300 }
301 }
302}
Note: See TracBrowser for help on using the repository browser.