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

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

PMD - Strict Exceptions

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