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

Last change on this file since 17637 was 17637, checked in by simon04, 3 years ago

fix #20647 - Add --status-report command line argument

  • Property svn:eol-style set to native
File size: 16.2 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;
6import static org.openstreetmap.josm.tools.Utils.getSystemEnv;
7import static org.openstreetmap.josm.tools.Utils.getSystemProperty;
8
9import java.awt.Dimension;
10import java.awt.DisplayMode;
11import java.awt.GraphicsDevice;
12import java.awt.GraphicsEnvironment;
13import java.awt.Toolkit;
14import java.awt.event.ActionEvent;
15import java.awt.event.KeyEvent;
16import java.awt.geom.AffineTransform;
17import java.io.PrintWriter;
18import java.io.StringWriter;
19import java.lang.management.ManagementFactory;
20import java.util.ArrayList;
21import java.util.Arrays;
22import java.util.Collection;
23import java.util.LinkedHashMap;
24import java.util.List;
25import java.util.ListIterator;
26import java.util.Locale;
27import java.util.Map;
28import java.util.Map.Entry;
29import java.util.Optional;
30import java.util.Set;
31import java.util.stream.Collectors;
32
33import javax.swing.UIManager;
34
35import org.openstreetmap.josm.data.Preferences;
36import org.openstreetmap.josm.data.Version;
37import org.openstreetmap.josm.data.osm.DataSet;
38import org.openstreetmap.josm.data.osm.DatasetConsistencyTest;
39import org.openstreetmap.josm.data.preferences.sources.MapPaintPrefHelper;
40import org.openstreetmap.josm.data.preferences.sources.PresetPrefHelper;
41import org.openstreetmap.josm.data.preferences.sources.SourcePrefHelper;
42import org.openstreetmap.josm.data.preferences.sources.ValidatorPrefHelper;
43import org.openstreetmap.josm.gui.ExtendedDialog;
44import org.openstreetmap.josm.gui.MainApplication;
45import org.openstreetmap.josm.gui.bugreport.DebugTextDisplay;
46import org.openstreetmap.josm.gui.util.GuiHelper;
47import org.openstreetmap.josm.io.OsmApi;
48import org.openstreetmap.josm.plugins.PluginHandler;
49import org.openstreetmap.josm.spi.preferences.Config;
50import org.openstreetmap.josm.tools.Logging;
51import org.openstreetmap.josm.tools.PlatformHookUnixoid;
52import org.openstreetmap.josm.tools.PlatformManager;
53import org.openstreetmap.josm.tools.Shortcut;
54import org.openstreetmap.josm.tools.Utils;
55import org.openstreetmap.josm.tools.bugreport.BugReportSender;
56
57/**
58 * Opens a dialog with useful status information like version numbers for Java, JOSM and plugins
59 * Also includes preferences with stripped username and password.
60 *
61 * @author xeen
62 */
63public final class ShowStatusReportAction extends JosmAction {
64
65 /**
66 * Localized description text for this action
67 */
68 public static final String ACTION_DESCRIPTION = tr("Show status report with useful information that can be attached to bugs");
69
70 /**
71 * Constructs a new {@code ShowStatusReportAction}
72 */
73 public ShowStatusReportAction() {
74 super(
75 tr("Show Status Report"),
76 "misc/statusreport",
77 ACTION_DESCRIPTION,
78 Shortcut.registerShortcut("help:showstatusreport", tr("Help: {0}",
79 tr("Show Status Report")), KeyEvent.CHAR_UNDEFINED, Shortcut.NONE), true, "help/showstatusreport", false);
80
81 setHelpId(ht("/Action/ShowStatusReport"));
82 }
83
84 /**
85 * Replies the report header (software and system info)
86 * @return The report header (software and system info)
87 */
88 public static String getReportHeader() {
89 StringWriter stringWriter = new StringWriter(256);
90 PrintWriter text = new PrintWriter(stringWriter);
91 String runtimeVersion = getSystemProperty("java.runtime.version");
92 text.println(Version.getInstance().getReleaseAttributes());
93 text.format("Identification: %s%n", Version.getInstance().getAgentString());
94 String buildNumber = PlatformManager.getPlatform().getOSBuildNumber();
95 if (!buildNumber.isEmpty()) {
96 text.format("OS Build number: %s%n", buildNumber);
97 }
98 text.format("Memory Usage: %d MB / %d MB (%d MB allocated, but free)%n",
99 Runtime.getRuntime().totalMemory() / 1024 / 1024,
100 Runtime.getRuntime().maxMemory() / 1024 / 1024,
101 Runtime.getRuntime().freeMemory() / 1024 / 1024);
102 text.format("Java version: %s, %s, %s%n",
103 runtimeVersion != null ? runtimeVersion : getSystemProperty("java.version"),
104 getSystemProperty("java.vendor"),
105 getSystemProperty("java.vm.name"));
106 text.format("Look and Feel: %s%n",
107 Optional.ofNullable(UIManager.getLookAndFeel()).map(laf -> laf.getClass().getName()).orElse("null"));
108 if (!GraphicsEnvironment.isHeadless()) {
109 text.append("Screen:");
110 for (GraphicsDevice gd : GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()) {
111 text.append(" ").append(gd.getIDstring());
112 DisplayMode dm = gd.getDisplayMode();
113 if (dm != null) {
114 AffineTransform transform = gd.getDefaultConfiguration().getDefaultTransform();
115 // Java 11: use DisplayMode#toString
116 text.format(" %d\u00D7%d (scaling %.2f\u00D7%.2f)",
117 dm.getWidth(), dm.getHeight(), transform.getScaleX(), transform.getScaleY());
118 }
119 }
120 text.println();
121 }
122 text.format("Maximum Screen Size: %s%n", toString(GuiHelper.getMaximumScreenSize()));
123 if (!GraphicsEnvironment.isHeadless()) {
124 Dimension bestCursorSize16 = Toolkit.getDefaultToolkit().getBestCursorSize(16, 16);
125 Dimension bestCursorSize32 = Toolkit.getDefaultToolkit().getBestCursorSize(32, 32);
126 text.format("Best cursor sizes: %s→%s, %s→%s%n",
127 toString(new Dimension(16, 16)), toString(bestCursorSize16),
128 toString(new Dimension(32, 32)), toString(bestCursorSize32));
129 }
130
131 if (PlatformManager.isPlatformUnixoid()) {
132 PlatformHookUnixoid platform = (PlatformHookUnixoid) PlatformManager.getPlatform();
133 // Add desktop environment
134 platform.getDesktopEnvironment().ifPresent(desktop -> text.format("Desktop environment: %s%n", desktop));
135 // Add Java package details
136 String packageDetails = platform.getJavaPackageDetails();
137 if (packageDetails != null) {
138 text.format("Java package: %s%n", packageDetails);
139 }
140 // Add WebStart package details if run from JNLP
141 if (Utils.isRunningJavaWebStart()) {
142 String webStartDetails = platform.getWebStartPackageDetails();
143 if (webStartDetails != null) {
144 text.format("WebStart package: %s%n", webStartDetails);
145 }
146 }
147 // Add Gnome Atk wrapper details if found
148 String atkWrapperDetails = platform.getAtkWrapperPackageDetails();
149 if (atkWrapperDetails != null) {
150 text.format("Java ATK Wrapper package: %s%n", atkWrapperDetails);
151 }
152 String lang = System.getenv("LANG");
153 if (lang != null) {
154 text.format("Environment variable LANG: %s%n", lang);
155 }
156 // Add dependencies details if found
157 for (String p : new String[] {
158 "apache-commons-compress", "libcommons-compress-java",
159 "apache-commons-jcs-core",
160 "apache-commons-logging", "libcommons-logging-java",
161 "fonts-noto",
162 "jsonp",
163 "metadata-extractor2",
164 "signpost-core", "liboauth-signpost-java",
165 "svgsalamander"
166 }) {
167 String details = PlatformHookUnixoid.getPackageDetails(p);
168 if (details != null) {
169 text.format("%s: %s%n", p, details);
170 }
171 }
172 }
173 try {
174 // Build a new list of VM parameters to modify it below if needed (default implementation returns an UnmodifiableList instance)
175 List<String> vmArguments = new ArrayList<>(ManagementFactory.getRuntimeMXBean().getInputArguments());
176 for (ListIterator<String> it = vmArguments.listIterator(); it.hasNext();) {
177 String value = it.next();
178 if (value.contains("=")) {
179 String[] param = value.split("=", 2);
180 // Hide some parameters for privacy concerns
181 if (param[0].toLowerCase(Locale.ENGLISH).startsWith("-dproxy")) {
182 it.set(param[0]+"=xxx");
183 } else if ("-Djnlpx.vmargs".equals(param[0])) {
184 // Remove jnlpx.vmargs (base64 encoded copy of VM arguments already included in clear)
185 it.remove();
186 } else {
187 // Replace some paths for readability and privacy concerns
188 String val = paramCleanup(param[1]);
189 if (!val.equals(param[1])) {
190 it.set(param[0] + '=' + val);
191 }
192 }
193 } else if (value.startsWith("-X")) {
194 // Remove arguments like -Xbootclasspath/a, -Xverify:remote, that can be very long and unhelpful
195 it.remove();
196 }
197 }
198 if (!vmArguments.isEmpty()) {
199 text.format("VM arguments: %s%n", vmArguments.toString().replace("\\\\", "\\"));
200 }
201 } catch (SecurityException e) {
202 Logging.trace(e);
203 }
204 List<String> commandLineArgs = MainApplication.getCommandLineArgs();
205 if (!commandLineArgs.isEmpty()) {
206 text.format("Program arguments: %s%n", Arrays.toString(paramCleanup(commandLineArgs).toArray()));
207 }
208 DataSet dataset = MainApplication.getLayerManager().getActiveDataSet();
209 if (dataset != null) {
210 String result = DatasetConsistencyTest.runTests(dataset);
211 if (result.isEmpty()) {
212 text.println("Dataset consistency test: No problems found");
213 } else {
214 text.println();
215 text.println("Dataset consistency test:");
216 text.println(result);
217 }
218 }
219 text.println();
220 appendCollection(text, "Plugins", Utils.transform(PluginHandler.getBugReportInformation(), i -> "+ " + i));
221 appendCollection(text, "Tagging presets", getCustomUrls(PresetPrefHelper.INSTANCE));
222 appendCollection(text, "Map paint styles", getCustomUrls(MapPaintPrefHelper.INSTANCE));
223 appendCollection(text, "Validator rules", getCustomUrls(ValidatorPrefHelper.INSTANCE));
224 appendCollection(text, "Last errors/warnings", Utils.transform(Logging.getLastErrorAndWarnings(), i -> "- " + i));
225
226 String osmApi = OsmApi.getOsmApi().getServerUrl();
227 if (!Config.getUrls().getDefaultOsmApiUrl().equals(osmApi.trim())) {
228 text.format("OSM API: %s%n", osmApi);
229 }
230
231 text.println();
232 return stringWriter.toString();
233 }
234
235 private static String toString(Dimension dimension) {
236 return dimension.width + "\u00D7" + dimension.height;
237 }
238
239 private static Collection<String> getCustomUrls(SourcePrefHelper helper) {
240 final Set<String> defaultUrls = helper.getDefault().stream()
241 .map(i -> i.url)
242 .collect(Collectors.toSet());
243 return helper.get().stream()
244 .filter(i -> !defaultUrls.contains(i.url))
245 .map(i -> (i.active ? "+ " : "- ") + i.url)
246 .collect(Collectors.toList());
247 }
248
249 private static List<String> paramCleanup(Collection<String> params) {
250 return params.stream()
251 .map(ShowStatusReportAction::paramCleanup)
252 .collect(Collectors.toList());
253 }
254
255 /**
256 * Fill map with anonymized name to the actual used path.
257 * @return map that maps shortened name to full directory path
258 */
259 static Map<String, String> getAnonimicDirectorySymbolMap() {
260 /** maps the anonymized name to the actual used path */
261 Map<String, String> map = new LinkedHashMap<>();
262 map.put(PlatformManager.isPlatformWindows() ? "%JAVA_HOME%" : "${JAVA_HOME}", getSystemEnv("JAVA_HOME"));
263 map.put("<java.home>", getSystemProperty("java.home"));
264 map.put("<josm.pref>", Config.getDirs().getPreferencesDirectory(false).toString());
265 map.put("<josm.userdata>", Config.getDirs().getUserDataDirectory(false).toString());
266 map.put("<josm.cache>", Config.getDirs().getCacheDirectory(false).toString());
267 map.put(PlatformManager.isPlatformWindows() ? "%UserProfile%" : "${HOME}", getSystemProperty("user.home"));
268 return map;
269 }
270
271 /**
272 * Shortens and removes private informations from a parameter used for status report.
273 * @param param parameter to cleanup
274 * @return shortened/anonymized parameter
275 */
276 static String paramCleanup(String param) {
277 final String userName = getSystemProperty("user.name");
278 final String userNameAlt = "<user.name>";
279
280 String val = param;
281 for (Entry<String, String> entry : getAnonimicDirectorySymbolMap().entrySet()) {
282 val = paramReplace(val, entry.getValue(), entry.getKey());
283 }
284 if (userName != null && userName.length() >= 3) {
285 val = paramReplace(val, userName, userNameAlt);
286 }
287 return val;
288 }
289
290 private static String paramReplace(String str, String target, String replacement) {
291 return target == null ? str : str.replace(target, replacement);
292 }
293
294 private static void appendCollection(PrintWriter text, String label, Collection<String> col) {
295 if (!col.isEmpty()) {
296 text.append(col.stream().map(o -> paramCleanup(o) + '\n')
297 .collect(Collectors.joining("", label + ":\n", "\n")));
298 }
299 }
300
301 private static String valueCleanup(Object value) {
302 String valueString = value.toString();
303 if (valueString.length() > 512 && value instanceof Collection<?>) {
304 valueString = ((Collection<?>) value).stream().map(v -> {
305 if (v instanceof Map<?, ?>) {
306 LinkedHashMap<Object, Object> map = new LinkedHashMap<>(((Map<?, ?>) v));
307 map.computeIfPresent("icon", (k, icon) -> Utils.shortenString(icon.toString(), 32)); // see #19058
308 return map.toString();
309 } else {
310 return String.valueOf(v);
311 }
312 }).collect(Collectors.joining(",\n ", "[", "\n]"));
313 }
314 return paramCleanup(valueString);
315 }
316
317 @Override
318 public void actionPerformed(ActionEvent e) {
319 StringBuilder text = new StringBuilder();
320 String reportHeader = getReportHeader();
321 text.append(reportHeader);
322
323 Preferences.main().getAllSettings().forEach((key, setting) -> {
324 if ("file-open.history".equals(key)
325 || "download.overpass.query".equals(key)
326 || "download.overpass.queries".equals(key)
327 || key.contains("username")
328 || key.contains("password")
329 || key.contains("access-token")) {
330 // Remove sensitive information from status report
331 return;
332 }
333 text.append(paramCleanup(key))
334 .append('=')
335 .append(valueCleanup(setting.getValue()))
336 .append('\n');
337 });
338
339 DebugTextDisplay ta = new DebugTextDisplay(text.toString());
340
341 ExtendedDialog ed = new ExtendedDialog(MainApplication.getMainFrame(),
342 tr("Status Report"),
343 tr("Copy to clipboard and close"), tr("Report bug"), tr("Close"));
344 ed.setButtonIcons("copy", "bug", "cancel");
345 ed.configureContextsensitiveHelp("/Action/ShowStatusReport", true);
346 ed.setContent(ta, false);
347 ed.setMinimumSize(new Dimension(380, 200));
348 ed.setPreferredSize(new Dimension(700, MainApplication.getMainFrame().getHeight()-50));
349
350 switch (ed.showDialog().getValue()) {
351 case 1: ta.copyToClipboard(); break;
352 case 2: BugReportSender.reportBug(reportHeader); break;
353 default: // do nothing
354 }
355 GuiHelper.destroyComponents(ed, false);
356 }
357}
Note: See TracBrowser for help on using the repository browser.