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

Last change on this file since 12828 was 12649, checked in by Don-vip, 7 years ago

see #15182 - code refactoring to avoid dependence on GUI packages from Preferences

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