001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.actions;
003
004import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
005import static org.openstreetmap.josm.tools.I18n.tr;
006
007import java.awt.Dimension;
008import java.awt.event.ActionEvent;
009import java.awt.event.KeyEvent;
010import java.lang.management.ManagementFactory;
011import java.util.ArrayList;
012import java.util.Arrays;
013import java.util.Collection;
014import java.util.HashSet;
015import java.util.List;
016import java.util.ListIterator;
017import java.util.Locale;
018import java.util.Map;
019import java.util.Map.Entry;
020import java.util.Set;
021import java.util.TreeSet;
022
023import org.openstreetmap.josm.Main;
024import org.openstreetmap.josm.data.Version;
025import org.openstreetmap.josm.data.osm.DataSet;
026import org.openstreetmap.josm.data.osm.DatasetConsistencyTest;
027import org.openstreetmap.josm.data.preferences.Setting;
028import org.openstreetmap.josm.gui.ExtendedDialog;
029import org.openstreetmap.josm.gui.preferences.SourceEditor;
030import org.openstreetmap.josm.gui.preferences.SourceEditor.ExtendedSourceEntry;
031import org.openstreetmap.josm.gui.preferences.SourceEntry;
032import org.openstreetmap.josm.gui.preferences.map.MapPaintPreference;
033import org.openstreetmap.josm.gui.preferences.map.TaggingPresetPreference;
034import org.openstreetmap.josm.gui.preferences.validator.ValidatorTagCheckerRulesPreference;
035import org.openstreetmap.josm.io.OsmApi;
036import org.openstreetmap.josm.plugins.PluginHandler;
037import org.openstreetmap.josm.tools.PlatformHookUnixoid;
038import org.openstreetmap.josm.tools.Shortcut;
039import org.openstreetmap.josm.tools.bugreport.BugReportSender;
040import org.openstreetmap.josm.tools.bugreport.DebugTextDisplay;
041
042/**
043 * @author xeen
044 *
045 * Opens a dialog with useful status information like version numbers for Java, JOSM and plugins
046 * Also includes preferences with stripped username and password
047 */
048public final class ShowStatusReportAction extends JosmAction {
049
050    /**
051     * Constructs a new {@code ShowStatusReportAction}
052     */
053    public ShowStatusReportAction() {
054        super(
055                tr("Show Status Report"),
056                "clock",
057                tr("Show status report with useful information that can be attached to bugs"),
058                Shortcut.registerShortcut("help:showstatusreport", tr("Help: {0}",
059                        tr("Show Status Report")), KeyEvent.CHAR_UNDEFINED, Shortcut.NONE), false);
060
061        putValue("help", ht("/Action/ShowStatusReport"));
062        putValue("toolbar", "help/showstatusreport");
063        Main.toolbar.register(this);
064    }
065
066    private static boolean isRunningJavaWebStart() {
067        try {
068            // See http://stackoverflow.com/a/16200769/2257172
069            return Class.forName("javax.jnlp.ServiceManager") != null;
070        } catch (ClassNotFoundException e) {
071            return false;
072        }
073    }
074
075    /**
076     * Replies the report header (software and system info)
077     * @return The report header (software and system info)
078     */
079    public static String getReportHeader() {
080        StringBuilder text = new StringBuilder(256);
081        String runtimeVersion = System.getProperty("java.runtime.version");
082        text.append(Version.getInstance().getReleaseAttributes())
083            .append("\nIdentification: ").append(Version.getInstance().getAgentString())
084            .append("\nMemory Usage: ")
085            .append(Runtime.getRuntime().totalMemory()/1024/1024)
086            .append(" MB / ")
087            .append(Runtime.getRuntime().maxMemory()/1024/1024)
088            .append(" MB (")
089            .append(Runtime.getRuntime().freeMemory()/1024/1024)
090            .append(" MB allocated, but free)\nJava version: ")
091            .append(runtimeVersion != null ? runtimeVersion : System.getProperty("java.version")).append(", ")
092            .append(System.getProperty("java.vendor")).append(", ")
093            .append(System.getProperty("java.vm.name")).append('\n');
094        if (Main.platform.getClass() == PlatformHookUnixoid.class) {
095            // Add Java package details
096            String packageDetails = ((PlatformHookUnixoid) Main.platform).getJavaPackageDetails();
097            if (packageDetails != null) {
098                text.append("Java package: ")
099                    .append(packageDetails)
100                    .append('\n');
101            }
102            // Add WebStart package details if run from JNLP
103            if (isRunningJavaWebStart()) {
104                String webStartDetails = ((PlatformHookUnixoid) Main.platform).getWebStartPackageDetails();
105                if (webStartDetails != null) {
106                    text.append("WebStart package: ")
107                        .append(webStartDetails)
108                        .append('\n');
109                }
110            }
111        }
112        try {
113            // Build a new list of VM parameters to modify it below if needed (default implementation returns an UnmodifiableList instance)
114            List<String> vmArguments = new ArrayList<>(ManagementFactory.getRuntimeMXBean().getInputArguments());
115            for (ListIterator<String> it = vmArguments.listIterator(); it.hasNext();) {
116                String value = it.next();
117                if (value.contains("=")) {
118                    String[] param = value.split("=");
119                    // Hide some parameters for privacy concerns
120                    if (param[0].toLowerCase(Locale.ENGLISH).startsWith("-dproxy")) {
121                        it.set(param[0]+"=xxx");
122                    } else {
123                        // Replace some paths for readability and privacy concerns
124                        String val = paramCleanup(param[1]);
125                        if (!val.equals(param[1])) {
126                            it.set(param[0] + '=' + val);
127                        }
128                    }
129                } else if (value.startsWith("-X")) {
130                    // Remove arguments like -Xbootclasspath/a, -Xverify:remote, that can be very long and unhelpful
131                    it.remove();
132                }
133            }
134            if (!vmArguments.isEmpty()) {
135                text.append("VM arguments: ").append(vmArguments.toString().replace("\\\\", "\\")).append('\n');
136            }
137        } catch (SecurityException e) {
138            if (Main.isTraceEnabled()) {
139                Main.trace(e.getMessage());
140            }
141        }
142        List<String> commandLineArgs = Main.getCommandLineArgs();
143        if (!commandLineArgs.isEmpty()) {
144            text.append("Program arguments: ").append(Arrays.toString(paramCleanup(commandLineArgs).toArray())).append('\n');
145        }
146        if (Main.main != null) {
147            DataSet dataset = Main.main.getCurrentDataSet();
148            if (dataset != null) {
149                String result = DatasetConsistencyTest.runTests(dataset);
150                if (result.isEmpty()) {
151                    text.append("Dataset consistency test: No problems found\n");
152                } else {
153                    text.append("\nDataset consistency test:\n").append(result).append('\n');
154                }
155            }
156        }
157        text.append('\n').append(PluginHandler.getBugReportText()).append('\n');
158
159        appendCollection(text, "Tagging presets", getCustomUrls(TaggingPresetPreference.PresetPrefHelper.INSTANCE));
160        appendCollection(text, "Map paint styles", getCustomUrls(MapPaintPreference.MapPaintPrefHelper.INSTANCE));
161        appendCollection(text, "Validator rules", getCustomUrls(ValidatorTagCheckerRulesPreference.RulePrefHelper.INSTANCE));
162        appendCollection(text, "Last errors/warnings", Main.getLastErrorAndWarnings());
163
164        String osmApi = OsmApi.getOsmApi().getServerUrl();
165        if (!OsmApi.DEFAULT_API_URL.equals(osmApi.trim())) {
166            text.append("OSM API: ").append(osmApi).append("\n\n");
167        }
168
169        return text.toString();
170    }
171
172    private static Collection<String> getCustomUrls(SourceEditor.SourcePrefHelper helper) {
173        Set<String> set = new TreeSet<>();
174        for (SourceEntry entry : helper.get()) {
175            set.add(entry.url);
176        }
177        for (ExtendedSourceEntry def : helper.getDefault()) {
178            set.remove(def.url);
179        }
180        return set;
181    }
182
183    private static List<String> paramCleanup(Collection<String> params) {
184        List<String> result = new ArrayList<>(params.size());
185        for (String param : params) {
186            result.add(paramCleanup(param));
187        }
188        return result;
189    }
190
191    /**
192     * Shortens and removes private informations from a parameter used for status report.
193     * @param param parameter to cleanup
194     * @return shortened/anonymized parameter
195     */
196    private static String paramCleanup(String param) {
197        final String envJavaHome = System.getenv("JAVA_HOME");
198        final String envJavaHomeAlt = Main.isPlatformWindows() ? "%JAVA_HOME%" : "${JAVA_HOME}";
199        final String propJavaHome = System.getProperty("java.home");
200        final String propJavaHomeAlt = "<java.home>";
201        final String prefDir = Main.pref.getPreferencesDirectory().toString();
202        final String prefDirAlt = "<josm.pref>";
203        final String userDataDir = Main.pref.getUserDataDirectory().toString();
204        final String userDataDirAlt = "<josm.userdata>";
205        final String userCacheDir = Main.pref.getCacheDirectory().toString();
206        final String userCacheDirAlt = "<josm.cache>";
207        final String userHomeDir = System.getProperty("user.home");
208        final String userHomeDirAlt = Main.isPlatformWindows() ? "%UserProfile%" : "${HOME}";
209        final String userName = System.getProperty("user.name");
210        final String userNameAlt = "<user.name>";
211
212        String val = param;
213        val = paramReplace(val, envJavaHome, envJavaHomeAlt);
214        val = paramReplace(val, envJavaHome, envJavaHomeAlt);
215        val = paramReplace(val, propJavaHome, propJavaHomeAlt);
216        val = paramReplace(val, prefDir, prefDirAlt);
217        val = paramReplace(val, userDataDir, userDataDirAlt);
218        val = paramReplace(val, userCacheDir, userCacheDirAlt);
219        val = paramReplace(val, userHomeDir, userHomeDirAlt);
220        val = paramReplace(val, userName, userNameAlt);
221        return val;
222    }
223
224    private static String paramReplace(String str, String target, String replacement) {
225        return target == null ? str : str.replace(target, replacement);
226    }
227
228    private static <T> void appendCollection(StringBuilder text, String label, Collection<T> col) {
229        if (!col.isEmpty()) {
230            text.append(label+":\n");
231            for (T o : col) {
232                text.append("- ").append(paramCleanup(o.toString())).append('\n');
233            }
234            text.append('\n');
235        }
236    }
237
238    @Override
239    public void actionPerformed(ActionEvent e) {
240        StringBuilder text = new StringBuilder();
241        String reportHeader = getReportHeader();
242        text.append(reportHeader);
243        try {
244            Map<String, Setting<?>> settings = Main.pref.getAllSettings();
245            Set<String> keys = new HashSet<>(settings.keySet());
246            for (String key : keys) {
247                // Remove sensitive information from status report
248                if (key.startsWith("marker.show") || key.contains("username") || key.contains("password") || key.contains("access-token")) {
249                    settings.remove(key);
250                }
251            }
252            for (Entry<String, Setting<?>> entry : settings.entrySet()) {
253                text.append(paramCleanup(entry.getKey()))
254                    .append('=')
255                    .append(paramCleanup(entry.getValue().getValue().toString())).append('\n');
256            }
257        } catch (Exception x) {
258            Main.error(x);
259        }
260
261        DebugTextDisplay ta = new DebugTextDisplay(text.toString());
262
263        ExtendedDialog ed = new ExtendedDialog(Main.parent,
264                tr("Status Report"),
265                new String[] {tr("Copy to clipboard and close"), tr("Report bug"), tr("Close") });
266        ed.setButtonIcons(new String[] {"copy", "bug", "cancel" });
267        ed.setContent(ta, false);
268        ed.setMinimumSize(new Dimension(380, 200));
269        ed.setPreferredSize(new Dimension(700, Main.parent.getHeight()-50));
270
271        switch (ed.showDialog().getValue()) {
272            case 1: ta.copyToClippboard(); break;
273            case 2: BugReportSender.reportBug(reportHeader); break;
274            default: // Do nothing
275        }
276    }
277}