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

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

sonar - squid:S3878 - Arrays should not be created for varargs parameters

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