Changeset 10899 in josm for trunk/src/org/openstreetmap


Ignore:
Timestamp:
2016-08-25T23:21:10+02:00 (8 years ago)
Author:
Don-vip
Message:

fix #13318 - Clean up program startup (parameters, logging) - patch by michael2402 - gsoc-core

Location:
trunk/src/org/openstreetmap/josm
Files:
2 added
3 edited

Legend:

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

    r10876 r10899  
    3535import java.util.concurrent.Executors;
    3636import java.util.concurrent.Future;
    37 import java.util.logging.Handler;
    38 import java.util.logging.Level;
    39 import java.util.logging.LogRecord;
    40 import java.util.logging.Logger;
    4137
    4238import javax.swing.Action;
     
    7470import org.openstreetmap.josm.data.validation.OsmValidator;
    7571import org.openstreetmap.josm.gui.GettingStarted;
    76 import org.openstreetmap.josm.gui.MainApplication.Option;
    7772import org.openstreetmap.josm.gui.MainFrame;
    7873import org.openstreetmap.josm.gui.MainMenu;
     
    8075import org.openstreetmap.josm.gui.MapFrame;
    8176import org.openstreetmap.josm.gui.MapFrameListener;
     77import org.openstreetmap.josm.gui.ProgramArguments;
     78import org.openstreetmap.josm.gui.ProgramArguments.Option;
    8279import org.openstreetmap.josm.gui.io.SaveLayersDialog;
    8380import org.openstreetmap.josm.gui.layer.AbstractModifiableLayer;
     
    104101import org.openstreetmap.josm.tools.I18n;
    105102import org.openstreetmap.josm.tools.ImageProvider;
     103import org.openstreetmap.josm.tools.Logging;
    106104import org.openstreetmap.josm.tools.OpenBrowser;
    107105import org.openstreetmap.josm.tools.OsmUrlToBounds;
     
    219217    protected static final Map<String, Throwable> NETWORK_ERRORS = new HashMap<>();
    220218
    221     // First lines of last 5 error and warning messages, used for bug reports
    222     private static final List<String> ERRORS_AND_WARNINGS = Collections.<String>synchronizedList(new ArrayList<String>());
    223 
    224219    private static final Set<OnlineResource> OFFLINE_RESOURCES = EnumSet.noneOf(OnlineResource.class);
    225220
     
    227222     * Logging level (5 = trace, 4 = debug, 3 = info, 2 = warn, 1 = error, 0 = none).
    228223     * @since 6248
    229      */
     224     * @deprecated Use {@link Logging} class.
     225     */
     226    @Deprecated
    230227    public static int logLevel = 3;
    231228
     
    235232     */
    236233    protected static final MainPanel mainPanel = new MainPanel(getLayerManager());
    237 
    238     private static void rememberWarnErrorMsg(String msg) {
    239         // Only remember first line of message
    240         int idx = msg.indexOf('\n');
    241         if (idx > 0) {
    242             ERRORS_AND_WARNINGS.add(msg.substring(0, idx));
    243         } else {
    244             ERRORS_AND_WARNINGS.add(msg);
    245         }
    246         // Only keep 10 lines to avoid memory leak
    247         while (ERRORS_AND_WARNINGS.size() > 10) {
    248             ERRORS_AND_WARNINGS.remove(0);
    249         }
    250     }
    251234
    252235    /**
     
    256239     */
    257240    public static final Collection<String> getLastErrorAndWarnings() {
    258         return Collections.unmodifiableList(ERRORS_AND_WARNINGS);
     241        return Logging.getLastErrorAndWarnings();
    259242    }
    260243
     
    264247     */
    265248    public static void clearLastErrorAndWarnings() {
    266         ERRORS_AND_WARNINGS.clear();
     249        Logging.clearLastErrorAndWarnings();
    267250    }
    268251
     
    273256     */
    274257    public static void error(String msg) {
    275         if (logLevel < 1)
    276             return;
    277         if (msg != null && !msg.isEmpty()) {
    278             System.err.println(tr("ERROR: {0}", msg));
    279             rememberWarnErrorMsg("E: "+msg);
    280         }
     258        Logging.error(msg);
    281259    }
    282260
     
    286264     */
    287265    public static void warn(String msg) {
    288         if (logLevel < 2)
    289             return;
    290         if (msg != null && !msg.isEmpty()) {
    291             System.err.println(tr("WARNING: {0}", msg));
    292             rememberWarnErrorMsg("W: "+msg);
    293         }
     266        Logging.warn(msg);
    294267    }
    295268
     
    299272     */
    300273    public static void info(String msg) {
    301         if (logLevel < 3)
    302             return;
    303         if (msg != null && !msg.isEmpty()) {
    304             System.out.println(tr("INFO: {0}", msg));
    305         }
     274        Logging.info(msg);
    306275    }
    307276
     
    311280     */
    312281    public static void debug(String msg) {
    313         if (logLevel < 4)
    314             return;
    315         if (msg != null && !msg.isEmpty()) {
    316             System.out.println(tr("DEBUG: {0}", msg));
    317         }
     282        Logging.debug(msg);
    318283    }
    319284
     
    323288     */
    324289    public static void trace(String msg) {
    325         if (logLevel < 5)
    326             return;
    327         if (msg != null && !msg.isEmpty()) {
    328             System.out.print("TRACE: ");
    329             System.out.println(msg);
    330         }
     290        Logging.trace(msg);
    331291    }
    332292
     
    338298     */
    339299    public static boolean isDebugEnabled() {
    340         return logLevel >= 4;
     300        return Logging.isLoggingEnabled(Logging.LEVEL_DEBUG);
    341301    }
    342302
     
    348308     */
    349309    public static boolean isTraceEnabled() {
    350         return logLevel >= 5;
     310        return Logging.isLoggingEnabled(Logging.LEVEL_TRACE);
    351311    }
    352312
     
    359319     */
    360320    public static void error(String msg, Object... objects) {
    361         error(MessageFormat.format(msg, objects));
     321        Logging.error(msg, objects);
    362322    }
    363323
     
    369329     */
    370330    public static void warn(String msg, Object... objects) {
    371         warn(MessageFormat.format(msg, objects));
     331        Logging.warn(msg, objects);
    372332    }
    373333
     
    379339     */
    380340    public static void info(String msg, Object... objects) {
    381         info(MessageFormat.format(msg, objects));
     341        Logging.info(msg, objects);
    382342    }
    383343
     
    389349     */
    390350    public static void debug(String msg, Object... objects) {
    391         debug(MessageFormat.format(msg, objects));
     351        Logging.debug(msg, objects);
    392352    }
    393353
     
    399359     */
    400360    public static void trace(String msg, Object... objects) {
    401         trace(MessageFormat.format(msg, objects));
     361        Logging.trace(msg, objects);
    402362    }
    403363
     
    408368     */
    409369    public static void error(Throwable t) {
    410         error(t, true);
     370        Logging.logWithStackTrace(Logging.LEVEL_ERROR, t);
    411371    }
    412372
     
    417377     */
    418378    public static void warn(Throwable t) {
    419         warn(t, true);
     379        Logging.logWithStackTrace(Logging.LEVEL_WARN, t);
    420380    }
    421381
     
    426386     */
    427387    public static void debug(Throwable t) {
    428         debug(getErrorMessage(t));
     388        Logging.log(Logging.LEVEL_DEBUG, t);
    429389    }
    430390
     
    435395     */
    436396    public static void trace(Throwable t) {
    437         trace(getErrorMessage(t));
     397        Logging.log(Logging.LEVEL_TRACE, t);
    438398    }
    439399
     
    445405     */
    446406    public static void error(Throwable t, boolean stackTrace) {
    447         error(getErrorMessage(t));
    448407        if (stackTrace) {
    449             t.printStackTrace();
     408            Logging.log(Logging.LEVEL_ERROR, t);
     409        } else {
     410            Logging.logWithStackTrace(Logging.LEVEL_ERROR, t);
    450411        }
    451412    }
     
    458419     */
    459420    public static void error(Throwable t, String message) {
    460         warn(message + ' ' + getErrorMessage(t));
     421        Logging.log(Logging.LEVEL_ERROR, message, t);
    461422    }
    462423
     
    468429     */
    469430    public static void warn(Throwable t, boolean stackTrace) {
    470         warn(getErrorMessage(t));
    471431        if (stackTrace) {
    472             t.printStackTrace();
     432            Logging.log(Logging.LEVEL_WARN, t);
     433        } else {
     434            Logging.logWithStackTrace(Logging.LEVEL_WARN, t);
    473435        }
    474436    }
     
    481443     */
    482444    public static void warn(Throwable t, String message) {
    483         warn(message + ' ' + getErrorMessage(t));
     445        Logging.log(Logging.LEVEL_WARN, message, t);
    484446    }
    485447
     
    493455        if (t == null) {
    494456            return null;
    495         }
    496         StringBuilder sb = new StringBuilder(t.getClass().getName());
    497         String msg = t.getMessage();
    498         if (msg != null) {
    499             sb.append(": ").append(msg.trim());
    500         }
    501         Throwable cause = t.getCause();
    502         if (cause != null && !cause.equals(t)) {
    503             sb.append(". ").append(tr("Cause: ")).append(getErrorMessage(cause));
    504         }
    505         return sb.toString();
     457        } else {
     458            return Logging.getErrorMessage(t);
     459        }
    506460    }
    507461
     
    571525        fileWatcher.start();
    572526
    573         new InitializationTask(tr("Executing platform startup hook")) {
    574             @Override
    575             public void initialize() {
    576                 platform.startupHook();
    577             }
    578         }.call();
    579 
    580         new InitializationTask(tr("Building main menu")) {
    581 
    582             @Override
    583             public void initialize() {
    584                 initializeMainWindow();
    585             }
    586         }.call();
     527        new InitializationTask(tr("Executing platform startup hook"), platform::startupHook).call();
     528
     529        new InitializationTask(tr("Building main menu"), this::initializeMainWindow).call();
    587530
    588531        undoRedo.addCommandQueueListener(redoUndoListener);
     
    597540        List<Callable<Void>> tasks = new ArrayList<>();
    598541
    599         tasks.add(new InitializationTask(tr("Initializing OSM API")) {
    600 
    601             @Override
    602             public void initialize() {
     542        tasks.add(new InitializationTask(tr("Initializing OSM API"), () -> {
    603543                // We try to establish an API connection early, so that any API
    604544                // capabilities are already known to the editor instance. However
     
    609549                    Main.warn(getErrorMessage(Utils.getRootCause(e)));
    610550                }
    611             }
    612         });
    613 
    614         tasks.add(new InitializationTask(tr("Initializing validator")) {
    615 
    616             @Override
    617             public void initialize() {
    618                 OsmValidator.initialize();
    619             }
    620         });
    621 
    622         tasks.add(new InitializationTask(tr("Initializing presets")) {
    623 
    624             @Override
    625             public void initialize() {
    626                 TaggingPresets.initialize();
    627             }
    628         });
    629 
    630         tasks.add(new InitializationTask(tr("Initializing map styles")) {
    631 
    632             @Override
    633             public void initialize() {
    634                 MapPaintPreference.initialize();
    635             }
    636         });
    637 
    638         tasks.add(new InitializationTask(tr("Loading imagery preferences")) {
    639 
    640             @Override
    641             public void initialize() {
    642                 ImageryPreference.initialize();
    643             }
    644         });
     551            }));
     552
     553        tasks.add(new InitializationTask(tr("Initializing validator"), OsmValidator::initialize));
     554
     555        tasks.add(new InitializationTask(tr("Initializing presets"), TaggingPresets::initialize));
     556
     557        tasks.add(new InitializationTask(tr("Initializing map styles"), MapPaintPreference::initialize));
     558
     559        tasks.add(new InitializationTask(tr("Loading imagery preferences"), ImageryPreference::initialize));
    645560
    646561        try {
    647             final ExecutorService service = Executors.newFixedThreadPool(
     562            ExecutorService service = Executors.newFixedThreadPool(
    648563                    Runtime.getRuntime().availableProcessors(), Utils.newThreadFactory("main-init-%d", Thread.NORM_PRIORITY));
    649564            for (Future<Void> i : service.invokeAll(tasks)) {
     
    658573        FeatureAdapter.registerBrowserAdapter(OpenBrowser::displayUrl);
    659574        FeatureAdapter.registerTranslationAdapter(I18n.getTranslationAdapter());
    660         FeatureAdapter.registerLoggingAdapter(name -> {
    661                 Logger logger = Logger.getAnonymousLogger();
    662                 logger.setUseParentHandlers(false);
    663                 logger.setLevel(Level.ALL);
    664                 if (logger.getHandlers().length == 0) {
    665                     logger.addHandler(new Handler() {
    666                         @Override
    667                         public void publish(LogRecord record) {
    668                             String msg = MessageFormat.format(record.getMessage(), record.getParameters());
    669                             if (record.getLevel().intValue() >= Level.SEVERE.intValue()) {
    670                                 Main.error(msg);
    671                             } else if (record.getLevel().intValue() >= Level.WARNING.intValue()) {
    672                                 Main.warn(msg);
    673                             } else if (record.getLevel().intValue() >= Level.INFO.intValue()) {
    674                                 Main.info(msg);
    675                             } else if (record.getLevel().intValue() >= Level.FINE.intValue()) {
    676                                 Main.debug(msg);
    677                             } else {
    678                                 Main.trace(msg);
    679                             }
    680                         }
    681 
    682                         @Override
    683                         public void flush() {
    684                             // Do nothing
    685                         }
    686 
    687                         @Override
    688                         public void close() {
    689                             // Do nothing
    690                         }
    691                     });
    692                 }
    693                 return logger;
    694             });
    695 
    696         new InitializationTask(tr("Updating user interface")) {
    697 
    698             @Override
    699             public void initialize() {
    700                 toolbar.refreshToolbarControl();
    701                 toolbar.control.updateUI();
    702                 contentPanePrivate.updateUI();
    703             }
    704         }.call();
     575        FeatureAdapter.registerLoggingAdapter(name -> Logging.getLogger());
     576
     577        new InitializationTask(tr("Updating user interface"), () -> {
     578            toolbar.refreshToolbarControl();
     579            toolbar.control.updateUI();
     580            contentPanePrivate.updateUI();
     581        }).call();
    705582    }
    706583
     
    713590    }
    714591
    715     private abstract static class InitializationTask implements Callable<Void> {
     592    private static class InitializationTask implements Callable<Void> {
    716593
    717594        private final String name;
    718 
    719         protected InitializationTask(String name) {
     595        private Runnable task;
     596
     597        protected InitializationTask(String name, Runnable task) {
    720598            this.name = name;
    721         }
    722 
    723         public abstract void initialize();
     599            this.task = task;
     600        }
    724601
    725602        @Override
     
    729606                status = initListener.updateStatus(name);
    730607            }
    731             initialize();
     608            task.run();
    732609            if (initListener != null) {
    733610                initListener.finish(status);
     
    951828     * @param args The parsed argument list.
    952829     */
    953     public static void preConstructorInit(Map<Option, Collection<String>> args) {
     830    public static void preConstructorInit(ProgramArguments args) {
    954831        ProjectionPreference.setProjection();
    955832
     
    1018895    }
    1019896
    1020     protected static void postConstructorProcessCmdLine(Map<Option, Collection<String>> args) {
    1021         if (args.containsKey(Option.DOWNLOAD)) {
    1022             List<File> fileList = new ArrayList<>();
    1023             for (String s : args.get(Option.DOWNLOAD)) {
    1024                 DownloadParamType.paramType(s).download(s, fileList);
    1025             }
    1026             if (!fileList.isEmpty()) {
    1027                 OpenFileAction.openFiles(fileList, true);
    1028             }
    1029         }
    1030         if (args.containsKey(Option.DOWNLOADGPS)) {
    1031             for (String s : args.get(Option.DOWNLOADGPS)) {
    1032                 DownloadParamType.paramType(s).downloadGps(s);
    1033             }
    1034         }
    1035         if (args.containsKey(Option.SELECTION)) {
    1036             for (String s : args.get(Option.SELECTION)) {
    1037                 SearchAction.search(s, SearchAction.SearchMode.add);
    1038             }
     897    protected static void postConstructorProcessCmdLine(ProgramArguments args) {
     898        List<File> fileList = new ArrayList<>();
     899        for (String s : args.get(Option.DOWNLOAD)) {
     900            DownloadParamType.paramType(s).download(s, fileList);
     901        }
     902        if (!fileList.isEmpty()) {
     903            OpenFileAction.openFiles(fileList, true);
     904        }
     905        for (String s : args.get(Option.DOWNLOADGPS)) {
     906            DownloadParamType.paramType(s).downloadGps(s);
     907        }
     908        for (String s : args.get(Option.SELECTION)) {
     909            SearchAction.search(s, SearchAction.SearchMode.add);
    1039910        }
    1040911    }
     
    14891360            if (!windowSwitchListeners.isEmpty()) {
    14901361                for (Window w : Window.getWindows()) {
    1491                     if (w.isShowing()) {
    1492                         if (!Arrays.asList(w.getWindowListeners()).contains(getInstance())) {
    1493                             w.addWindowListener(getInstance());
    1494                         }
     1362                    if (w.isShowing() && !Arrays.asList(w.getWindowListeners()).contains(getInstance())) {
     1363                        w.addWindowListener(getInstance());
    14951364                    }
    14961365                }
  • trunk/src/org/openstreetmap/josm/gui/MainApplication.java

    r10876 r10899  
    2525import java.security.Policy;
    2626import java.security.cert.CertificateException;
    27 import java.util.ArrayList;
    2827import java.util.Arrays;
    2928import java.util.Collection;
    30 import java.util.EnumMap;
    3129import java.util.List;
    3230import java.util.Locale;
    33 import java.util.Map;
     31import java.util.Optional;
    3432import java.util.Set;
    3533import java.util.TreeSet;
     34import java.util.logging.Level;
    3635
    3736import javax.swing.JOptionPane;
     
    4645import org.openstreetmap.josm.data.CustomConfigurator;
    4746import org.openstreetmap.josm.data.Version;
     47import org.openstreetmap.josm.gui.ProgramArguments.Option;
    4848import org.openstreetmap.josm.gui.SplashScreen.SplashProgressMonitor;
    4949import org.openstreetmap.josm.gui.download.DownloadDialog;
     
    6363import org.openstreetmap.josm.tools.HttpClient;
    6464import org.openstreetmap.josm.tools.I18n;
     65import org.openstreetmap.josm.tools.Logging;
    6566import org.openstreetmap.josm.tools.OsmUrlToBounds;
    6667import org.openstreetmap.josm.tools.PlatformHookWindows;
    6768import org.openstreetmap.josm.tools.Utils;
    6869import org.openstreetmap.josm.tools.WindowGeometry;
     70import org.openstreetmap.josm.tools.bugreport.BugReport;
    6971import org.openstreetmap.josm.tools.bugreport.BugReportExceptionHandler;
    70 
    71 import gnu.getopt.Getopt;
    72 import gnu.getopt.LongOpt;
    7372
    7473/**
     
    171170
    172171    /**
    173      * JOSM command line options.
    174      * @see <a href="https://josm.openstreetmap.de/wiki/Help/CommandLineOptions">Help/CommandLineOptions</a>
    175      * @since 5279
    176      */
    177     public enum Option {
    178         /** --help|-h                                  Show this help */
    179         HELP(false),
    180         /** --version                                  Displays the JOSM version and exits */
    181         VERSION(false),
    182         /** --debug                                    Print debugging messages to console */
    183         DEBUG(false),
    184         /** --trace                                    Print detailed debugging messages to console */
    185         TRACE(false),
    186         /** --language=&lt;language&gt;                Set the language */
    187         LANGUAGE(true),
    188         /** --reset-preferences                        Reset the preferences to default */
    189         RESET_PREFERENCES(false),
    190         /** --load-preferences=&lt;url-to-xml&gt;      Changes preferences according to the XML file */
    191         LOAD_PREFERENCES(true),
    192         /** --set=&lt;key&gt;=&lt;value&gt;            Set preference key to value */
    193         SET(true),
    194         /** --geometry=widthxheight(+|-)x(+|-)y        Standard unix geometry argument */
    195         GEOMETRY(true),
    196         /** --no-maximize                              Do not launch in maximized mode */
    197         NO_MAXIMIZE(false),
    198         /** --maximize                                 Launch in maximized mode */
    199         MAXIMIZE(false),
    200         /** --download=minlat,minlon,maxlat,maxlon     Download the bounding box <br>
    201          *  --download=&lt;URL&gt;                     Download the location at the URL (with lat=x&amp;lon=y&amp;zoom=z) <br>
    202          *  --download=&lt;filename&gt;                Open a file (any file type that can be opened with File/Open) */
    203         DOWNLOAD(true),
    204         /** --downloadgps=minlat,minlon,maxlat,maxlon  Download the bounding box as raw GPS <br>
    205          *  --downloadgps=&lt;URL&gt;                  Download the location at the URL (with lat=x&amp;lon=y&amp;zoom=z) as raw GPS */
    206         DOWNLOADGPS(true),
    207         /** --selection=&lt;searchstring&gt;           Select with the given search */
    208         SELECTION(true),
    209         /** --offline=&lt;osm_api|josm_website|all&gt; Disable access to the given resource(s), delimited by comma */
    210         OFFLINE(true),
    211         /** --skip-plugins */
    212         SKIP_PLUGINS(false);
    213 
    214         private final String name;
    215         private final boolean requiresArg;
    216 
    217         Option(boolean requiresArgument) {
    218             this.name = name().toLowerCase(Locale.ENGLISH).replace('_', '-');
    219             this.requiresArg = requiresArgument;
    220         }
    221 
    222         /**
    223          * Replies the option name
    224          * @return The option name, in lowercase
    225          */
    226         public String getName() {
    227             return name;
    228         }
    229 
    230         /**
    231          * Determines if this option requires an argument.
    232          * @return {@code true} if this option requires an argument, {@code false} otherwise
    233          */
    234         public boolean requiresArgument() {
    235             return requiresArg;
    236         }
    237     }
    238 
    239     /**
    240      * Builds the command-line argument map.
    241      * @param args command-line arguments array
    242      * @return command-line argument map
    243      */
    244     public static Map<Option, Collection<String>> buildCommandLineArgumentMap(String ... args) {
    245 
    246         List<LongOpt> los = new ArrayList<>();
    247         for (Option o : Option.values()) {
    248             los.add(new LongOpt(o.getName(), o.requiresArgument() ? LongOpt.REQUIRED_ARGUMENT : LongOpt.NO_ARGUMENT, null, 0));
    249         }
    250 
    251         Getopt g = new Getopt("JOSM", args, "hv", los.toArray(new LongOpt[los.size()]));
    252 
    253         Map<Option, Collection<String>> argMap = new EnumMap<>(Option.class);
    254 
    255         int c;
    256         while ((c = g.getopt()) != -1) {
    257             Option opt;
    258             switch (c) {
    259                 case 'h':
    260                     opt = Option.HELP;
    261                     break;
    262                 case 'v':
    263                     opt = Option.VERSION;
    264                     break;
    265                 case 0:
    266                     opt = Option.values()[g.getLongind()];
    267                     break;
    268                 default:
    269                     opt = null;
    270             }
    271             if (opt != null) {
    272                 Collection<String> values = argMap.get(opt);
    273                 if (values == null) {
    274                     values = new ArrayList<>();
    275                     argMap.put(opt, values);
    276                 }
    277                 values.add(g.getOptarg());
    278             } else
    279                 throw new IllegalArgumentException("Invalid option: "+c);
    280         }
    281         // positional arguments are a shortcut for the --download ... option
    282         for (int i = g.getOptind(); i < args.length; ++i) {
    283             Collection<String> values = argMap.get(Option.DOWNLOAD);
    284             if (values == null) {
    285                 values = new ArrayList<>();
    286                 argMap.put(Option.DOWNLOAD, values);
    287             }
    288             values.add(args[i]);
    289         }
    290 
    291         return argMap;
    292     }
    293 
    294     /**
    295172     * Main application Startup
    296173     * @param argArray Command-line arguments
     
    300177
    301178        // construct argument table
    302         Map<Option, Collection<String>> args = null;
     179        ProgramArguments args = null;
    303180        try {
    304             args = buildCommandLineArgumentMap(argArray);
     181            args = new ProgramArguments(argArray);
    305182        } catch (IllegalArgumentException e) {
    306183            System.exit(1);
     
    308185        }
    309186
    310         final boolean languageGiven = args.containsKey(Option.LANGUAGE);
    311 
    312         if (languageGiven) {
    313             I18n.set(args.get(Option.LANGUAGE).iterator().next());
    314         }
    315 
    316         if (args.containsKey(Option.TRACE)) {
    317             // Enable JOSM debug level
    318             logLevel = 5;
    319             // Enable debug in OAuth signpost via system preference, but only at trace level
    320             Utils.updateSystemProperty("debug", "true");
    321             Main.info(tr("Enabled detailed debug level (trace)"));
    322         } else if (args.containsKey(Option.DEBUG)) {
    323             // Enable JOSM debug level
    324             logLevel = 4;
    325             Main.info(tr("Printing debugging messages to console"));
    326         }
     187        Level logLevel = args.getLogLevel();
     188        Logging.setLogLevel(logLevel);
     189        Main.info(tr("Log level is at ", logLevel));
     190
     191        Optional<String> language = args.getSingle(Option.LANGUAGE);
     192        I18n.set(language.orElse(null));
    327193
    328194        Policy.setPolicy(new Policy() {
     
    350216        Main.COMMAND_LINE_ARGS.addAll(Arrays.asList(argArray));
    351217
    352         if (args.containsKey(Option.VERSION)) {
     218        if (args.showVersion()) {
    353219            System.out.println(Version.getInstance().getAgentString());
    354220            System.exit(0);
    355         }
    356 
    357         boolean skipLoadingPlugins = false;
    358         if (args.containsKey(Option.SKIP_PLUGINS)) {
    359             skipLoadingPlugins = true;
    360             Main.info(tr("Plugin loading skipped"));
    361         }
    362 
    363         Main.pref.init(args.containsKey(Option.RESET_PREFERENCES));
    364 
    365         if (args.containsKey(Option.SET)) {
    366             for (String i : args.get(Option.SET)) {
    367                 String[] kv = i.split("=", 2);
    368                 Main.pref.put(kv[0], "null".equals(kv[1]) ? null : kv[1]);
    369             }
    370         }
    371 
    372         if (!languageGiven) {
    373             I18n.set(Main.pref.get("language", null));
    374         }
    375         Main.pref.updateSystemProperties();
    376 
    377         checkIPv6();
    378 
    379         // asking for help? show help and exit
    380         if (args.containsKey(Option.HELP)) {
     221        } else if (args.showHelp()) {
    381222            showHelp();
    382223            System.exit(0);
    383224        }
    384225
     226        boolean skipLoadingPlugins = args.hasOption(Option.SKIP_PLUGINS);
     227        if (skipLoadingPlugins) {
     228            Main.info(tr("Plugin loading skipped"));
     229        }
     230
     231        if (Logging.isLoggingEnabled(Logging.LEVEL_TRACE)) {
     232            // Enable debug in OAuth signpost via system preference, but only at trace level
     233            Utils.updateSystemProperty("debug", "true");
     234            Main.info(tr("Enabled detailed debug level (trace)"));
     235        }
     236
     237        Main.pref.init(args.hasOption(Option.RESET_PREFERENCES));
     238
     239        args.getPreferencesToSet().forEach(Main.pref::put);
     240
     241        if (!language.isPresent()) {
     242            I18n.set(Main.pref.get("language", null));
     243        }
     244        Main.pref.updateSystemProperties();
     245
     246        checkIPv6();
     247
     248        // asking for help? show help and exit
     249        if (args.hasOption(Option.HELP)) {
     250            showHelp();
     251            System.exit(0);
     252        }
     253
    385254        processOffline(args);
    386255
     
    392261
    393262        WindowGeometry geometry = WindowGeometry.mainWindow("gui.geometry",
    394                 args.containsKey(Option.GEOMETRY) ? args.get(Option.GEOMETRY).iterator().next() : null,
    395                 !args.containsKey(Option.NO_MAXIMIZE) && Main.pref.getBoolean("gui.maximized", false));
     263                args.getSingle(Option.GEOMETRY).orElse(null),
     264                !args.hasOption(Option.NO_MAXIMIZE) && Main.pref.getBoolean("gui.maximized", false));
    396265        final MainFrame mainFrame = new MainFrame(contentPanePrivate, mainPanel, geometry);
    397266        Main.parent = mainFrame;
    398267
    399         if (args.containsKey(Option.LOAD_PREFERENCES)) {
     268        if (args.hasOption(Option.LOAD_PREFERENCES)) {
    400269            CustomConfigurator.XMLCommandProcessor config = new CustomConfigurator.XMLCommandProcessor(Main.pref);
    401270            for (String i : args.get(Option.LOAD_PREFERENCES)) {
     
    404273                    config.openAndReadXML(is);
    405274                } catch (IOException ex) {
    406                     throw new RuntimeException(ex);
     275                    throw BugReport.intercept(ex).put("file", i);
    407276                }
    408277            }
     
    467336
    468337        boolean maximized = Main.pref.getBoolean("gui.maximized", false);
    469         if ((!args.containsKey(Option.NO_MAXIMIZE) && maximized) || args.containsKey(Option.MAXIMIZE)) {
     338        if ((!args.hasOption(Option.NO_MAXIMIZE) && maximized) || args.hasOption(Option.MAXIMIZE)) {
    470339            mainFrame.setMaximized(true);
    471340        }
     
    525394    }
    526395
    527     private static void processOffline(Map<Option, Collection<String>> args) {
    528         if (args.containsKey(Option.OFFLINE)) {
    529             for (String s : args.get(Option.OFFLINE).iterator().next().split(",")) {
     396    private static void processOffline(ProgramArguments args) {
     397        for (String offlineNames : args.get(Option.OFFLINE)) {
     398            for (String s : offlineNames.split(",")) {
    530399                try {
    531400                    Main.setOffline(OnlineResource.valueOf(s.toUpperCase(Locale.ENGLISH)));
     
    537406                }
    538407            }
    539             Set<OnlineResource> offline = Main.getOfflineResources();
    540             if (!offline.isEmpty()) {
    541                 Main.warn(trn("JOSM is running in offline mode. This resource will not be available: {0}",
    542                         "JOSM is running in offline mode. These resources will not be available: {0}",
    543                         offline.size(), offline.size() == 1 ? offline.iterator().next() : Arrays.toString(offline.toArray())));
    544             }
     408        }
     409        Set<OnlineResource> offline = Main.getOfflineResources();
     410        if (!offline.isEmpty()) {
     411            Main.warn(trn("JOSM is running in offline mode. This resource will not be available: {0}",
     412                    "JOSM is running in offline mode. These resources will not be available: {0}",
     413                    offline.size(), offline.size() == 1 ? offline.iterator().next() : Arrays.toString(offline.toArray())));
    545414        }
    546415    }
     
    597466    private static class GuiFinalizationWorker implements Runnable {
    598467
    599         private final Map<Option, Collection<String>> args;
     468        private final ProgramArguments args;
    600469        private final DefaultProxySelector proxySelector;
    601470
    602         GuiFinalizationWorker(Map<Option, Collection<String>> args, DefaultProxySelector proxySelector) {
     471        GuiFinalizationWorker(ProgramArguments args, DefaultProxySelector proxySelector) {
    603472            this.args = args;
    604473            this.proxySelector = proxySelector;
  • trunk/src/org/openstreetmap/josm/tools/bugreport/BugReport.java

    r10886 r10899  
    66import java.io.StringWriter;
    77import java.util.concurrent.CopyOnWriteArrayList;
     8import java.util.function.Predicate;
    89
    910import org.openstreetmap.josm.actions.ShowStatusReportAction;
     
    185186     */
    186187    public static String getCallingMethod(int offset) {
     188        String className = BugReport.class.getName();
     189        String methodName = "getCallingMethod";
     190        StackTraceElement found = getCallingMethod(offset, className, methodName::equals);
     191        if (found != null) {
     192            return found.getClassName().replaceFirst(".*\\.", "") + '#' + found.getMethodName();
     193        } else {
     194            return "?";
     195        }
     196    }
     197
     198    /**
     199     * Find the method that called the given method on the current stack trace.
     200     * @param offset
     201     *           How many methods to look back in the stack trace. 1 gives the method calling this method, 0 gives you getCallingMethod().
     202     * @param className The name of the class to search for
     203     * @param methodName The name of the method to search for
     204     * @return The class and method name or null if it is unknown.
     205     */
     206    public static StackTraceElement getCallingMethod(int offset, String className, Predicate<String> methodName) {
    187207        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
    188         String className = BugReport.class.getName();
    189208        for (int i = 0; i < stackTrace.length - offset; i++) {
    190209            StackTraceElement element = stackTrace[i];
    191             if (className.equals(element.getClassName()) && "getCallingMethod".equals(element.getMethodName())) {
     210            if (className.equals(element.getClassName()) && methodName.test(element.getMethodName())) {
    192211                StackTraceElement toReturn = stackTrace[i + offset];
    193                 return toReturn.getClassName().replaceFirst(".*\\.", "") + '#' + toReturn.getMethodName();
     212                return toReturn;
    194213            }
    195214        }
    196         return "?";
     215        return null;
    197216    }
    198217
Note: See TracChangeset for help on using the changeset viewer.