Changeset 13647 in josm for trunk/src/org


Ignore:
Timestamp:
2018-04-19T20:37:16+02:00 (6 years ago)
Author:
Don-vip
Message:

see #16204 - Allow to start and close JOSM in WebStart sandbox mode (where every external access is denied). This was very useful to reproduce some very tricky bugs that occured in real life but were almost impossible to diagnose.

Location:
trunk/src/org/openstreetmap/josm
Files:
46 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/org/openstreetmap/josm/Main.java

    r13434 r13647  
    165165            asynchronousRunnableTasks().forEach(service::submit);
    166166            asynchronousCallableTasks().forEach(service::submit);
    167             service.shutdown();
     167            try {
     168                service.shutdown();
     169            } catch (SecurityException e) {
     170                Logging.log(Logging.LEVEL_ERROR, "Unable to shutdown executor service", e);
     171            }
    168172        } catch (InterruptedException | ExecutionException ex) {
    169173            throw new JosmRuntimeException(ex);
  • trunk/src/org/openstreetmap/josm/actions/AboutAction.java

    r12643 r13647  
    3434import org.openstreetmap.josm.tools.Logging;
    3535import org.openstreetmap.josm.tools.Shortcut;
     36import org.openstreetmap.josm.tools.Utils;
    3637
    3738/**
     
    8990                "<p>" + tr("Last change at {0}", version.getTime()) + "</p>" +
    9091                "<p style='font-size:50%'></p>" +
    91                 "<p>" + tr("Java Version {0}", System.getProperty("java.version")) + "</p>" +
     92                "<p>" + tr("Java Version {0}", Utils.getSystemProperty("java.version")) + "</p>" +
    9293                "<p style='font-size:50%'></p>" +
    9394                "</html>");
  • trunk/src/org/openstreetmap/josm/actions/JosmAction.java

    r13611 r13647  
    3636import org.openstreetmap.josm.tools.Destroyable;
    3737import org.openstreetmap.josm.tools.ImageProvider;
     38import org.openstreetmap.josm.tools.ImageResource;
    3839import org.openstreetmap.josm.tools.Logging;
    3940import org.openstreetmap.josm.tools.Shortcut;
     
    8182            String toolbarId, boolean installAdapters) {
    8283        super(name);
    83         if (icon != null)
    84             icon.getResource().attachImageIcon(this, true);
     84        if (icon != null) {
     85            ImageResource resource = icon.getResource();
     86            if (resource != null) {
     87                resource.attachImageIcon(this, true);
     88            }
     89        }
    8590        setHelpId();
    8691        sc = shortcut;
     
    119124    public JosmAction(String name, String iconName, String tooltip, Shortcut shortcut, boolean registerInToolbar,
    120125            String toolbarId, boolean installAdapters) {
    121         this(name, iconName == null ? null : new ImageProvider(iconName), tooltip, shortcut, registerInToolbar,
     126        this(name, iconName == null ? null : new ImageProvider(iconName).setOptional(true), tooltip, shortcut, registerInToolbar,
    122127                toolbarId == null ? iconName : toolbarId, installAdapters);
    123128    }
  • trunk/src/org/openstreetmap/josm/actions/RestartAction.java

    r13393 r13647  
    44import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
    55import static org.openstreetmap.josm.tools.I18n.tr;
     6import static org.openstreetmap.josm.tools.Utils.getSystemProperty;
    67
    78import java.awt.event.ActionEvent;
     
    7172     */
    7273    public static boolean isRestartSupported() {
    73         return System.getProperty("sun.java.command") != null;
     74        return getSystemProperty("sun.java.command") != null;
    7475    }
    7576
     
    8283        // it is executed by a start script that can handle restart.
    8384        // Request for restart is indicated by exit code 9.
    84         String scriptRestart = System.getProperty("josm.restart");
     85        String scriptRestart = getSystemProperty("josm.restart");
    8586        if ("true".equals(scriptRestart)) {
    8687            MainApplication.exitJosm(true, 9, SaveLayersDialog.Reason.RESTART);
     
    9091        final List<String> cmd;
    9192        // special handling for OSX .app package
    92         if (Main.isPlatformOsx() && System.getProperty("java.library.path").contains("/JOSM.app/Contents/MacOS")) {
     93        if (Main.isPlatformOsx() && getSystemProperty("java.library.path").contains("/JOSM.app/Contents/MacOS")) {
    9394            cmd = getAppleCommands();
    9495        } else {
     
    134135        // Determine webstart JNLP file. Use jnlpx.origFilenameArg instead of jnlp.application.href,
    135136        // because only this one is present when run from j2plauncher.exe (see #10795)
    136         final String jnlp = System.getProperty("jnlpx.origFilenameArg");
     137        final String jnlp = getSystemProperty("jnlpx.origFilenameArg");
    137138        // program main and program arguments (be careful a sun property. might not be supported by all JVM)
    138         final String javaCommand = System.getProperty("sun.java.command");
     139        final String javaCommand = getSystemProperty("sun.java.command");
    139140        if (javaCommand == null) {
    140141            throw new IOException("Unable to retrieve sun.java.command property");
     
    160161                // else it's a .class, add the classpath and mainClass
    161162                cmd.add("-cp");
    162                 cmd.add('"' + System.getProperty("java.class.path") + '"');
     163                cmd.add('"' + getSystemProperty("java.class.path") + '"');
    163164                cmd.add(mainCommand[0].replace("jdk.plugin/", "")); // Main class appears to be invalid on Java WebStart 9
    164165            }
     
    174175
    175176    private static String getJavaRuntime() throws IOException {
    176         final String java = System.getProperty("java.home") + File.separator + "bin" + File.separator +
     177        final String java = getSystemProperty("java.home") + File.separator + "bin" + File.separator +
    177178                (Main.isPlatformWindows() ? "java.exe" : "java");
    178179        if (!new File(java).isFile()) {
  • trunk/src/org/openstreetmap/josm/actions/ShowStatusReportAction.java

    r13434 r13647  
    44import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
    55import static org.openstreetmap.josm.tools.I18n.tr;
     6import static org.openstreetmap.josm.tools.Utils.getSystemEnv;
     7import static org.openstreetmap.josm.tools.Utils.getSystemProperty;
    68
    79import java.awt.Dimension;
     
    8486    public static String getReportHeader() {
    8587        StringBuilder text = new StringBuilder(256);
    86         String runtimeVersion = System.getProperty("java.runtime.version");
     88        String runtimeVersion = getSystemProperty("java.runtime.version");
    8789        text.append(Version.getInstance().getReleaseAttributes())
    8890            .append("\nIdentification: ").append(Version.getInstance().getAgentString());
     
    98100            .append(Runtime.getRuntime().freeMemory()/1024/1024)
    99101            .append(" MB allocated, but free)\nJava version: ")
    100             .append(runtimeVersion != null ? runtimeVersion : System.getProperty("java.version")).append(", ")
    101             .append(System.getProperty("java.vendor")).append(", ")
    102             .append(System.getProperty("java.vm.name"))
     102            .append(runtimeVersion != null ? runtimeVersion : getSystemProperty("java.version")).append(", ")
     103            .append(getSystemProperty("java.vendor")).append(", ")
     104            .append(getSystemProperty("java.vm.name"))
    103105            .append("\nScreen: ");
    104106        if (!GraphicsEnvironment.isHeadless()) {
     
    227229     */
    228230    private static String paramCleanup(String param) {
    229         final String envJavaHome = System.getenv("JAVA_HOME");
     231        final String envJavaHome = getSystemEnv("JAVA_HOME");
    230232        final String envJavaHomeAlt = Main.isPlatformWindows() ? "%JAVA_HOME%" : "${JAVA_HOME}";
    231         final String propJavaHome = System.getProperty("java.home");
     233        final String propJavaHome = getSystemProperty("java.home");
    232234        final String propJavaHomeAlt = "<java.home>";
    233235        final String prefDir = Config.getDirs().getPreferencesDirectory(false).toString();
     
    237239        final String userCacheDir = Config.getDirs().getCacheDirectory(false).toString();
    238240        final String userCacheDirAlt = "<josm.cache>";
    239         final String userHomeDir = System.getProperty("user.home");
     241        final String userHomeDir = getSystemProperty("user.home");
    240242        final String userHomeDirAlt = Main.isPlatformWindows() ? "%UserProfile%" : "${HOME}";
    241         final String userName = System.getProperty("user.name");
     243        final String userName = getSystemProperty("user.name");
    242244        final String userNameAlt = "<user.name>";
    243245
     
    250252        val = paramReplace(val, userCacheDir, userCacheDirAlt);
    251253        val = paramReplace(val, userHomeDir, userHomeDirAlt);
    252         if (userName.length() >= 3) {
     254        if (userName != null && userName.length() >= 3) {
    253255            val = paramReplace(val, userName, userNameAlt);
    254256        }
  • trunk/src/org/openstreetmap/josm/data/Preferences.java

    r13548 r13647  
    44import static org.openstreetmap.josm.tools.I18n.marktr;
    55import static org.openstreetmap.josm.tools.I18n.tr;
     6import static org.openstreetmap.josm.tools.Utils.getSystemEnv;
     7import static org.openstreetmap.josm.tools.Utils.getSystemProperty;
    68
    79import java.io.File;
     
    218220     */
    219221    public String getJOSMDirectoryBaseName() {
    220         String name = System.getProperty("josm.dir.name");
     222        String name = getSystemProperty("josm.dir.name");
    221223        if (name != null)
    222224            return name;
     
    343345        addPossibleResourceDir(locations, dirs.getPreferencesDirectory(false).getPath());
    344346        addPossibleResourceDir(locations, dirs.getUserDataDirectory(false).getPath());
    345         addPossibleResourceDir(locations, System.getenv("JOSM_RESOURCES"));
    346         addPossibleResourceDir(locations, System.getProperty("josm.resources"));
     347        addPossibleResourceDir(locations, getSystemEnv("JOSM_RESOURCES"));
     348        addPossibleResourceDir(locations, getSystemProperty("josm.resources"));
    347349        if (Main.isPlatformWindows()) {
    348             String appdata = System.getenv("APPDATA");
    349             if (appdata != null && System.getenv("ALLUSERSPROFILE") != null
     350            String appdata = getSystemEnv("APPDATA");
     351            if (appdata != null && getSystemEnv("ALLUSERSPROFILE") != null
    350352                    && appdata.lastIndexOf(File.separator) != -1) {
    351353                appdata = appdata.substring(appdata.lastIndexOf(File.separator));
    352                 locations.add(new File(new File(System.getenv("ALLUSERSPROFILE"),
     354                locations.add(new File(new File(getSystemEnv("ALLUSERSPROFILE"),
    353355                        appdata), "JOSM").getPath());
    354356            }
     
    456458                new PrintWriter(new File(prefFile + "_tmp"), StandardCharsets.UTF_8.name()), false, defaults)) {
    457459            writer.write(settings);
     460        } catch (SecurityException e) {
     461            throw new IOException(e);
    458462        }
    459463
     
    686690                    save();
    687691                } catch (IOException e) {
    688                     Logging.log(Logging.LEVEL_WARN, tr("Failed to persist preferences to ''{0}''", getPreferenceFile().getAbsoluteFile()), e);
     692                    File file = getPreferenceFile();
     693                    try {
     694                        file = file.getAbsoluteFile();
     695                    } catch (SecurityException ex) {
     696                        Logging.trace(ex);
     697                    }
     698                    Logging.log(Logging.LEVEL_WARN, tr("Failed to persist preferences to ''{0}''", file), e);
    689699                }
    690700            }
  • trunk/src/org/openstreetmap/josm/data/StructUtils.java

    r13563 r13647  
    160160                continue;
    161161            }
    162             Utils.setObjectsAccessible(f);
    163162            try {
     163                Utils.setObjectsAccessible(f);
    164164                Object fieldValue = f.get(struct);
    165165                Object defaultFieldValue = f.get(structPrototype);
     
    176176                    }
    177177                }
    178             } catch (IllegalAccessException ex) {
     178            } catch (IllegalAccessException | SecurityException ex) {
    179179                throw new JosmRuntimeException(ex);
    180180            }
  • trunk/src/org/openstreetmap/josm/data/Version.java

    r12627 r13647  
    1313import org.openstreetmap.josm.tools.LanguageInfo;
    1414import org.openstreetmap.josm.tools.Logging;
     15import org.openstreetmap.josm.tools.Utils;
    1516
    1617/**
     
    198199     */
    199200    public String getFullAgentString() {
    200         return getAgentString() + " Java/"+System.getProperty("java.version");
     201        return getAgentString() + " Java/"+Utils.getSystemProperty("java.version");
    201202    }
    202203}
  • trunk/src/org/openstreetmap/josm/data/cache/JCSCacheManager.java

    r13644 r13647  
    6262        // http://westsworld.dk/blog/2008/01/jcs-and-performance/
    6363        jcsLog = Logger.getLogger("org.apache.commons.jcs");
    64         jcsLog.setLevel(Level.INFO);
    65         jcsLog.setUseParentHandlers(false);
    66         // we need a separate handler from Main's, as we downgrade LEVEL.INFO to DEBUG level
    67         Arrays.stream(jcsLog.getHandlers()).forEach(jcsLog::removeHandler);
    68         jcsLog.addHandler(new Handler() {
    69             final SimpleFormatter formatter = new SimpleFormatter();
    70 
    71             @Override
    72             public void publish(LogRecord record) {
    73                 String msg = formatter.formatMessage(record);
    74                 if (record.getLevel().intValue() >= Level.SEVERE.intValue()) {
    75                     Logging.error(msg);
    76                 } else if (record.getLevel().intValue() >= Level.WARNING.intValue()) {
    77                     Logging.warn(msg);
    78                     // downgrade INFO level to debug, as JCS is too verbose at INFO level
    79                 } else if (record.getLevel().intValue() >= Level.INFO.intValue()) {
    80                     Logging.debug(msg);
    81                 } else {
    82                     Logging.trace(msg);
    83                 }
    84             }
    85 
    86             @Override
    87             public void flush() {
    88                 // nothing to be done on flush
    89             }
    90 
    91             @Override
    92             public void close() {
    93                 // nothing to be done on close
    94             }
    95         });
     64        try {
     65            jcsLog.setLevel(Level.INFO);
     66            jcsLog.setUseParentHandlers(false);
     67            // we need a separate handler from Main's, as we downgrade LEVEL.INFO to DEBUG level
     68            Arrays.stream(jcsLog.getHandlers()).forEach(jcsLog::removeHandler);
     69            jcsLog.addHandler(new Handler() {
     70                final SimpleFormatter formatter = new SimpleFormatter();
     71
     72                @Override
     73                public void publish(LogRecord record) {
     74                    String msg = formatter.formatMessage(record);
     75                    if (record.getLevel().intValue() >= Level.SEVERE.intValue()) {
     76                        Logging.error(msg);
     77                    } else if (record.getLevel().intValue() >= Level.WARNING.intValue()) {
     78                        Logging.warn(msg);
     79                        // downgrade INFO level to debug, as JCS is too verbose at INFO level
     80                    } else if (record.getLevel().intValue() >= Level.INFO.intValue()) {
     81                        Logging.debug(msg);
     82                    } else {
     83                        Logging.trace(msg);
     84                    }
     85                }
     86
     87                @Override
     88                public void flush() {
     89                    // nothing to be done on flush
     90                }
     91
     92                @Override
     93                public void close() {
     94                    // nothing to be done on close
     95                }
     96            });
     97        } catch (SecurityException e) {
     98            Logging.log(Logging.LEVEL_ERROR, "Unable to configure JCS logs", e);
     99        }
    96100    }
    97101
     
    101105
    102106    @SuppressWarnings("resource")
    103     private static void initialize()  {
     107    private static void initialize() {
    104108        File cacheDir = new File(Config.getDirs().getCacheDirectory(true), "jcs");
    105109
     
    124128        Properties props = new Properties();
    125129        // these are default common to all cache regions
    126         // use of auxiliary cache and sizing of the caches is done with giving proper geCache(...) params
     130        // use of auxiliary cache and sizing of the caches is done with giving proper getCache(...) params
    127131        // CHECKSTYLE.OFF: SingleSpaceSeparator
    128132        props.setProperty("jcs.default.cacheattributes",                      CompositeCacheAttributes.class.getCanonicalName());
  • trunk/src/org/openstreetmap/josm/data/imagery/CachedTileLoaderFactory.java

    r12856 r13647  
    4848                    Map.class);
    4949        } catch (NoSuchMethodException | SecurityException e) {
    50             Logging.warn(e);
     50            Logging.log(Logging.LEVEL_WARN, "Unable to initialize cache tile loader factory", e);
    5151            throw new IllegalArgumentException(e);
    5252        }
     
    5858            defPath = new File(Config.getDirs().getCacheDirectory(true), "tiles").getAbsolutePath();
    5959        } catch (SecurityException e) {
    60             Logging.warn(e);
     60            Logging.log(Logging.LEVEL_WARN, "Unable to get tile cache directory", e);
    6161        }
    6262        return new StringProperty("imagery.generic.loader.cachedir", defPath);
  • trunk/src/org/openstreetmap/josm/data/preferences/JosmBaseDirectories.java

    r13021 r13647  
    33
    44import static org.openstreetmap.josm.tools.I18n.tr;
     5import static org.openstreetmap.josm.tools.Utils.getSystemProperty;
    56
    67import java.io.File;
     
    2728    }
    2829
     30    /**
     31     * Returns the unique instance.
     32     * @return the unique instance
     33     */
    2934    public static JosmBaseDirectories getInstance() {
    3035        return InstanceHolder.INSTANCE;
     
    4954    public File getPreferencesDirectory(boolean createIfMissing) {
    5055        if (preferencesDir == null) {
    51             String path;
    52             path = System.getProperty("josm.pref");
     56            String path = getSystemProperty("josm.pref");
    5357            if (path != null) {
    5458                preferencesDir = new File(path).getAbsoluteFile();
    5559            } else {
    56                 path = System.getProperty("josm.home");
     60                path = getSystemProperty("josm.home");
    5761                if (path != null) {
    5862                    preferencesDir = new File(path).getAbsoluteFile();
     
    6266            }
    6367        }
    64         if (createIfMissing && !preferencesDir.exists() && !preferencesDir.mkdirs()) {
    65             Logging.warn(tr("Failed to create missing preferences directory: {0}", preferencesDir.getAbsoluteFile()));
    66             JOptionPane.showMessageDialog(
    67                     Main.parent,
    68                     tr("<html>Failed to create missing preferences directory: {0}</html>", preferencesDir.getAbsoluteFile()),
    69                     tr("Error"),
    70                     JOptionPane.ERROR_MESSAGE
    71             );
     68        try {
     69            if (createIfMissing && !preferencesDir.exists() && !preferencesDir.mkdirs()) {
     70                Logging.warn(tr("Failed to create missing preferences directory: {0}", preferencesDir.getAbsoluteFile()));
     71                JOptionPane.showMessageDialog(
     72                        Main.parent,
     73                        tr("<html>Failed to create missing preferences directory: {0}</html>", preferencesDir.getAbsoluteFile()),
     74                        tr("Error"),
     75                        JOptionPane.ERROR_MESSAGE
     76                );
     77            }
     78        } catch (SecurityException e) {
     79            Logging.log(Logging.LEVEL_ERROR, "Unable to check if preferences dir must be created", e);
    7280        }
    7381        return preferencesDir;
     
    7785    public File getUserDataDirectory(boolean createIfMissing) {
    7886        if (userdataDir == null) {
    79             String path;
    80             path = System.getProperty("josm.userdata");
     87            String path = getSystemProperty("josm.userdata");
    8188            if (path != null) {
    8289                userdataDir = new File(path).getAbsoluteFile();
    8390            } else {
    84                 path = System.getProperty("josm.home");
     91                path = getSystemProperty("josm.home");
    8592                if (path != null) {
    8693                    userdataDir = new File(path).getAbsoluteFile();
     
    9097            }
    9198        }
    92         if (createIfMissing && !userdataDir.exists() && !userdataDir.mkdirs()) {
    93             Logging.warn(tr("Failed to create missing user data directory: {0}", userdataDir.getAbsoluteFile()));
    94             JOptionPane.showMessageDialog(
    95                     Main.parent,
    96                     tr("<html>Failed to create missing user data directory: {0}</html>", userdataDir.getAbsoluteFile()),
    97                     tr("Error"),
    98                     JOptionPane.ERROR_MESSAGE
    99             );
     99        try {
     100            if (createIfMissing && !userdataDir.exists() && !userdataDir.mkdirs()) {
     101                Logging.warn(tr("Failed to create missing user data directory: {0}", userdataDir.getAbsoluteFile()));
     102                JOptionPane.showMessageDialog(
     103                        Main.parent,
     104                        tr("<html>Failed to create missing user data directory: {0}</html>", userdataDir.getAbsoluteFile()),
     105                        tr("Error"),
     106                        JOptionPane.ERROR_MESSAGE
     107                );
     108            }
     109        } catch (SecurityException e) {
     110            Logging.log(Logging.LEVEL_ERROR, "Unable to check if user data dir must be created", e);
    100111        }
    101112        return userdataDir;
     
    105116    public File getCacheDirectory(boolean createIfMissing) {
    106117        if (cacheDir == null) {
    107             String path = System.getProperty("josm.cache");
     118            String path = getSystemProperty("josm.cache");
    108119            if (path != null) {
    109120                cacheDir = new File(path).getAbsoluteFile();
    110121            } else {
    111                 path = System.getProperty("josm.home");
     122                path = getSystemProperty("josm.home");
    112123                if (path != null) {
    113124                    cacheDir = new File(path, "cache");
     
    122133            }
    123134        }
    124         if (createIfMissing && !cacheDir.exists() && !cacheDir.mkdirs()) {
    125             Logging.warn(tr("Failed to create missing cache directory: {0}", cacheDir.getAbsoluteFile()));
    126             JOptionPane.showMessageDialog(
    127                     Main.parent,
    128                     tr("<html>Failed to create missing cache directory: {0}</html>", cacheDir.getAbsoluteFile()),
    129                     tr("Error"),
    130                     JOptionPane.ERROR_MESSAGE
    131             );
     135        try {
     136            if (createIfMissing && !cacheDir.exists() && !cacheDir.mkdirs()) {
     137                Logging.warn(tr("Failed to create missing cache directory: {0}", cacheDir.getAbsoluteFile()));
     138                JOptionPane.showMessageDialog(
     139                        Main.parent,
     140                        tr("<html>Failed to create missing cache directory: {0}</html>", cacheDir.getAbsoluteFile()),
     141                        tr("Error"),
     142                        JOptionPane.ERROR_MESSAGE
     143                );
     144            }
     145        } catch (SecurityException e) {
     146            Logging.log(Logging.LEVEL_ERROR, "Unable to check if cache dir must be created", e);
    132147        }
    133148        return cacheDir;
  • trunk/src/org/openstreetmap/josm/data/projection/datum/NTV2Proj4DirGridShiftFileSource.java

    r13204 r13647  
    1414import org.openstreetmap.josm.tools.Platform;
    1515import org.openstreetmap.josm.tools.PlatformVisitor;
     16import org.openstreetmap.josm.tools.Utils;
    1617
    1718/**
     
    5152        // If not, search into PROJ_LIB directory
    5253        if (grid == null) {
    53             String projLib = System.getProperty("PROJ_LIB");
     54            String projLib = Utils.getSystemProperty("PROJ_LIB");
    5455            if (projLib != null && !projLib.isEmpty()) {
    5556                File dir = new File(projLib);
  • trunk/src/org/openstreetmap/josm/data/validation/OsmValidator.java

    r12856 r13647  
    6666import org.openstreetmap.josm.gui.layer.ValidatorLayer;
    6767import org.openstreetmap.josm.gui.preferences.projection.ProjectionPreference;
     68import org.openstreetmap.josm.gui.util.GuiHelper;
    6869import org.openstreetmap.josm.spi.preferences.Config;
    6970import org.openstreetmap.josm.tools.AlphanumComparator;
     
    176177     */
    177178    public static String getValidatorDir() {
    178         return new File(Config.getDirs().getUserDataDirectory(true), "validator").getAbsolutePath();
     179        File dir = new File(Config.getDirs().getUserDataDirectory(true), "validator");
     180        try {
     181            return dir.getAbsolutePath();
     182        } catch (SecurityException e) {
     183            Logging.log(Logging.LEVEL_ERROR, null, e);
     184            return dir.getPath();
     185        }
    179186    }
    180187
     
    184191    private static void checkValidatorDir() {
    185192        File pathDir = new File(getValidatorDir());
    186         if (!pathDir.exists()) {
    187             Utils.mkDirs(pathDir);
     193        try {
     194            if (!pathDir.exists()) {
     195                Utils.mkDirs(pathDir);
     196            }
     197        } catch (SecurityException e) {
     198            Logging.log(Logging.LEVEL_ERROR, "Unable to check validator directory", e);
    188199        }
    189200    }
     
    193204        if (ValidatorPrefHelper.PREF_USE_IGNORE.get()) {
    194205            Path path = Paths.get(getValidatorDir()).resolve("ignorederrors");
    195             if (path.toFile().exists()) {
    196                 try {
    197                     ignoredErrors.addAll(Files.readAllLines(path, StandardCharsets.UTF_8));
    198                 } catch (final FileNotFoundException e) {
    199                     Logging.debug(Logging.getErrorMessage(e));
    200                 } catch (final IOException e) {
    201                     Logging.error(e);
     206            try {
     207                if (path.toFile().exists()) {
     208                    try {
     209                        ignoredErrors.addAll(Files.readAllLines(path, StandardCharsets.UTF_8));
     210                    } catch (FileNotFoundException e) {
     211                        Logging.debug(Logging.getErrorMessage(e));
     212                    } catch (IOException e) {
     213                        Logging.error(e);
     214                    }
    202215                }
     216            } catch (SecurityException e) {
     217                Logging.log(Logging.LEVEL_ERROR, "Unable to load ignored errors", e);
    203218            }
    204219        }
     
    385400                }
    386401            } catch (Exception e) { // NOPMD
    387                 Logging.error(e);
     402                String message = tr("Error initializing test {0}:\n {1}", test.getClass().getSimpleName(), e);
     403                Logging.error(message);
    388404                if (!GraphicsEnvironment.isHeadless()) {
    389                     JOptionPane.showMessageDialog(Main.parent,
    390                             tr("Error initializing test {0}:\n {1}", test.getClass().getSimpleName(), e),
    391                             tr("Error"), JOptionPane.ERROR_MESSAGE);
     405                    GuiHelper.runInEDT(() -> {
     406                        JOptionPane.showMessageDialog(Main.parent, message, tr("Error"), JOptionPane.ERROR_MESSAGE);
     407                    });
    392408                }
    393409            }
  • trunk/src/org/openstreetmap/josm/gui/GettingStarted.java

    r12846 r13647  
    3333import org.openstreetmap.josm.tools.Logging;
    3434import org.openstreetmap.josm.tools.OpenBrowser;
     35import org.openstreetmap.josm.tools.Utils;
    3536import org.openstreetmap.josm.tools.WikiReader;
    3637
     
    8586
    8687        private final int myVersion = Version.getInstance().getVersion();
    87         private final String myJava = System.getProperty("java.version");
     88        private final String myJava = Utils.getSystemProperty("java.version");
    8889        private final String myLang = LanguageInfo.getWikiLanguagePrefix();
    8990
  • trunk/src/org/openstreetmap/josm/gui/MainApplication.java

    r13445 r13647  
    44import static org.openstreetmap.josm.tools.I18n.tr;
    55import static org.openstreetmap.josm.tools.I18n.trn;
     6import static org.openstreetmap.josm.tools.Utils.getSystemProperty;
    67
    78import java.awt.BorderLayout;
     
    357358            ed.setIcon(JOptionPane.WARNING_MESSAGE);
    358359            StringBuilder content = new StringBuilder(tr("You are running version {0} of Java.",
    359                     "<b>"+System.getProperty("java.version")+"</b>")).append("<br><br>");
    360             if ("Sun Microsystems Inc.".equals(System.getProperty("java.vendor")) && !platform.isOpenJDK()) {
     360                    "<b>"+getSystemProperty("java.version")+"</b>")).append("<br><br>");
     361            if ("Sun Microsystems Inc.".equals(getSystemProperty("java.vendor")) && !platform.isOpenJDK()) {
    361362                content.append("<b>").append(tr("This version is no longer supported by {0} since {1} and is not recommended for use.",
    362363                        "Oracle", eolDate)).append("</b><br><br>");
     
    421422                    try {
    422423                        OsmApi.getOsmApi().initialize(null, true);
    423                     } catch (OsmTransferCanceledException | OsmApiInitializationException e) {
     424                    } catch (OsmTransferCanceledException | OsmApiInitializationException | SecurityException e) {
    424425                        Logging.warn(Logging.getErrorMessage(Utils.getRootCause(e)));
    425426                    }
     
    485486    protected void shutdown() {
    486487        if (!GraphicsEnvironment.isHeadless()) {
    487             worker.shutdown();
     488            try {
     489                worker.shutdown();
     490            } catch (SecurityException e) {
     491                Logging.log(Logging.LEVEL_ERROR, "Unable to shutdown worker", e);
     492            }
    488493            JCSCacheManager.shutdown();
    489494        }
     
    498503        super.shutdown();
    499504        if (!GraphicsEnvironment.isHeadless()) {
    500             worker.shutdownNow();
     505            try {
     506                worker.shutdownNow();
     507            } catch (SecurityException e) {
     508                Logging.log(Logging.LEVEL_ERROR, "Unable to shutdown worker", e);
     509            }
    501510        }
    502511    }
     
    872881        I18n.set(language.orElse(null));
    873882
    874         Policy.setPolicy(new Policy() {
    875             // Permissions for plug-ins loaded when josm is started via webstart
    876             private PermissionCollection pc;
    877 
    878             {
    879                 pc = new Permissions();
    880                 pc.add(new AllPermission());
    881             }
    882 
    883             @Override
    884             public PermissionCollection getPermissions(CodeSource codesource) {
    885                 return pc;
    886             }
    887         });
    888 
    889         Thread.setDefaultUncaughtExceptionHandler(new BugReportExceptionHandler());
     883        try {
     884            Policy.setPolicy(new Policy() {
     885                // Permissions for plug-ins loaded when josm is started via webstart
     886                private PermissionCollection pc;
     887
     888                {
     889                    pc = new Permissions();
     890                    pc.add(new AllPermission());
     891                }
     892
     893                @Override
     894                public PermissionCollection getPermissions(CodeSource codesource) {
     895                    return pc;
     896                }
     897            });
     898        } catch (SecurityException e) {
     899            Logging.log(Logging.LEVEL_ERROR, "Unable to set permissions", e);
     900        }
     901
     902        try {
     903            Thread.setDefaultUncaughtExceptionHandler(new BugReportExceptionHandler());
     904        } catch (SecurityException e) {
     905            Logging.log(Logging.LEVEL_ERROR, "Unable to set uncaught exception handler", e);
     906        }
    890907
    891908        // initialize the platform hook, and
     
    917934        }
    918935
    919         Main.pref.init(args.hasOption(Option.RESET_PREFERENCES));
     936        try {
     937            Main.pref.init(args.hasOption(Option.RESET_PREFERENCES));
     938        } catch (SecurityException e) {
     939            Logging.log(Logging.LEVEL_ERROR, "Unable to initialize preferences", e);
     940        }
    920941
    921942        args.getPreferencesToSet().forEach(Main.pref::put);
     
    9791000            Logging.warn(Logging.getErrorMessage(Utils.getRootCause(ex)));
    9801001        }
    981         Authenticator.setDefault(DefaultAuthenticator.getInstance());
    982         DefaultProxySelector proxySelector = new DefaultProxySelector(ProxySelector.getDefault());
    983         ProxySelector.setDefault(proxySelector);
     1002        try {
     1003            Authenticator.setDefault(DefaultAuthenticator.getInstance());
     1004        } catch (SecurityException e) {
     1005            Logging.log(Logging.LEVEL_ERROR, "Unable to set default authenticator", e);
     1006        }
     1007        DefaultProxySelector proxySelector = null;
     1008        try {
     1009            proxySelector = new DefaultProxySelector(ProxySelector.getDefault());
     1010        } catch (SecurityException e) {
     1011            Logging.log(Logging.LEVEL_ERROR, "Unable to get default proxy selector", e);
     1012        }
     1013        try {
     1014            if (proxySelector != null) {
     1015                ProxySelector.setDefault(proxySelector);
     1016            }
     1017        } catch (SecurityException e) {
     1018            Logging.log(Logging.LEVEL_ERROR, "Unable to set default proxy selector", e);
     1019        }
    9841020        OAuthAccessTokenHolder.getInstance().init(CredentialsManager.getInstance());
    9851021
     
    10931129            } catch (ReflectiveOperationException | RuntimeException e) { // NOPMD
    10941130                // Catch RuntimeException in order to catch InaccessibleObjectException, new in Java 9
    1095                 Logging.warn(e);
     1131                Logging.log(Logging.LEVEL_WARN, null, e);
    10961132            }
    10971133        }
     
    11201156        // Workaround for JDK-8180379: crash on Windows 10 1703 with Windows L&F and java < 8u141 / 9+172
    11211157        // To remove during Java 9 migration
    1122         if (System.getProperty("os.name").toLowerCase(Locale.ENGLISH).contains("windows 10") &&
     1158        if (getSystemProperty("os.name").toLowerCase(Locale.ENGLISH).contains("windows 10") &&
    11231159                platform.getDefaultStyle().equals(LafPreference.LAF.get())) {
    11241160            try {
     
    11351171            } catch (NumberFormatException | ReflectiveOperationException | JosmRuntimeException e) {
    11361172                Logging.error(e);
     1173            } catch (ExceptionInInitializerError e) {
     1174                Logging.log(Logging.LEVEL_ERROR, null, e);
    11371175            }
    11381176        }
     
    11961234        }
    11971235
    1198         UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
     1236        UIManager.put("OptionPane.okIcon", ImageProvider.getIfAvailable("ok"));
    11991237        UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
    1200         UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
     1238        UIManager.put("OptionPane.cancelIcon", ImageProvider.getIfAvailable("cancel"));
    12011239        UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
    12021240        // Ensures caret color is the same than text foreground color, see #12257
     
    12281266
    12291267        monitor.indeterminateSubTask(tr("Installing updated plugins"));
    1230         PluginHandler.installDownloadedPlugins(pluginsToLoad, true);
     1268        try {
     1269            PluginHandler.installDownloadedPlugins(pluginsToLoad, true);
     1270        } catch (SecurityException e) {
     1271            Logging.log(Logging.LEVEL_ERROR, "Unable to install plugins", e);
     1272        }
    12311273
    12321274        monitor.indeterminateSubTask(tr("Loading early plugins"));
     
    14041446                    }
    14051447                }
    1406                 autosaveTask.schedule();
     1448                try {
     1449                    autosaveTask.schedule();
     1450                } catch (SecurityException e) {
     1451                    Logging.log(Logging.LEVEL_ERROR, "Unable to schedule autosave!", e);
     1452                }
    14071453            }
    14081454        }
     
    14261472
    14271473        private boolean handleProxyErrors() {
    1428             return handleNetworkOrProxyErrors(proxySelector.hasErrors(), tr("Proxy errors occurred"),
     1474            return proxySelector != null &&
     1475                handleNetworkOrProxyErrors(proxySelector.hasErrors(), tr("Proxy errors occurred"),
    14291476                    tr("JOSM tried to access the following resources:<br>" +
    14301477                            "{0}" +
  • trunk/src/org/openstreetmap/josm/gui/MainFrame.java

    r12846 r13647  
    1717import java.util.List;
    1818
     19import javax.swing.ImageIcon;
    1920import javax.swing.JFrame;
    2021import javax.swing.JPanel;
     
    8283        geometry.applySafe(this);
    8384        List<Image> l = new LinkedList<>();
    84         l.add(ImageProvider.get("logo_16x16x32").getImage());
    85         l.add(ImageProvider.get("logo_16x16x8").getImage());
    86         l.add(ImageProvider.get("logo_32x32x32").getImage());
    87         l.add(ImageProvider.get("logo_32x32x8").getImage());
    88         l.add(ImageProvider.get("logo_48x48x32").getImage());
    89         l.add(ImageProvider.get("logo_48x48x8").getImage());
    90         l.add(ImageProvider.get("logo").getImage());
     85        for (String file : new String[] {
     86                "logo_16x16x32", "logo_16x16x8", "logo_32x32x32", "logo_32x32x8", "logo_48x48x32", "logo_48x48x8", "logo"}) {
     87            ImageIcon img = ImageProvider.getIfAvailable(file);
     88            if (img != null) {
     89                l.add(img.getImage());
     90            }
     91        }
    9192        setIconImages(l);
    9293        addWindowListener(new ExitWindowAdapter());
  • trunk/src/org/openstreetmap/josm/gui/bugreport/BugReportDialog.java

    r13330 r13647  
    175175        panel.add(settings);
    176176
    177         JButton sendBugReportButton = new JButton(tr("Report Bug"), ImageProvider.get("bug"));
     177        JButton sendBugReportButton = new JButton(tr("Report Bug"), ImageProvider.getIfAvailable("bug"));
    178178        sendBugReportButton.addActionListener(e -> sendBug());
    179179        panel.add(sendBugReportButton, GBC.eol().insets(0, 0, 0, 0).anchor(GBC.SOUTHEAST));
  • trunk/src/org/openstreetmap/josm/gui/bugreport/JosmUpdatePanel.java

    r13068 r13647  
    9292        add(new JMultilineLabel(tr("Before you file a bug report make sure you have updated to the latest version of JOSM here:")), GBC.eol());
    9393        add(new UrlLabel(Main.getJOSMWebsite(), 2), GBC.eop().insets(8, 0, 0, 0));
    94         JButton updateButton = new JButton(tr("Update JOSM"), ImageProvider.get("download"));
     94        JButton updateButton = new JButton(tr("Update JOSM"), ImageProvider.getIfAvailable("download"));
    9595        updateButton.addActionListener(e -> openJosmUpdateSite());
    9696        add(updateButton, GBC.eol().anchor(GBC.EAST));
  • trunk/src/org/openstreetmap/josm/gui/conflict/tags/TagConflictResolutionUtil.java

    r12851 r13647  
    2121import org.openstreetmap.josm.data.osm.TagCollection;
    2222import org.openstreetmap.josm.spi.preferences.Config;
     23import org.openstreetmap.josm.tools.JosmRuntimeException;
    2324import org.openstreetmap.josm.tools.Logging;
    2425import org.openstreetmap.josm.tools.Pair;
     
    137138            // make sure the empty value is in the tag set such that we can delete the tag
    138139            // in the conflict dialog if necessary
    139             //
    140140            tc.add(new Tag(key, ""));
    141141        }
     
    149149     */
    150150    public static void applyAutomaticTagConflictResolution(TagCollection tc) {
    151         applyAutomaticTagConflictResolution(tc, getAutomaticTagConflictResolvers());
     151        try {
     152            applyAutomaticTagConflictResolution(tc, getAutomaticTagConflictResolvers());
     153        } catch (JosmRuntimeException e) {
     154            Logging.log(Logging.LEVEL_ERROR, "Unable to automatically resolve tag conflicts", e);
     155        }
    152156    }
    153157
  • trunk/src/org/openstreetmap/josm/gui/datatransfer/ClipboardUtils.java

    r12620 r13647  
    4949            try {
    5050                clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    51             } catch (HeadlessException e) {
    52                 Logging.warn("Headless. Using fake clipboard.", e);
     51            } catch (HeadlessException | SecurityException e) {
     52                Logging.warn("Using fake clipboard.", e);
    5353                clipboard = new Clipboard("fake");
    5454            }
  • trunk/src/org/openstreetmap/josm/gui/dialogs/MapPaintDialog.java

    r13036 r13647  
    450450            final StyleSource s = model.getRow(sel);
    451451
    452             FileChooserManager fcm = new FileChooserManager(false, "mappaint.clone-style.lastDirectory", System.getProperty("user.home"));
     452            FileChooserManager fcm = new FileChooserManager(false, "mappaint.clone-style.lastDirectory", Utils.getSystemProperty("user.home"));
    453453            String suggestion = fcm.getInitialDirectory() + File.separator + s.getFileNamePart();
    454454
  • trunk/src/org/openstreetmap/josm/gui/io/RecentlyOpenedFilesMenu.java

    r12846 r13647  
    3434        super(tr("Open Recent"));
    3535        setToolTipText(tr("List of recently opened files"));
    36         setIcon(ImageProvider.get("openrecent", ImageProvider.ImageSizes.MENU));
     36        setIcon(new ImageProvider("openrecent").setOptional(true).setSize(ImageProvider.ImageSizes.MENU).get());
    3737        putClientProperty("help", ht("/Action/OpenRecent"));
    3838
  • trunk/src/org/openstreetmap/josm/gui/io/SaveLayersDialog.java

    r13206 r13647  
    5555import org.openstreetmap.josm.tools.GBC;
    5656import org.openstreetmap.josm.tools.ImageProvider;
     57import org.openstreetmap.josm.tools.ImageResource;
    5758import org.openstreetmap.josm.tools.InputMapUtils;
    5859import org.openstreetmap.josm.tools.Logging;
     
    364365            putValue(NAME, tr("Cancel"));
    365366            putValue(SHORT_DESCRIPTION, tr("Close this dialog and resume editing in JOSM"));
    366             new ImageProvider("cancel").getResource().attachImageIcon(this, true);
     367            ImageResource resource = new ImageProvider("cancel").setOptional(true).getResource();
     368            if (resource != null) {
     369                resource.attachImageIcon(this, true);
     370            }
    367371            InputMapUtils.addEscapeAction(getRootPane(), this);
    368372        }
     
    398402                    putValue(NAME, tr("Exit now!"));
    399403                    putValue(SHORT_DESCRIPTION, tr("Exit JOSM without saving. Unsaved changes are lost."));
    400                     new ImageProvider("exit").getResource().attachImageIcon(this, true);
     404                    attachImageIcon(new ImageProvider("exit"));
    401405                    break;
    402406                case RESTART:
    403407                    putValue(NAME, tr("Restart now!"));
    404408                    putValue(SHORT_DESCRIPTION, tr("Restart JOSM without saving. Unsaved changes are lost."));
    405                     new ImageProvider("restart").getResource().attachImageIcon(this, true);
     409                    attachImageIcon(new ImageProvider("restart"));
    406410                    break;
    407411                case DELETE:
    408412                    putValue(NAME, tr("Delete now!"));
    409413                    putValue(SHORT_DESCRIPTION, tr("Delete layers without saving. Unsaved changes are lost."));
    410                     new ImageProvider("dialogs", "delete").getResource().attachImageIcon(this, true);
    411                     break;
    412             }
    413 
     414                    attachImageIcon(new ImageProvider("dialogs", "delete"));
     415                    break;
     416            }
     417        }
     418
     419        private void attachImageIcon(ImageProvider provider) {
     420            ImageResource resource = provider.setOptional(true).getResource();
     421            if (resource != null) {
     422                resource.attachImageIcon(this, true);
     423            }
    414424        }
    415425
     
    465475
    466476        Image getImage(String name, boolean disabled) {
    467             ImageIcon img = new ImageProvider(name).setDisabled(disabled).get();
     477            ImageIcon img = new ImageProvider(name).setDisabled(disabled).setOptional(true).get();
    468478            return img != null ? img.getImage() : null;
    469479        }
     
    474484                    putValue(NAME, tr("Perform actions before exiting"));
    475485                    putValue(SHORT_DESCRIPTION, tr("Exit JOSM with saving. Unsaved changes are uploaded and/or saved."));
    476                     putValue(BASE_ICON, ImageProvider.get("exit"));
     486                    putValue(BASE_ICON, ImageProvider.getIfAvailable("exit"));
    477487                    break;
    478488                case RESTART:
    479489                    putValue(NAME, tr("Perform actions before restarting"));
    480490                    putValue(SHORT_DESCRIPTION, tr("Restart JOSM with saving. Unsaved changes are uploaded and/or saved."));
    481                     putValue(BASE_ICON, ImageProvider.get("restart"));
     491                    putValue(BASE_ICON, ImageProvider.getIfAvailable("restart"));
    482492                    break;
    483493                case DELETE:
    484494                    putValue(NAME, tr("Perform actions before deleting"));
    485495                    putValue(SHORT_DESCRIPTION, tr("Save/Upload layers before deleting. Unsaved changes are not lost."));
    486                     putValue(BASE_ICON, ImageProvider.get("dialogs", "delete"));
     496                    putValue(BASE_ICON, ImageProvider.getIfAvailable("dialogs", "delete"));
    487497                    break;
    488498            }
     
    491501
    492502        public void redrawIcon() {
    493             Image base = ((ImageIcon) getValue(BASE_ICON)).getImage();
     503            ImageIcon base = ((ImageIcon) getValue(BASE_ICON));
    494504            BufferedImage newIco = new BufferedImage(ICON_SIZE*3, ICON_SIZE, BufferedImage.TYPE_4BYTE_ABGR);
    495505            Graphics2D g = newIco.createGraphics();
     
    497507            g.drawImage(model.getLayersToUpload().isEmpty() ? upldDis : upld, ICON_SIZE*0, 0, ICON_SIZE, ICON_SIZE, null);
    498508            g.drawImage(model.getLayersToSave().isEmpty()   ? saveDis : save, ICON_SIZE*1, 0, ICON_SIZE, ICON_SIZE, null);
    499             g.drawImage(base,                                                 ICON_SIZE*2, 0, ICON_SIZE, ICON_SIZE, null);
     509            if (base != null) {
     510                g.drawImage(base.getImage(),                                  ICON_SIZE*2, 0, ICON_SIZE, ICON_SIZE, null);
     511            }
    500512            // CHECKSTYLE.ON: SingleSpaceSeparator
    501513            putValue(SMALL_ICON, new ImageIcon(newIco));
  • trunk/src/org/openstreetmap/josm/gui/layer/AutosaveTask.java

    r13114 r13647  
    44import static org.openstreetmap.josm.tools.I18n.marktr;
    55import static org.openstreetmap.josm.tools.I18n.tr;
     6import static org.openstreetmap.josm.tools.Utils.getSystemProperty;
    67
    78import java.io.BufferedReader;
     
    383384    public List<File> getUnsavedLayersFiles() {
    384385        List<File> result = new ArrayList<>();
    385         File[] files = autosaveDir.listFiles((FileFilter)
    386                 pathname -> OsmImporter.FILE_FILTER.accept(pathname) || NoteImporter.FILE_FILTER.accept(pathname));
    387         if (files == null)
    388             return result;
    389         for (File file: files) {
    390             if (file.isFile()) {
    391                 boolean skipFile = false;
    392                 File pidFile = getPidFile(file);
    393                 if (pidFile.exists()) {
    394                     try (BufferedReader reader = Files.newBufferedReader(pidFile.toPath(), StandardCharsets.UTF_8)) {
    395                         String jvmId = reader.readLine();
    396                         if (jvmId != null) {
    397                             String pid = jvmId.split("@")[0];
    398                             skipFile = jvmPerfDataFileExists(pid);
     386        try {
     387            File[] files = autosaveDir.listFiles((FileFilter)
     388                    pathname -> OsmImporter.FILE_FILTER.accept(pathname) || NoteImporter.FILE_FILTER.accept(pathname));
     389            if (files == null)
     390                return result;
     391            for (File file: files) {
     392                if (file.isFile()) {
     393                    boolean skipFile = false;
     394                    File pidFile = getPidFile(file);
     395                    if (pidFile.exists()) {
     396                        try (BufferedReader reader = Files.newBufferedReader(pidFile.toPath(), StandardCharsets.UTF_8)) {
     397                            String jvmId = reader.readLine();
     398                            if (jvmId != null) {
     399                                String pid = jvmId.split("@")[0];
     400                                skipFile = jvmPerfDataFileExists(pid);
     401                            }
     402                        } catch (IOException | SecurityException t) {
     403                            Logging.error(t);
    399404                        }
    400                     } catch (IOException | SecurityException t) {
    401                         Logging.error(t);
    402405                    }
    403                 }
    404                 if (!skipFile) {
    405                     result.add(file);
    406                 }
    407             }
     406                    if (!skipFile) {
     407                        result.add(file);
     408                    }
     409                }
     410            }
     411        } catch (SecurityException e) {
     412            Logging.log(Logging.LEVEL_ERROR, "Unable to list unsaved layers files", e);
    408413        }
    409414        return result;
     
    411416
    412417    private static boolean jvmPerfDataFileExists(final String jvmId) {
    413         File jvmDir = new File(System.getProperty("java.io.tmpdir") + File.separator + "hsperfdata_" + System.getProperty("user.name"));
     418        File jvmDir = new File(getSystemProperty("java.io.tmpdir") + File.separator + "hsperfdata_" + getSystemProperty("user.name"));
    414419        if (jvmDir.exists() && jvmDir.canRead()) {
    415420            File[] files = jvmDir.listFiles((FileFilter) file -> file.getName().equals(jvmId) && file.isFile());
  • trunk/src/org/openstreetmap/josm/gui/mappaint/StyleSource.java

    r12825 r13647  
    223223            i = new ImageProvider(i).addOverlay(new ImageOverlay(new ImageProvider("warning-small"), 0.5, 0.5, 1, 1));
    224224        }
    225         return i;
     225        return i.setOptional(true);
    226226    }
    227227
  • trunk/src/org/openstreetmap/josm/gui/widgets/TextContextualPopupMenu.java

    r13504 r13647  
    173173            mi.setText(label);
    174174            if (iconName != null && Config.getPref().getBoolean("text.popupmenu.useicons", true)) {
    175                 ImageIcon icon = ImageProvider.get(iconName, ImageProvider.ImageSizes.SMALLICON);
     175                ImageIcon icon = new ImageProvider(iconName).setOptional(true).setSize(ImageProvider.ImageSizes.SMALLICON).get();
    176176                if (icon != null) {
    177177                    mi.setIcon(icon);
  • trunk/src/org/openstreetmap/josm/io/CacheCustomContent.java

    r13204 r13647  
    205205            output.write(this.data);
    206206            output.flush();
    207         } catch (IOException | InvalidPathException e) {
    208             Logging.error(e);
     207        } catch (IOException | InvalidPathException | SecurityException e) {
     208            Logging.log(Logging.LEVEL_ERROR, "Unable to save data", e);
    209209        }
    210210    }
  • trunk/src/org/openstreetmap/josm/io/CachedFile.java

    r13560 r13647  
    282282                }
    283283            } else {
    284                 cacheFile = checkLocal(url);
     284                try {
     285                    cacheFile = checkLocal(url);
     286                } catch (SecurityException e) {
     287                    throw new IOException(e);
     288                }
    285289            }
    286290        } catch (MalformedURLException e) {
  • trunk/src/org/openstreetmap/josm/io/CertificateAmendment.java

    r13605 r13647  
    192192            return;
    193193        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    194         Path cacertsPath = Paths.get(System.getProperty("java.home"), "lib", "security", "cacerts");
     194        Path cacertsPath = Paths.get(Utils.getSystemProperty("java.home"), "lib", "security", "cacerts");
    195195        try (InputStream is = Files.newInputStream(cacertsPath)) {
    196196            keyStore.load(is, "changeit".toCharArray());
     197        } catch (SecurityException e) {
     198            Logging.log(Logging.LEVEL_ERROR, "Unable to load keystore", e);
     199            return;
    197200        }
    198201
  • trunk/src/org/openstreetmap/josm/io/DefaultProxySelector.java

    r13493 r13647  
    2020import org.openstreetmap.josm.spi.preferences.Config;
    2121import org.openstreetmap.josm.tools.Logging;
     22import org.openstreetmap.josm.tools.Utils;
    2223
    2324/**
     
    5960    private static boolean jvmWillUseSystemProxies;
    6061    static {
    61         String v = System.getProperty("java.net.useSystemProxies");
     62        String v = Utils.getSystemProperty("java.net.useSystemProxies");
    6263        if (v != null && v.equals(Boolean.TRUE.toString())) {
    6364            jvmWillUseSystemProxies = true;
  • trunk/src/org/openstreetmap/josm/io/OsmApi.java

    r13499 r13647  
    252252                // In that case, force update and try again
    253253                initializeCapabilities(cache.updateForceString());
     254            } catch (SecurityException e) {
     255                Logging.log(Logging.LEVEL_ERROR, "Unable to initialize OSM API", e);
    254256            }
    255257            if (capabilities == null) {
  • trunk/src/org/openstreetmap/josm/io/protocols/data/Handler.java

    r10936 r13647  
    3030        String pkg = pkgName.substring(0, pkgName.lastIndexOf('.'));
    3131
    32         String protocolHandlers = System.getProperty("java.protocol.handler.pkgs", "");
    33         if (!protocolHandlers.contains(pkg)) {
     32        String protocolHandlers = Utils.getSystemProperty("java.protocol.handler.pkgs");
     33        if (protocolHandlers != null && !protocolHandlers.contains(pkg)) {
    3434            StringBuilder sb = new StringBuilder(protocolHandlers);
    3535            if (sb.length() > 0) {
  • trunk/src/org/openstreetmap/josm/plugins/PluginHandler.java

    r13300 r13647  
    965965            Set<String> plugins = new HashSet<>(Config.getPref().getList("plugins", new LinkedList<String>()));
    966966            Logging.debug("Plugins list initialized to {0}", plugins);
    967             String systemProp = System.getProperty("josm.plugins");
     967            String systemProp = Utils.getSystemProperty("josm.plugins");
    968968            if (systemProp != null) {
    969969                plugins.addAll(Arrays.asList(systemProp.split(",")));
  • trunk/src/org/openstreetmap/josm/plugins/ReadLocalPluginInformationTask.java

    r13204 r13647  
    138138        try {
    139139            monitor.beginTask("");
    140             scanSiteCacheFiles(monitor, pluginsDirectory);
    141             scanPluginFiles(monitor, pluginsDirectory);
     140            try {
     141                scanSiteCacheFiles(monitor, pluginsDirectory);
     142            } catch (SecurityException e) {
     143                Logging.log(Logging.LEVEL_ERROR, "Unable to scan site cache files", e);
     144            }
     145            try {
     146                scanPluginFiles(monitor, pluginsDirectory);
     147            } catch (SecurityException e) {
     148                Logging.log(Logging.LEVEL_ERROR, "Unable to scan plugin files", e);
     149            }
    142150        } finally {
    143151            monitor.setCustomText("");
  • trunk/src/org/openstreetmap/josm/tools/HttpClient.java

    r13358 r13647  
    7070
    7171    static {
    72         CookieHandler.setDefault(new CookieManager());
     72        try {
     73            CookieHandler.setDefault(new CookieManager());
     74        } catch (SecurityException e) {
     75            Logging.log(Logging.LEVEL_ERROR, "Unable to set default cookie handler", e);
     76        }
    7377    }
    7478
  • trunk/src/org/openstreetmap/josm/tools/I18n.java

    r13544 r13647  
    351351        // FIXME: This must be updated after we switch to Java 9.
    352352        // See https://docs.oracle.com/javase/9/docs/api/java/util/spi/LocaleServiceProvider.html
    353         System.setProperty("java.locale.providers", "SPI,JRE,CLDR"); // Don't call Utils.updateSystemProperty to avoid spurious log at startup
     353        try {
     354            // Don't call Utils.updateSystemProperty to avoid spurious log at startup
     355            System.setProperty("java.locale.providers", "SPI,JRE,CLDR");
     356        } catch (SecurityException e) {
     357            // Don't call Logging class, it may not be fully initialized yet
     358            System.err.println("Unable to set locale providers: " + e.getMessage());
     359        }
    354360    }
    355361
  • trunk/src/org/openstreetmap/josm/tools/ImageProvider.java

    r13493 r13647  
    256256
    257257    /** set of class loaders to take images from */
    258     protected static final Set<ClassLoader> classLoaders = new HashSet<>(Arrays.asList(
    259             ClassLoader.getSystemClassLoader(), ImageProvider.class.getClassLoader()));
     258    protected static final Set<ClassLoader> classLoaders = new HashSet<>();
     259    static {
     260        try {
     261            classLoaders.add(ClassLoader.getSystemClassLoader());
     262        } catch (SecurityException e) {
     263            Logging.log(Logging.LEVEL_ERROR, "Unable to get system classloader", e);
     264        }
     265        try {
     266            classLoaders.add(ImageProvider.class.getClassLoader());
     267        } catch (SecurityException e) {
     268            Logging.log(Logging.LEVEL_ERROR, "Unable to get application classloader", e);
     269        }
     270    }
    260271
    261272    /** directories in which images are searched */
     
    11321143        switch (type) {
    11331144        case SVG:
    1134             SVGDiagram svg;
     1145            SVGDiagram svg = null;
    11351146            synchronized (getSvgUniverse()) {
    1136                 URI uri = getSvgUniverse().loadSVG(path);
    1137                 svg = getSvgUniverse().getDiagram(uri);
     1147                try {
     1148                    URI uri = getSvgUniverse().loadSVG(path);
     1149                    svg = getSvgUniverse().getDiagram(uri);
     1150                } catch (SecurityException e) {
     1151                    Logging.log(Logging.LEVEL_WARN, "Unable to read SVG", e);
     1152                }
    11381153            }
    11391154            return svg == null ? null : new ImageResource(svg);
     
    11491164                }
    11501165            } catch (IOException e) {
    1151                 Logging.warn(e);
     1166                Logging.log(Logging.LEVEL_WARN, "Unable to read image", e);
     1167                Logging.debug(e);
    11521168            }
    11531169            return img == null ? null : new ImageResource(img);
     
    11671183        } else {
    11681184            File f = new File(path, name);
    1169             if ((path != null || f.isAbsolute()) && f.exists())
    1170                 return Utils.fileToURL(f);
     1185            try {
     1186                if ((path != null || f.isAbsolute()) && f.exists())
     1187                    return Utils.fileToURL(f);
     1188            } catch (SecurityException e) {
     1189                Logging.log(Logging.LEVEL_ERROR, "Unable to access image", e);
     1190            }
    11711191        }
    11721192        return null;
     
    11931213        // Try user-data directory
    11941214        if (Config.getDirs() != null) {
    1195             String dir = new File(Config.getDirs().getUserDataDirectory(false), "images").getAbsolutePath();
     1215            File file = new File(Config.getDirs().getUserDataDirectory(false), "images");
     1216            String dir = file.getPath();
     1217            try {
     1218                dir = file.getAbsolutePath();
     1219            } catch (SecurityException e) {
     1220                Logging.debug(e);
     1221            }
    11961222            try {
    11971223                u = getImageUrl(dir, imageName);
     
    17301756            }
    17311757            return bi;
    1732         } catch (IOException e) {
    1733             throw new IIOException("Can't get input stream from URL!", e);
     1758        } catch (SecurityException e) {
     1759            throw new IOException(e);
    17341760        }
    17351761    }
     
    19421968     */
    19431969    public static void shutdown(boolean now) {
    1944         if (now) {
    1945             IMAGE_FETCHER.shutdownNow();
    1946         } else {
    1947             IMAGE_FETCHER.shutdown();
     1970        try {
     1971            if (now) {
     1972                IMAGE_FETCHER.shutdownNow();
     1973            } else {
     1974                IMAGE_FETCHER.shutdown();
     1975            }
     1976        } catch (SecurityException ex) {
     1977            Logging.log(Logging.LEVEL_ERROR, "Failed to shutdown background image fetcher.", ex);
    19481978        }
    19491979    }
  • trunk/src/org/openstreetmap/josm/tools/Logging.java

    r13263 r13647  
    6464        ConsoleHandler stderr = new ConsoleHandler();
    6565        LOGGER.addHandler(stderr);
    66         stderr.setLevel(LEVEL_WARN);
     66        try {
     67            stderr.setLevel(LEVEL_WARN);
     68        } catch (SecurityException e) {
     69            System.err.println("Unable to set logging level: " + e.getMessage());
     70        }
    6771
    6872        ConsoleHandler stdout = new ConsoleHandler() {
     
    8185        };
    8286        LOGGER.addHandler(stdout);
    83         stdout.setLevel(Level.ALL);
     87        try {
     88            stdout.setLevel(Level.ALL);
     89        } catch (SecurityException e) {
     90            System.err.println("Unable to set logging level: " + e.getMessage());
     91        }
    8492
    8593        LOGGER.addHandler(WARNINGS);
     
    404412        private int messagesLogged;
    405413
    406         RememberWarningHandler() {
    407             setLevel(LEVEL_WARN);
    408         }
    409 
    410414        synchronized void clear() {
    411415            messagesLogged = 0;
     
    415419        @Override
    416420        public synchronized void publish(LogRecord record) {
    417             if (!isLoggable(record)) {
     421            // We don't use setLevel + isLoggable to work in WebStart Sandbox mode
     422            if (record.getLevel().intValue() < LEVEL_WARN.intValue()) {
    418423                return;
    419424            }
  • trunk/src/org/openstreetmap/josm/tools/Platform.java

    r12784 r13647  
    5454    public static Platform determinePlatform() {
    5555        if (platform == null) {
    56             String os = System.getProperty("os.name");
     56            String os = Utils.getSystemProperty("os.name");
    5757            if (os == null) {
    5858                Logging.warn("Your operating system has no name, so I'm guessing its some kind of *nix.");
  • trunk/src/org/openstreetmap/josm/tools/PlatformHook.java

    r13504 r13647  
    268268     */
    269269    default boolean isOpenJDK() {
    270         String javaHome = System.getProperty("java.home");
     270        String javaHome = Utils.getSystemProperty("java.home");
    271271        return javaHome != null && javaHome.contains("openjdk");
    272272    }
  • trunk/src/org/openstreetmap/josm/tools/PlatformHookOsx.java

    r13450 r13647  
    33
    44import static org.openstreetmap.josm.tools.I18n.tr;
     5import static org.openstreetmap.josm.tools.Utils.getSystemProperty;
    56
    67import java.awt.Desktop;
     
    393394    @Override
    394395    public String getOSDescription() {
    395         return System.getProperty("os.name") + ' ' + System.getProperty("os.version");
     396        return getSystemProperty("os.name") + ' ' + getSystemProperty("os.version");
    396397    }
    397398
     
    421422    @Override
    422423    public File getDefaultCacheDirectory() {
    423         return new File(System.getProperty("user.home")+"/Library/Caches",
     424        return new File(getSystemProperty("user.home")+"/Library/Caches",
    424425                Main.pref.getJOSMDirectoryBaseName());
    425426    }
     
    427428    @Override
    428429    public File getDefaultPrefDirectory() {
    429         return new File(System.getProperty("user.home")+"/Library/Preferences",
     430        return new File(getSystemProperty("user.home")+"/Library/Preferences",
    430431                Main.pref.getJOSMDirectoryBaseName());
    431432    }
     
    433434    @Override
    434435    public File getDefaultUserDataDirectory() {
    435         return new File(System.getProperty("user.home")+"/Library",
     436        return new File(getSystemProperty("user.home")+"/Library",
    436437                Main.pref.getJOSMDirectoryBaseName());
    437438    }
  • trunk/src/org/openstreetmap/josm/tools/PlatformHookUnixoid.java

    r13450 r13647  
    33
    44import static org.openstreetmap.josm.tools.I18n.tr;
     5import static org.openstreetmap.josm.tools.Utils.getSystemEnv;
     6import static org.openstreetmap.josm.tools.Utils.getSystemProperty;
    57
    68import java.awt.Desktop;
     
    4547    public void preStartupHook() {
    4648        // See #12022 - Disable GNOME ATK Java wrapper as it causes a lot of serious trouble
    47         if ("org.GNOME.Accessibility.AtkWrapper".equals(System.getProperty("assistive_technologies"))) {
     49        if ("org.GNOME.Accessibility.AtkWrapper".equals(getSystemProperty("assistive_technologies"))) {
    4850            System.clearProperty("assistive_technologies");
    4951        }
     
    154156     */
    155157    public String getJavaPackageDetails() {
    156         String home = System.getProperty("java.home");
     158        String home = getSystemProperty("java.home");
    157159        if (home.contains("java-8-openjdk") || home.contains("java-1.8.0-openjdk")) {
    158160            return getPackageDetails("openjdk-8-jre", "java-1_8_0-openjdk", "java-1.8.0-openjdk");
     
    202204
    203205    private String buildOSDescription() {
    204         String osName = System.getProperty("os.name");
     206        String osName = getSystemProperty("os.name");
    205207        if ("Linux".equalsIgnoreCase(osName)) {
    206208            try {
     
    339341    private static File getDotDirectory() {
    340342        String dirName = "." + Main.pref.getJOSMDirectoryBaseName().toLowerCase(Locale.ENGLISH);
    341         return new File(System.getProperty("user.home"), dirName);
     343        return new File(getSystemProperty("user.home"), dirName);
    342344    }
    343345
     
    357359            return new File(getDotDirectory(), "cache");
    358360        } else {
    359             String xdgCacheDir = System.getenv("XDG_CACHE_HOME");
     361            String xdgCacheDir = getSystemEnv("XDG_CACHE_HOME");
    360362            if (xdgCacheDir != null && !xdgCacheDir.isEmpty()) {
    361363                return new File(xdgCacheDir, Main.pref.getJOSMDirectoryBaseName());
    362364            } else {
    363                 return new File(System.getProperty("user.home") + File.separator +
     365                return new File(getSystemProperty("user.home") + File.separator +
    364366                        ".cache" + File.separator + Main.pref.getJOSMDirectoryBaseName());
    365367            }
     
    372374            return getDotDirectory();
    373375        } else {
    374             String xdgConfigDir = System.getenv("XDG_CONFIG_HOME");
     376            String xdgConfigDir = getSystemEnv("XDG_CONFIG_HOME");
    375377            if (xdgConfigDir != null && !xdgConfigDir.isEmpty()) {
    376378                return new File(xdgConfigDir, Main.pref.getJOSMDirectoryBaseName());
    377379            } else {
    378                 return new File(System.getProperty("user.home") + File.separator +
     380                return new File(getSystemProperty("user.home") + File.separator +
    379381                        ".config" + File.separator + Main.pref.getJOSMDirectoryBaseName());
    380382            }
     
    387389            return getDotDirectory();
    388390        } else {
    389             String xdgDataDir = System.getenv("XDG_DATA_HOME");
     391            String xdgDataDir = getSystemEnv("XDG_DATA_HOME");
    390392            if (xdgDataDir != null && !xdgDataDir.isEmpty()) {
    391393                return new File(xdgDataDir, Main.pref.getJOSMDirectoryBaseName());
    392394            } else {
    393                 return new File(System.getProperty("user.home") + File.separator +
     395                return new File(getSystemProperty("user.home") + File.separator +
    394396                        ".local" + File.separator + "share" + File.separator + Main.pref.getJOSMDirectoryBaseName());
    395397            }
  • trunk/src/org/openstreetmap/josm/tools/PlatformHookWindows.java

    r13487 r13647  
    2727import static java.awt.event.KeyEvent.VK_Z;
    2828import static org.openstreetmap.josm.tools.I18n.tr;
     29import static org.openstreetmap.josm.tools.Utils.getSystemEnv;
     30import static org.openstreetmap.josm.tools.Utils.getSystemProperty;
    2931import static org.openstreetmap.josm.tools.WinRegistry.HKEY_LOCAL_MACHINE;
    3032
     
    270272    @Override
    271273    public String getOSDescription() {
    272         return Utils.strip(System.getProperty("os.name")) + ' ' +
    273                 ((System.getenv("ProgramFiles(x86)") == null) ? "32" : "64") + "-Bit";
     274        return Utils.strip(getSystemProperty("os.name")) + ' ' +
     275                ((getSystemEnv("ProgramFiles(x86)") == null) ? "32" : "64") + "-Bit";
    274276    }
    275277
     
    316318            }
    317319            sb.append(" (").append(getCurrentBuild()).append(')');
    318         } catch (ReflectiveOperationException | JosmRuntimeException e) {
    319             Logging.error(e);
     320        } catch (ReflectiveOperationException | JosmRuntimeException | NoClassDefFoundError e) {
     321            Logging.log(Logging.LEVEL_ERROR, "Unable to get Windows build number", e);
     322            Logging.debug(e);
    320323        }
    321324        return sb.toString();
     
    473476    @Override
    474477    public File getDefaultCacheDirectory() {
    475         String p = System.getenv("LOCALAPPDATA");
     478        String p = getSystemEnv("LOCALAPPDATA");
    476479        if (p == null || p.isEmpty()) {
    477480            // Fallback for Windows OS earlier than Windows Vista, where the variable is not defined
    478             p = System.getenv("APPDATA");
     481            p = getSystemEnv("APPDATA");
    479482        }
    480483        return new File(new File(p, Main.pref.getJOSMDirectoryBaseName()), "cache");
     
    483486    @Override
    484487    public File getDefaultPrefDirectory() {
    485         return new File(System.getenv("APPDATA"), Main.pref.getJOSMDirectoryBaseName());
     488        return new File(getSystemEnv("APPDATA"), Main.pref.getJOSMDirectoryBaseName());
    486489    }
    487490
     
    524527            return;
    525528
    526         String javaLibPath = System.getProperty("java.home") + File.separator + "lib";
     529        String javaLibPath = getSystemProperty("java.home") + File.separator + "lib";
    527530        Path templateFile = FileSystems.getDefault().getPath(javaLibPath, templateFileName);
    528         if (!Files.isReadable(templateFile)) {
    529             Logging.warn("extended font config - unable to find font config template file {0}", templateFile.toString());
     531        String templatePath = templateFile.toString();
     532        if (templatePath.startsWith("null") || !Files.isReadable(templateFile)) {
     533            Logging.warn("extended font config - unable to find font config template file {0}", templatePath);
    530534            return;
    531535        }
     
    612616        // Use more low-level method to find the installed fonts.
    613617        List<String> fontsAvail = new ArrayList<>();
    614         Path fontPath = FileSystems.getDefault().getPath(System.getenv("SYSTEMROOT"), "Fonts");
     618        Path fontPath = FileSystems.getDefault().getPath(getSystemEnv("SYSTEMROOT"), "Fonts");
    615619        try (DirectoryStream<Path> ds = Files.newDirectoryStream(fontPath)) {
    616620            for (Path p : ds) {
  • trunk/src/org/openstreetmap/josm/tools/RightAndLefthandTraffic.java

    r13559 r13647  
    2525import org.openstreetmap.josm.data.osm.DataSet;
    2626import org.openstreetmap.josm.data.osm.DownloadPolicy;
    27 import org.openstreetmap.josm.data.osm.UploadPolicy;
    2827import org.openstreetmap.josm.data.osm.OsmPrimitive;
    2928import org.openstreetmap.josm.data.osm.Relation;
    3029import org.openstreetmap.josm.data.osm.RelationMember;
     30import org.openstreetmap.josm.data.osm.UploadPolicy;
    3131import org.openstreetmap.josm.data.osm.Way;
    3232import org.openstreetmap.josm.io.IllegalDataException;
     
    6969        if (optimizedWays.isEmpty()) {
    7070            optimizedWays = computeOptimizedBoundaries();
    71             saveOptimizedBoundaries(optimizedWays);
     71            try {
     72                saveOptimizedBoundaries(optimizedWays);
     73            } catch (IOException | SecurityException e) {
     74                Logging.log(Logging.LEVEL_ERROR, "Unable to save optimized boundaries", e);
     75            }
    7276        }
    7377        rlCache = new GeoPropertyIndex<>(new DefaultGeoProperty(optimizedWays), 24);
     
    154158    }
    155159
    156     private static void saveOptimizedBoundaries(Collection<Way> optimizedWays) {
     160    private static void saveOptimizedBoundaries(Collection<Way> optimizedWays) throws IOException {
    157161        DataSet ds = optimizedWays.iterator().next().getDataSet();
    158162        File file = new File(Config.getDirs().getCacheDirectory(true), "left-right-hand-traffic.osm");
     
    163167            w.writeContent(ds);
    164168            w.footer();
    165         } catch (IOException ex) {
    166             throw new JosmRuntimeException(ex);
    167169        }
    168170    }
     
    172174                Config.getDirs().getCacheDirectory(false).getPath(), "left-right-hand-traffic.osm"))) {
    173175           return OsmReader.parseDataSet(is, null).getWays();
    174         } catch (IllegalDataException | IOException | InvalidPathException ex) {
     176        } catch (IllegalDataException | IOException | InvalidPathException | SecurityException ex) {
    175177            Logging.trace(ex);
    176178            return Collections.emptyList();
  • trunk/src/org/openstreetmap/josm/tools/Utils.java

    r13597 r13647  
    887887     */
    888888    public static File getJosmTempDir() {
    889         String tmpDir = System.getProperty("java.io.tmpdir");
     889        String tmpDir = getSystemProperty("java.io.tmpdir");
    890890        if (tmpDir == null) {
    891891            return null;
     
    12681268
    12691269    /**
     1270     * Gets the value of the specified environment variable.
     1271     * An environment variable is a system-dependent external named value.
     1272     * @param name name the name of the environment variable
     1273     * @return the string value of the variable;
     1274     *         {@code null} if the variable is not defined in the system environment or if a security exception occurs.
     1275     * @see System#getenv(String)
     1276     * @since 13647
     1277     */
     1278    public static String getSystemEnv(String name) {
     1279        try {
     1280            return System.getenv(name);
     1281        } catch (SecurityException e) {
     1282            Logging.log(Logging.LEVEL_ERROR, "Unable to get system env", e);
     1283            return null;
     1284        }
     1285    }
     1286
     1287    /**
     1288     * Gets the system property indicated by the specified key.
     1289     * @param key the name of the system property.
     1290     * @return the string value of the system property;
     1291     *         {@code null} if there is no property with that key or if a security exception occurs.
     1292     * @see System#getProperty(String)
     1293     * @since 13647
     1294     */
     1295    public static String getSystemProperty(String key) {
     1296        try {
     1297            return System.getProperty(key);
     1298        } catch (SecurityException e) {
     1299            Logging.log(Logging.LEVEL_ERROR, "Unable to get system property", e);
     1300            return null;
     1301        }
     1302    }
     1303
     1304    /**
    12701305     * Updates a given system property.
    12711306     * @param key The property key
     
    12761311    public static String updateSystemProperty(String key, String value) {
    12771312        if (value != null) {
    1278             String old = System.setProperty(key, value);
    1279             if (Logging.isDebugEnabled() && !value.equals(old)) {
    1280                 if (!key.toLowerCase(Locale.ENGLISH).contains("password")) {
    1281                     Logging.debug("System property '" + key + "' set to '" + value + "'. Old value was '" + old + '\'');
    1282                 } else {
    1283                     Logging.debug("System property '" + key + "' changed.");
     1313            try {
     1314                String old = System.setProperty(key, value);
     1315                if (Logging.isDebugEnabled() && !value.equals(old)) {
     1316                    if (!key.toLowerCase(Locale.ENGLISH).contains("password")) {
     1317                        Logging.debug("System property '" + key + "' set to '" + value + "'. Old value was '" + old + '\'');
     1318                    } else {
     1319                        Logging.debug("System property '" + key + "' changed.");
     1320                    }
    12841321                }
    1285             }
    1286             return old;
     1322                return old;
     1323            } catch (SecurityException e) {
     1324                // Don't call Logging class, it may not be fully initialized yet
     1325                System.err.println("Unable to update system property: " + e.getMessage());
     1326            }
    12871327        }
    12881328        return null;
     
    15921632     */
    15931633    public static int getJavaVersion() {
    1594         String version = System.getProperty("java.version");
     1634        String version = getSystemProperty("java.version");
    15951635        if (version.startsWith("1.")) {
    15961636            version = version.substring(2);
     
    16131653     */
    16141654    public static int getJavaUpdate() {
    1615         String version = System.getProperty("java.version");
     1655        String version = getSystemProperty("java.version");
    16161656        if (version.startsWith("1.")) {
    16171657            version = version.substring(2);
     
    16431683     */
    16441684    public static int getJavaBuild() {
    1645         String version = System.getProperty("java.runtime.version");
     1685        String version = getSystemProperty("java.runtime.version");
    16461686        int bPos = version.indexOf('b');
    16471687        int pPos = version.indexOf('+');
     
    17571797        try {
    17581798            return new ScriptEngineManager(null).getEngineByName("JavaScript");
    1759         } catch (SecurityException e) {
    1760             Logging.error(e);
     1799        } catch (SecurityException | ExceptionInInitializerError e) {
     1800            Logging.log(Logging.LEVEL_ERROR, "Unable to get JavaScript engine", e);
    17611801            return null;
    17621802        }
     
    17891829                            FileTime jarTime = Files.readAttributes(jarFile, BasicFileAttributes.class).lastModifiedTime();
    17901830                            // Copy it to temp directory (hopefully free of exclamation mark) if needed (missing or older jar)
    1791                             Path jarCopy = Paths.get(System.getProperty("java.io.tmpdir")).resolve(filename);
     1831                            Path jarCopy = Paths.get(getSystemProperty("java.io.tmpdir")).resolve(filename);
    17921832                            if (!jarCopy.toFile().exists() ||
    17931833                                    Files.readAttributes(jarCopy, BasicFileAttributes.class).lastModifiedTime().compareTo(jarTime) < 0) {
  • trunk/src/org/openstreetmap/josm/tools/bugreport/ReportedException.java

    r12620 r13647  
    1010import java.util.Collections;
    1111import java.util.ConcurrentModificationException;
     12import java.util.HashMap;
    1213import java.util.IdentityHashMap;
    1314import java.util.Iterator;
     
    4041
    4142    /**
    42      * We capture all stack traces on exception creation. This allows us to trace synchonization problems better. We cannot be really sure what
    43      * happened but we at least see which threads
    44      */
    45     private final transient Map<Thread, StackTraceElement[]> allStackTraces;
     43     * We capture all stack traces on exception creation. This allows us to trace synchonization problems better.
     44     * We cannot be really sure what happened but we at least see which threads
     45     */
     46    private final transient Map<Thread, StackTraceElement[]> allStackTraces = new HashMap<>();
    4647    private final LinkedList<Section> sections = new LinkedList<>();
    4748    private final transient Thread caughtOnThread;
     
    5556        super(exception);
    5657
    57         allStackTraces = Thread.getAllStackTraces();
     58        try {
     59            allStackTraces.putAll(Thread.getAllStackTraces());
     60        } catch (SecurityException e) {
     61            Logging.log(Logging.LEVEL_ERROR, "Unable to get thread stack traces", e);
     62        }
    5863        this.caughtOnThread = caughtOnThread;
    5964    }
Note: See TracChangeset for help on using the changeset viewer.