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

Last change on this file since 14932 was 14706, checked in by GerdP, 5 years ago

fix more recent sonar issues

  • Property svn:eol-style set to native
File size: 13.9 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 putValue("toolbar", "help/showstatusreport");
70 MainApplication.getToolbar().register(this);
71 }
72
73 private static boolean isRunningJavaWebStart() {
74 try {
75 // See http://stackoverflow.com/a/16200769/2257172
76 return Class.forName("javax.jnlp.ServiceManager") != null;
77 } catch (ClassNotFoundException e) {
78 return false;
79 }
80 }
81
82 /**
83 * Replies the report header (software and system info)
84 * @return The report header (software and system info)
85 */
86 public static String getReportHeader() {
87 StringBuilder text = new StringBuilder(256);
88 String runtimeVersion = getSystemProperty("java.runtime.version");
89 text.append(Version.getInstance().getReleaseAttributes())
90 .append("\nIdentification: ").append(Version.getInstance().getAgentString());
91 String buildNumber = PlatformManager.getPlatform().getOSBuildNumber();
92 if (!buildNumber.isEmpty()) {
93 text.append("\nOS Build number: ").append(buildNumber);
94 }
95 text.append("\nMemory Usage: ")
96 .append(Runtime.getRuntime().totalMemory()/1024/1024)
97 .append(" MB / ")
98 .append(Runtime.getRuntime().maxMemory()/1024/1024)
99 .append(" MB (")
100 .append(Runtime.getRuntime().freeMemory()/1024/1024)
101 .append(" MB allocated, but free)\nJava version: ")
102 .append(runtimeVersion != null ? runtimeVersion : getSystemProperty("java.version")).append(", ")
103 .append(getSystemProperty("java.vendor")).append(", ")
104 .append(getSystemProperty("java.vm.name"))
105 .append("\nScreen: ");
106 if (!GraphicsEnvironment.isHeadless()) {
107 text.append(Arrays.stream(GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()).map(gd -> {
108 StringBuilder b = new StringBuilder(gd.getIDstring());
109 DisplayMode dm = gd.getDisplayMode();
110 if (dm != null) {
111 b.append(' ').append(dm.getWidth()).append('x').append(dm.getHeight());
112 }
113 return b.toString();
114 }).collect(Collectors.joining(", ")));
115 }
116 Dimension maxScreenSize = GuiHelper.getMaximumScreenSize();
117 text.append("\nMaximum Screen Size: ")
118 .append((int) maxScreenSize.getWidth()).append('x')
119 .append((int) maxScreenSize.getHeight()).append('\n');
120
121 if (PlatformManager.isPlatformUnixoid()) {
122 PlatformHookUnixoid platform = (PlatformHookUnixoid) PlatformManager.getPlatform();
123 // Add Java package details
124 String packageDetails = platform.getJavaPackageDetails();
125 if (packageDetails != null) {
126 text.append("Java package: ")
127 .append(packageDetails)
128 .append('\n');
129 }
130 // Add WebStart package details if run from JNLP
131 if (isRunningJavaWebStart()) {
132 String webStartDetails = platform.getWebStartPackageDetails();
133 if (webStartDetails != null) {
134 text.append("WebStart package: ")
135 .append(webStartDetails)
136 .append('\n');
137 }
138 }
139 // Add Gnome Atk wrapper details if found
140 String atkWrapperDetails = platform.getAtkWrapperPackageDetails();
141 if (atkWrapperDetails != null) {
142 text.append("Java ATK Wrapper package: ")
143 .append(atkWrapperDetails)
144 .append('\n');
145 }
146 }
147 try {
148 // Build a new list of VM parameters to modify it below if needed (default implementation returns an UnmodifiableList instance)
149 List<String> vmArguments = new ArrayList<>(ManagementFactory.getRuntimeMXBean().getInputArguments());
150 for (ListIterator<String> it = vmArguments.listIterator(); it.hasNext();) {
151 String value = it.next();
152 if (value.contains("=")) {
153 String[] param = value.split("=");
154 // Hide some parameters for privacy concerns
155 if (param[0].toLowerCase(Locale.ENGLISH).startsWith("-dproxy")) {
156 it.set(param[0]+"=xxx");
157 } else if ("-Djnlpx.vmargs".equals(param[0])) {
158 // Remove jnlpx.vmargs (base64 encoded copy of VM arguments already included in clear)
159 it.remove();
160 } else {
161 // Replace some paths for readability and privacy concerns
162 String val = paramCleanup(param[1]);
163 if (!val.equals(param[1])) {
164 it.set(param[0] + '=' + val);
165 }
166 }
167 } else if (value.startsWith("-X")) {
168 // Remove arguments like -Xbootclasspath/a, -Xverify:remote, that can be very long and unhelpful
169 it.remove();
170 }
171 }
172 if (!vmArguments.isEmpty()) {
173 text.append("VM arguments: ").append(vmArguments.toString().replace("\\\\", "\\")).append('\n');
174 }
175 } catch (SecurityException e) {
176 Logging.trace(e);
177 }
178 List<String> commandLineArgs = MainApplication.getCommandLineArgs();
179 if (!commandLineArgs.isEmpty()) {
180 text.append("Program arguments: ").append(Arrays.toString(paramCleanup(commandLineArgs).toArray())).append('\n');
181 }
182 DataSet dataset = MainApplication.getLayerManager().getActiveDataSet();
183 if (dataset != null) {
184 String result = DatasetConsistencyTest.runTests(dataset);
185 if (result.isEmpty()) {
186 text.append("Dataset consistency test: No problems found\n");
187 } else {
188 text.append("\nDataset consistency test:\n").append(result).append('\n');
189 }
190 }
191 text.append('\n');
192 appendCollection(text, "Plugins", Utils.transform(PluginHandler.getBugReportInformation(), i -> "+ " + i));
193 appendCollection(text, "Tagging presets", getCustomUrls(PresetPrefHelper.INSTANCE));
194 appendCollection(text, "Map paint styles", getCustomUrls(MapPaintPrefHelper.INSTANCE));
195 appendCollection(text, "Validator rules", getCustomUrls(ValidatorPrefHelper.INSTANCE));
196 appendCollection(text, "Last errors/warnings", Utils.transform(Logging.getLastErrorAndWarnings(), i -> "- " + i));
197
198 String osmApi = OsmApi.getOsmApi().getServerUrl();
199 if (!Config.getUrls().getDefaultOsmApiUrl().equals(osmApi.trim())) {
200 text.append("OSM API: ").append(osmApi).append("\n\n");
201 }
202
203 return text.toString();
204 }
205
206 private static Collection<String> getCustomUrls(SourcePrefHelper helper) {
207 final Set<String> defaultUrls = helper.getDefault().stream()
208 .map(i -> i.url)
209 .collect(Collectors.toSet());
210 return helper.get().stream()
211 .filter(i -> !defaultUrls.contains(i.url))
212 .map(i -> (i.active ? "+ " : "- ") + i.url)
213 .collect(Collectors.toList());
214 }
215
216 private static List<String> paramCleanup(Collection<String> params) {
217 List<String> result = new ArrayList<>(params.size());
218 for (String param : params) {
219 result.add(paramCleanup(param));
220 }
221 return result;
222 }
223
224 /**
225 * Fill map with anonymized name to the actual used path.
226 * @return map that maps shortened name to full directory path
227 */
228 static Map<String, String> getAnonimicDirectorySymbolMap() {
229 /** maps the anonymized name to the actual used path */
230 Map<String, String> map = new LinkedHashMap<>();
231 map.put(PlatformManager.isPlatformWindows() ? "%JAVA_HOME%" : "${JAVA_HOME}", getSystemEnv("JAVA_HOME"));
232 map.put("<java.home>", getSystemProperty("java.home"));
233 map.put("<josm.pref>", Config.getDirs().getPreferencesDirectory(false).toString());
234 map.put("<josm.userdata>", Config.getDirs().getUserDataDirectory(false).toString());
235 map.put("<josm.cache>", Config.getDirs().getCacheDirectory(false).toString());
236 map.put(PlatformManager.isPlatformWindows() ? "%UserProfile%" : "${HOME}", getSystemProperty("user.home"));
237 return map;
238 }
239
240 /**
241 * Shortens and removes private informations from a parameter used for status report.
242 * @param param parameter to cleanup
243 * @return shortened/anonymized parameter
244 */
245 static String paramCleanup(String param) {
246 final String userName = getSystemProperty("user.name");
247 final String userNameAlt = "<user.name>";
248
249 String val = param;
250 for (Entry<String, String> entry : getAnonimicDirectorySymbolMap().entrySet()) {
251 val = paramReplace(val, entry.getValue(), entry.getKey());
252 }
253 if (userName != null && userName.length() >= 3) {
254 val = paramReplace(val, userName, userNameAlt);
255 }
256 return val;
257 }
258
259 private static String paramReplace(String str, String target, String replacement) {
260 return target == null ? str : str.replace(target, replacement);
261 }
262
263 private static void appendCollection(StringBuilder text, String label, Collection<String> col) {
264 if (!col.isEmpty()) {
265 text.append(label).append(":\n");
266 for (String o : col) {
267 text.append(paramCleanup(o)).append('\n');
268 }
269 text.append('\n');
270 }
271 }
272
273 @Override
274 public void actionPerformed(ActionEvent e) {
275 StringBuilder text = new StringBuilder();
276 String reportHeader = getReportHeader();
277 text.append(reportHeader);
278
279 Preferences.main().getAllSettings().forEach((key, setting) -> {
280 if (key.startsWith("marker.show")
281 || "file-open.history".equals(key)
282 || "download.overpass.query".equals(key)
283 || "download.overpass.queries".equals(key)
284 || key.contains("username")
285 || key.contains("password")
286 || key.contains("access-token")) {
287 // Remove sensitive information from status report
288 return;
289 }
290 text.append(paramCleanup(key))
291 .append('=')
292 .append(paramCleanup(setting.getValue().toString()))
293 .append('\n');
294 });
295
296 DebugTextDisplay ta = new DebugTextDisplay(text.toString());
297
298 ExtendedDialog ed = new ExtendedDialog(MainApplication.getMainFrame(),
299 tr("Status Report"),
300 tr("Copy to clipboard and close"), tr("Report bug"), tr("Close"));
301 ed.setButtonIcons("copy", "bug", "cancel");
302 ed.setContent(ta, false);
303 ed.setMinimumSize(new Dimension(380, 200));
304 ed.setPreferredSize(new Dimension(700, MainApplication.getMainFrame().getHeight()-50));
305
306 switch (ed.showDialog().getValue()) {
307 case 1: ta.copyToClipboard(); break;
308 case 2: BugReportSender.reportBug(reportHeader); break;
309 default: // do nothing
310 }
311 GuiHelper.destroyComponents(ed, false);
312 }
313}
Note: See TracBrowser for help on using the repository browser.