Changeset 14052 in josm for trunk/src


Ignore:
Timestamp:
2018-07-26T22:01:31+02:00 (6 years ago)
Author:
Don-vip
Message:

see #16010 - use JMockit to enable more extensive test coverage (patch by ris, modified)

see https://github.com/openstreetmap/josm/pull/24/commits for details

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

Legend:

Unmodified
Added
Removed
  • trunk/src/org/openstreetmap/josm/data/preferences/JosmBaseDirectories.java

    r13776 r14052  
    155155        return cacheDir;
    156156    }
     157
     158    /**
     159     * Clears any previously calculated values used for {@link #getPreferencesDirectory(boolean)},
     160     * {@link #getCacheDirectory(boolean)} or {@link #getUserDataDirectory(boolean)}. Useful for tests.
     161     * @since 14052
     162     */
     163    public void clearMemos() {
     164        this.preferencesDir = null;
     165        this.cacheDir = null;
     166        this.userdataDir = null;
     167    }
    157168}
  • trunk/src/org/openstreetmap/josm/gui/ConditionalOptionPaneUtil.java

    r12846 r14052  
    265265     *
    266266     */
    267     static class MessagePanel extends JPanel {
     267    public static class MessagePanel extends JPanel {
    268268        private final JRadioButton cbShowPermanentDialog = new JRadioButton(NotShowAgain.PERMANENT.getLabel());
    269269        private final JRadioButton cbShowSessionDialog = new JRadioButton(NotShowAgain.SESSION.getLabel());
  • trunk/src/org/openstreetmap/josm/gui/MainApplication.java

    r13963 r14052  
    488488    @Override
    489489    protected void shutdown() {
    490         if (!GraphicsEnvironment.isHeadless()) {
    491             try {
    492                 worker.shutdown();
    493             } catch (SecurityException e) {
    494                 Logging.log(Logging.LEVEL_ERROR, "Unable to shutdown worker", e);
    495             }
    496             JCSCacheManager.shutdown();
    497         }
     490        try {
     491            worker.shutdown();
     492        } catch (SecurityException e) {
     493            Logging.log(Logging.LEVEL_ERROR, "Unable to shutdown worker", e);
     494        }
     495        JCSCacheManager.shutdown();
     496
    498497        if (mainFrame != null) {
    499498            mainFrame.storeState();
     
    505504        layerManager.resetState();
    506505        super.shutdown();
    507         if (!GraphicsEnvironment.isHeadless()) {
    508             try {
    509                 worker.shutdownNow();
    510             } catch (SecurityException e) {
    511                 Logging.log(Logging.LEVEL_ERROR, "Unable to shutdown worker", e);
    512             }
     506
     507        try {
     508            // in case the current task still hasn't finished
     509            worker.shutdownNow();
     510        } catch (SecurityException e) {
     511            Logging.log(Logging.LEVEL_ERROR, "Unable to shutdown worker", e);
    513512        }
    514513    }
  • trunk/src/org/openstreetmap/josm/gui/MapViewState.java

    r13387 r14052  
    33
    44import java.awt.Container;
    5 import java.awt.GraphicsEnvironment;
    65import java.awt.Point;
    76import java.awt.geom.AffineTransform;
     
    146145
    147146    private static Point findTopLeftOnScreen(JComponent position) {
    148         if (GraphicsEnvironment.isHeadless()) {
    149             // in our imaginary universe the window is always (10, 10) from the top left of the screen
    150             Point topLeftInWindow = findTopLeftInWindow(position);
    151             return new Point(topLeftInWindow.x + 10, topLeftInWindow.y + 10);
    152         } else {
    153             try {
    154                 return position.getLocationOnScreen();
    155             } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
    156                 throw BugReport.intercept(e).put("position", position).put("parent", position::getParent);
    157             }
     147        try {
     148            return position.getLocationOnScreen();
     149        } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
     150            throw BugReport.intercept(e).put("position", position).put("parent", position::getParent);
    158151        }
    159152    }
  • trunk/src/org/openstreetmap/josm/gui/NavigatableComponent.java

    r13868 r14052  
    33
    44import java.awt.Cursor;
    5 import java.awt.GraphicsEnvironment;
    65import java.awt.Point;
    76import java.awt.Rectangle;
     
    326325
    327326    protected boolean isVisibleOnScreen() {
    328         return GraphicsEnvironment.isHeadless() || (
    329             SwingUtilities.getWindowAncestor(this) != null && isShowing()
    330         );
     327        return SwingUtilities.getWindowAncestor(this) != null && isShowing();
    331328    }
    332329
  • trunk/src/org/openstreetmap/josm/gui/io/AsynchronousUploadPrimitivesTask.java

    r13654 r14052  
    44import static org.openstreetmap.josm.tools.I18n.tr;
    55
    6 import java.awt.GraphicsEnvironment;
    76import java.util.Optional;
    87
     
    8685        synchronized (AsynchronousUploadPrimitivesTask.class) {
    8786            if (asynchronousUploadPrimitivesTask != null) {
    88                 if (!GraphicsEnvironment.isHeadless()) {
    89                     GuiHelper.runInEDTAndWait(() ->
    90                             JOptionPane.showMessageDialog(MainApplication.parent,
    91                                     tr("A background upload is already in progress. " +
    92                                             "Kindly wait for it to finish before uploading new changes")));
    93                 }
     87                GuiHelper.runInEDTAndWait(() ->
     88                        JOptionPane.showMessageDialog(MainApplication.parent,
     89                                tr("A background upload is already in progress. " +
     90                                        "Kindly wait for it to finish before uploading new changes")));
    9491                return Optional.empty();
    9592            } else {
  • trunk/src/org/openstreetmap/josm/gui/preferences/PreferenceTabbedPane.java

    r13431 r14052  
    2626import javax.swing.JScrollPane;
    2727import javax.swing.JTabbedPane;
    28 import javax.swing.SwingUtilities;
    2928import javax.swing.event.ChangeEvent;
    3029import javax.swing.event.ChangeListener;
     
    6059import org.openstreetmap.josm.gui.preferences.validator.ValidatorTagCheckerRulesPreference;
    6160import org.openstreetmap.josm.gui.preferences.validator.ValidatorTestsPreference;
     61import org.openstreetmap.josm.gui.util.GuiHelper;
    6262import org.openstreetmap.josm.plugins.PluginDownloadTask;
    6363import org.openstreetmap.josm.plugins.PluginHandler;
     
    175175            }
    176176
    177             Main.parent.repaint();
     177            if (Main.parent != null) {
     178                Main.parent.repaint();
     179            }
    178180        }
    179181    }
     
    421423                // by the remaining "save preferences" activites run on the Swing EDT.
    422424                MainApplication.worker.submit(task);
    423                 MainApplication.worker.submit(() -> SwingUtilities.invokeLater(continuation));
     425                MainApplication.worker.submit(() -> GuiHelper.runInEDT(continuation));
    424426            } else {
    425427                // no need for asynchronous activities. Simply run the remaining "save preference"
  • trunk/src/org/openstreetmap/josm/gui/preferences/advanced/ExportProfileAction.java

    r12881 r14052  
    5656        }
    5757        if (keys.isEmpty()) {
    58             if (!GraphicsEnvironment.isHeadless()) {
    59                 JOptionPane.showMessageDialog(Main.parent,
    60                         tr("All the preferences of this group are default, nothing to save"), tr("Warning"), JOptionPane.WARNING_MESSAGE);
    61             }
     58            JOptionPane.showMessageDialog(Main.parent,
     59                    tr("All the preferences of this group are default, nothing to save"), tr("Warning"), JOptionPane.WARNING_MESSAGE);
    6260            return;
    6361        }
  • trunk/src/org/openstreetmap/josm/gui/preferences/advanced/PreferencesTable.java

    r12987 r14052  
    88import java.awt.Component;
    99import java.awt.Font;
    10 import java.awt.GraphicsEnvironment;
    1110import java.awt.GridBagLayout;
    1211import java.awt.event.MouseAdapter;
     
    9695    public boolean editPreference(final JComponent gui) {
    9796        if (getSelectedRowCount() != 1) {
    98             if (!GraphicsEnvironment.isHeadless()) {
    99                 JOptionPane.showMessageDialog(
    100                         gui,
    101                         tr("Please select the row to edit."),
    102                         tr("Warning"),
    103                         JOptionPane.WARNING_MESSAGE
    104                         );
    105             }
     97            JOptionPane.showMessageDialog(
     98                    gui,
     99                    tr("Please select the row to edit."),
     100                    tr("Warning"),
     101                    JOptionPane.WARNING_MESSAGE
     102                    );
    106103            return false;
    107104        }
     
    197194        PrefEntry pe = null;
    198195        boolean ok = false;
    199         if (!GraphicsEnvironment.isHeadless() && askAddSetting(gui, p)) {
     196        if (askAddSetting(gui, p)) {
    200197            if (rbString.isSelected()) {
    201198                StringSetting sSetting = new StringSetting(null);
     
    282279    public void resetPreferences(final JComponent gui) {
    283280        if (getSelectedRowCount() == 0) {
    284             if (!GraphicsEnvironment.isHeadless()) {
    285                 JOptionPane.showMessageDialog(
    286                         gui,
    287                         tr("Please select the row to delete."),
    288                         tr("Warning"),
    289                         JOptionPane.WARNING_MESSAGE
    290                         );
    291             }
     281            JOptionPane.showMessageDialog(
     282                    gui,
     283                    tr("Please select the row to delete."),
     284                    tr("Warning"),
     285                    JOptionPane.WARNING_MESSAGE
     286                    );
    292287            return;
    293288        }
  • trunk/src/org/openstreetmap/josm/gui/preferences/plugin/PluginPreference.java

    r13842 r14052  
    77import java.awt.BorderLayout;
    88import java.awt.Component;
    9 import java.awt.GraphicsEnvironment;
    109import java.awt.GridBagConstraints;
    1110import java.awt.GridBagLayout;
     
    159158        }
    160159        sb.append("</html>");
    161         if (!GraphicsEnvironment.isHeadless()) {
    162             GuiHelper.runInEDTAndWait(() -> HelpAwareOptionPane.showOptionDialog(
    163                     parent,
    164                     sb.toString(),
    165                     tr("Update plugins"),
    166                     !failed.isEmpty() ? JOptionPane.WARNING_MESSAGE : JOptionPane.INFORMATION_MESSAGE,
    167                             HelpUtil.ht("/Preferences/Plugins")
    168                     ));
    169         }
     160        GuiHelper.runInEDTAndWait(() -> HelpAwareOptionPane.showOptionDialog(
     161                parent,
     162                sb.toString(),
     163                tr("Update plugins"),
     164                !failed.isEmpty() ? JOptionPane.WARNING_MESSAGE : JOptionPane.INFORMATION_MESSAGE,
     165                        HelpUtil.ht("/Preferences/Plugins")
     166                ));
    170167    }
    171168
     
    212209    }
    213210
     211    private static Component addButton(JPanel pnl, JButton button, String buttonName) {
     212        button.setName(buttonName);
     213        return pnl.add(button);
     214    }
     215
    214216    private JPanel buildActionPanel() {
    215217        JPanel pnl = new JPanel(new GridLayout(1, 4));
    216218
    217         pnl.add(new JButton(new DownloadAvailablePluginsAction()));
    218         pnl.add(new JButton(new UpdateSelectedPluginsAction()));
    219         ExpertToggleAction.addVisibilitySwitcher(pnl.add(new JButton(new SelectByListAction())));
    220         ExpertToggleAction.addVisibilitySwitcher(pnl.add(new JButton(new ConfigureSitesAction())));
     219        // assign some component names to these as we go to aid testing
     220        addButton(pnl, new JButton(new DownloadAvailablePluginsAction()), "downloadListButton");
     221        addButton(pnl, new JButton(new UpdateSelectedPluginsAction()), "updatePluginsButton");
     222        ExpertToggleAction.addVisibilitySwitcher(addButton(pnl, new JButton(new SelectByListAction()), "loadFromListButton"));
     223        ExpertToggleAction.addVisibilitySwitcher(addButton(pnl, new JButton(new ConfigureSitesAction()), "configureSitesButton"));
    221224        return pnl;
    222225    }
  • trunk/src/org/openstreetmap/josm/gui/progress/swing/ProgressMonitorExecutor.java

    r12675 r14052  
    22package org.openstreetmap.josm.gui.progress.swing;
    33
     4import java.util.concurrent.CancellationException;
     5import java.util.concurrent.ExecutionException;
     6import java.util.concurrent.Future;
    47import java.util.concurrent.LinkedBlockingQueue;
    58import java.util.concurrent.ThreadPoolExecutor;
    69import java.util.concurrent.TimeUnit;
    710
     11import org.openstreetmap.josm.tools.Logging;
    812import org.openstreetmap.josm.tools.Utils;
    913
     
    3741    }
    3842
     43    @Override
     44    public void afterExecute(final Runnable r, Throwable t) {
     45        // largely as proposed by JDK8 docs
     46        super.afterExecute(r, t);
     47        if (t == null && r instanceof Future<?>) {
     48            try {
     49                ((Future<?>) r).get();
     50            } catch (CancellationException cancellationException) {
     51                t = cancellationException;
     52            } catch (ExecutionException executionException) {
     53                t = executionException.getCause();
     54            } catch (InterruptedException interruptedException) {
     55                Thread.currentThread().interrupt(); // ignore/reset
     56            }
     57        }
     58        if (t != null) {
     59            Logging.error("Thread {0} raised {1}", Thread.currentThread().getName(), t);
     60        }
     61    }
    3962}
  • trunk/src/org/openstreetmap/josm/gui/util/GuiHelper.java

    r13493 r14052  
    202202    }
    203203
     204    private static void handleEDTException(Throwable t) {
     205        Logging.logWithStackTrace(Logging.LEVEL_ERROR, t, "Exception raised in EDT");
     206    }
     207
    204208    /**
    205209     * Executes synchronously a runnable in
     
    215219                SwingUtilities.invokeAndWait(task);
    216220            } catch (InterruptedException | InvocationTargetException e) {
    217                 Logging.error(e);
     221                handleEDTException(e);
    218222            }
    219223        }
     
    256260                return callable.call();
    257261            } catch (Exception e) { // NOPMD
    258                 Logging.error(e);
     262                handleEDTException(e);
    259263                return null;
    260264            }
     
    265269                return task.get();
    266270            } catch (InterruptedException | ExecutionException e) {
    267                 Logging.error(e);
     271                handleEDTException(e);
    268272                return null;
    269273            }
  • trunk/src/org/openstreetmap/josm/tools/Logging.java

    r13647 r14052  
    5151    private static final RememberWarningHandler WARNINGS = new RememberWarningHandler();
    5252
     53    /**
     54     * A {@link ConsoleHandler} with a couple of extra features, allowing it to be targeted at an
     55     * an arbitrary {@link OutputStream} which it can be asked to reaquire the reference for on demand
     56     * through {@link #reacquireOutputStream()}. It can also prevent a LogRecord's output if a
     57     * specified {@code prioritizedHandler} would have outputted it.
     58     * @since 14052
     59     */
     60    public static class ReacquiringConsoleHandler extends ConsoleHandler {
     61        private final Supplier<OutputStream> outputStreamSupplier;
     62        private final Handler prioritizedHandler;
     63        private OutputStream outputStreamMemo;
     64
     65        /**
     66        * Construct a new {@link ReacquiringConsoleHandler}.
     67        * @param outputStreamSupplier A {@link Supplier} which will return the desired
     68        *   {@link OutputStream} for this handler when called. Particularly useful if you happen to be
     69        *   using a test framework which will switch out references to the stderr/stdout streams with
     70        *   new dummy ones from time to time.
     71        * @param prioritizedHandler If non-null, will suppress output of any log records which pass this
     72        *   handler's {@code Handler#isLoggable(LogRecord)} method.
     73        */
     74        public ReacquiringConsoleHandler(
     75            final Supplier<OutputStream> outputStreamSupplier,
     76            final Handler prioritizedHandler
     77        ) {
     78            this.outputStreamSupplier = outputStreamSupplier;
     79            this.prioritizedHandler = prioritizedHandler;
     80
     81            this.reacquireOutputStream();
     82        }
     83
     84        /**
     85         * Set output stream to one acquired from calling outputStreamSupplier
     86         */
     87        public void reacquireOutputStream() {
     88            final OutputStream reacquiredStream = this.outputStreamSupplier.get();
     89
     90            // only bother calling setOutputStream if it's actually different, as setOutputStream
     91            // has the nasty side effect of closing any previous output stream, which is certainly not
     92            // what we would want were the new stream the same one
     93            if (reacquiredStream != this.outputStreamMemo) {
     94                this.setOutputStream(reacquiredStream);
     95            }
     96        }
     97
     98        @Override
     99        public synchronized void setOutputStream(final OutputStream outputStream) {
     100            // this wouldn't be necessary if StreamHandler made it possible to see what the current
     101            // output stream is set to
     102            this.outputStreamMemo = outputStream;
     103            super.setOutputStream(outputStream);
     104        }
     105
     106        @Override
     107        public synchronized void publish(LogRecord record) {
     108            if (this.prioritizedHandler == null || !this.prioritizedHandler.isLoggable(record)) {
     109                super.publish(record);
     110            }
     111        }
     112    }
     113
    53114    static {
    54115        // We need to be sure java.locale.providers system property is initialized by JOSM, not by JRE
     
    62123        Utils.updateSystemProperty("java.util.logging.SimpleFormatter.format", "%1$tF %1$tT.%1$tL %4$s: %5$s%6$s%n");
    63124
    64         ConsoleHandler stderr = new ConsoleHandler();
     125        ConsoleHandler stderr = new ReacquiringConsoleHandler(() -> System.err, null);
    65126        LOGGER.addHandler(stderr);
    66127        try {
     
    70131        }
    71132
    72         ConsoleHandler stdout = new ConsoleHandler() {
    73             @Override
    74             protected synchronized void setOutputStream(OutputStream out) {
    75                 // overwrite output stream.
    76                 super.setOutputStream(System.out);
    77             }
    78 
    79             @Override
    80             public synchronized void publish(LogRecord record) {
    81                 if (!stderr.isLoggable(record)) {
    82                     super.publish(record);
    83                 }
    84             }
    85         };
     133        ConsoleHandler stdout = new ReacquiringConsoleHandler(() -> System.out, stderr);
    86134        LOGGER.addHandler(stdout);
    87135        try {
Note: See TracChangeset for help on using the changeset viewer.