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

Last change on this file since 17337 was 17337, checked in by simon04, 4 years ago

ShowStatusReportAction: migrate to PrintWriter

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