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

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

see #19251 - Java 8: use Stream

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