Changeset 19106 in josm


Ignore:
Timestamp:
2024-06-13T21:18:45+02:00 (7 days ago)
Author:
taylor.smock
Message:

Cleanup some new PMD warnings from PMD 7.x (followup of r19101)

Location:
trunk
Files:
39 edited

Legend:

Unmodified
Added
Removed
  • trunk/scripts/SyncEditorLayerIndex.java

    r18989 r19106  
    108108    private static String optionEncoding;
    109109    private static boolean optionNoEli;
    110     private Map<String, String> skip = new HashMap<>();
    111     private Map<String, String> skipStart = new HashMap<>();
     110    private final Map<String, String> skip = new HashMap<>();
     111    private final Map<String, String> skipStart = new HashMap<>();
    112112
    113113    /**
     
    238238
    239239    void loadSkip() throws IOException {
    240         final Pattern pattern = Pattern.compile("^\\|\\| *(ELI|Ignore) *\\|\\| *\\{\\{\\{(.+)\\}\\}\\} *\\|\\|");
     240        final Pattern pattern = Pattern.compile("^\\|\\| *(ELI|Ignore) *\\|\\| *\\{\\{\\{(.+)}}} *\\|\\|");
    241241        try (BufferedReader fr = Files.newBufferedReader(Paths.get(ignoreInputFile), UTF_8)) {
    242242            String line;
     
    479479                    shapes += sep + "</shape>\n";
    480480                }
    481             } catch (IllegalArgumentException ignored) {
    482                 Logging.trace(ignored);
     481            } catch (IllegalArgumentException illegalArgumentException) {
     482                Logging.trace(illegalArgumentException);
    483483            }
    484484            if (!shapes.isEmpty()) {
     
    776776            if (m.matches()) {
    777777                Calendar cal = Calendar.getInstance();
    778                 cal.set(Integer.valueOf(m.group(2)),
    779                         m.group(4) == null ? 0 : Integer.valueOf(m.group(4))-1,
    780                         m.group(6) == null ? 1 : Integer.valueOf(m.group(6)));
     778                cal.set(Integer.parseInt(m.group(2)),
     779                        m.group(4) == null ? 0 : Integer.parseInt(m.group(4))-1,
     780                        m.group(6) == null ? 1 : Integer.parseInt(m.group(6)));
    781781                cal.add(Calendar.DAY_OF_MONTH, -1);
    782782                ed2 = m.group(1) + cal.get(Calendar.YEAR);
     
    12301230                } else {
    12311231                    try {
    1232                         URL jurl = new URL(u.replaceAll("\\{switch:[^\\}]*\\}", "x"));
     1232                        URL jurl = new URL(u.replaceAll("\\{switch:[^}]*}", "x"));
    12331233                        String domain = jurl.getHost();
    12341234                        int port = jurl.getPort();
     
    13751375        List<String> r = new ArrayList<>();
    13761376        List<String> u = getProjectionsUnstripped(e);
    1377         if (u != null) {
    1378             for (String p : u) {
    1379                 if (!oldproj.containsKey(p) && !("CRS:84".equals(p) && !(getUrlStripped(e).matches("(?i)version=1\\.3")))) {
    1380                     r.add(p);
    1381                 }
     1377        for (String p : u) {
     1378            if (!oldproj.containsKey(p) && !("CRS:84".equals(p) && !(getUrlStripped(e).matches("(?i)version=1\\.3")))) {
     1379                r.add(p);
    13821380            }
    13831381        }
  • trunk/src/org/openstreetmap/josm/actions/OrthogonalizeAction.java

    r17458 r19106  
    4444/**
    4545 * Tools / Orthogonalize
    46  *
     46 * <p>
    4747 * Align edges of a way so all angles are angles of 90 or 180 degrees.
    4848 * See USAGE String below.
     
    7373     * excepted deviation from an angle of 0, 90, 180, 360 degrees
    7474     * maximum value: 45 degrees
    75      *
     75     * <p>
    7676     * Current policy is to except just everything, no matter how strange the result would be.
    7777     */
     
    8686    /**
    8787     * Undo the previous orthogonalization for certain nodes.
    88      *
     88     * <p>
    8989     * This is useful, if the way shares nodes that you don't like to change, e.g. imports or
    9090     * work of another user.
    91      *
     91     * <p>
    9292     * This action can be triggered by shortcut only.
    9393     */
     
    279279            int n = wd.wayNodes.size();
    280280            int i = wd.wayNodes.indexOf(singleNode);
    281             Node n0, n2;
     281            final Node n0;
     282            final Node n2;
    282283            if (i == 0 && n >= 3 && singleNode.equals(wd.wayNodes.get(n-1))) {
    283284                n0 = wd.wayNodes.get(n-2);
     
    428429                for (Node n : cs) {
    429430                    s.remove(n);
    430                     average += nC.get(n).doubleValue();
     431                    average += nC.get(n);
    431432                }
    432433                average = average / cs.size();
  • trunk/src/org/openstreetmap/josm/gui/animation/DropImage.java

    r18932 r19106  
    99import java.net.URL;
    1010import java.net.URLDecoder;
     11import java.nio.charset.StandardCharsets;
    1112import java.util.ArrayList;
    1213import java.util.Enumeration;
     
    7172            String path = "images/presets/";
    7273            URL url = DropImage.class.getClassLoader().getResource(path);
    73             if (url != null && url.getProtocol().equals("file")) {
     74            if (url != null && "file".equals(url.getProtocol())) {
    7475                ArrayList<File> dirs = new ArrayList<>();
    7576                dirs.add(new File(url.toURI()));
     
    8788                } while (!dirs.isEmpty());
    8889                name = result.get(seed.nextInt(result.size()));
    89             } else if (url != null && url.getProtocol().equals("jar")) {
    90                 String jarPath = url.getPath().substring(5, url.getPath().indexOf("!"));
    91                 try (JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"))) {
     90            } else if (url != null && "jar".equals(url.getProtocol())) {
     91                String jarPath = url.getPath().substring(5, url.getPath().indexOf('!'));
     92                try (JarFile jar = new JarFile(URLDecoder.decode(jarPath, StandardCharsets.UTF_8))) {
    9293                    Enumeration<JarEntry> entries = jar.entries();
    9394                    while (entries.hasMoreElements()) {
  • trunk/src/org/openstreetmap/josm/gui/conflict/pair/AbstractListMergeModel.java

    r18972 r19106  
    6565 * decisions. {@link PropertyChangeListener}s can register for property value changes of
    6666 * {@link #FROZEN_PROP}.
    67  *
     67 * <p>
    6868 * ListMergeModel is an abstract class. Three methods have to be implemented by subclasses:
    6969 * <ul>
     
    203203        entries = new EnumMap<>(ListRole.class);
    204204        for (ListRole role : ListRole.values()) {
    205             entries.put(role, new ArrayList<T>());
     205            entries.put(role, new ArrayList<>());
    206206        }
    207207
     
    379379            items.add(tr("{0} more...", deletedIds.size() - MAX_DELETED_PRIMITIVE_IN_DIALOG));
    380380        }
    381         StringBuilder sb = new StringBuilder();
    382         sb.append("<html>")
    383           .append(tr("The following objects could not be copied to the target object<br>because they are deleted in the target dataset:"))
    384           .append(Utils.joinAsHtmlUnorderedList(items))
    385           .append("</html>");
     381        String sb = "<html>" +
     382                tr("The following objects could not be copied to the target object<br>because they are deleted in the target dataset:") +
     383                Utils.joinAsHtmlUnorderedList(items) +
     384                "</html>";
    386385        HelpAwareOptionPane.showOptionDialog(
    387386                MainApplication.getMainFrame(),
    388                 sb.toString(),
     387                sb,
    389388                tr("Merging deleted objects failed"),
    390389                JOptionPane.WARNING_MESSAGE,
  • trunk/src/org/openstreetmap/josm/gui/conflict/tags/MultiValueCellEditor.java

    r19050 r19106  
    2828 * proposed tag values. The editor also allows to select all proposed valued or
    2929 * to remove the tag.
    30  *
     30 * <p>
    3131 * The editor responds intercepts some keys and interprets them as navigation keys. It
    3232 * forwards navigation events to {@link NavigationListener}s registered with this editor.
    3333 * You should register the parent table using this editor as {@link NavigationListener}.
    34  *
     34 * <p>
    3535 * {@link KeyEvent#VK_ENTER} and {@link KeyEvent#VK_TAB} trigger a {@link NavigationListener#gotoNextDecision()}.
    3636 */
     
    8888    public MultiValueCellEditor() {
    8989        editorModel = new JosmComboBoxModel<>();
    90         editor = new JosmComboBox<Object>(editorModel) {
     90        editor = new JosmComboBox<>(editorModel) {
    9191            @Override
    9292            public void processKeyEvent(KeyEvent e) {
     
    216216         */
    217217        protected void renderValue(Object value) {
    218             setFont(UIManager.getFont("ComboBox.font"));
     218            final String comboBoxFont = "ComboBox.font";
     219            setFont(UIManager.getFont(comboBoxFont));
    219220            if (value instanceof String) {
    220221                setText((String) value);
     
    223224                case UNDECIDED:
    224225                    setText(tr("Choose a value"));
    225                     setFont(UIManager.getFont("ComboBox.font").deriveFont(Font.ITALIC + Font.BOLD));
     226                    setFont(UIManager.getFont(comboBoxFont).deriveFont(Font.ITALIC + Font.BOLD));
    226227                    break;
    227228                case KEEP_NONE:
    228229                    setText(tr("none"));
    229                     setFont(UIManager.getFont("ComboBox.font").deriveFont(Font.ITALIC + Font.BOLD));
     230                    setFont(UIManager.getFont(comboBoxFont).deriveFont(Font.ITALIC + Font.BOLD));
    230231                    break;
    231232                case KEEP_ALL:
    232233                    setText(tr("all"));
    233                     setFont(UIManager.getFont("ComboBox.font").deriveFont(Font.ITALIC + Font.BOLD));
     234                    setFont(UIManager.getFont(comboBoxFont).deriveFont(Font.ITALIC + Font.BOLD));
    234235                    break;
    235236                case SUM_ALL_NUMERIC:
    236237                    setText(tr("sum"));
    237                     setFont(UIManager.getFont("ComboBox.font").deriveFont(Font.ITALIC + Font.BOLD));
     238                    setFont(UIManager.getFont(comboBoxFont).deriveFont(Font.ITALIC + Font.BOLD));
    238239                    break;
    239240                default:
  • trunk/src/org/openstreetmap/josm/gui/datatransfer/TagTransferable.java

    r11015 r19106  
    5454                string.append('\n');
    5555            }
    56             string.append(e.getKey());
    57             string.append('=');
    58             string.append(e.getValue());
     56            string.append(e.getKey())
     57                .append('=')
     58                .append(e.getValue());
    5959        }
    6060        return string.toString();
  • trunk/src/org/openstreetmap/josm/gui/dialogs/InspectPrimitiveDataText.java

    r19078 r19106  
    223223            s.append(INDENT).append(INDENT);
    224224            addHeadline(m.getMember());
    225             s.append(tr(" as \"{0}\"", m.getRole()));
    226             s.append(NL);
     225            s.append(tr(" as \"{0}\"", m.getRole()))
     226                .append(NL);
    227227        }
    228228    }
  • trunk/src/org/openstreetmap/josm/gui/dialogs/SelectionListDialog.java

    r19101 r19106  
    529529                    .filter(i -> history.get(i).equals(selection))
    530530                    .findFirst()
    531                     .ifPresent(i -> history.remove(i));
     531                    .ifPresent(history::remove);
    532532            int maxsize = Config.getPref().getInt("select.history-size", SELECTION_HISTORY_SIZE);
    533533            while (history.size() > maxsize) {
  • trunk/src/org/openstreetmap/josm/gui/dialogs/ToggleDialog.java

    r18871 r19106  
    1111import java.awt.Graphics;
    1212import java.awt.GraphicsEnvironment;
     13import java.awt.GridBagConstraints;
    1314import java.awt.GridBagLayout;
    1415import java.awt.GridLayout;
     
    4647import javax.swing.JToggleButton;
    4748import javax.swing.Scrollable;
     49import javax.swing.SwingConstants;
    4850import javax.swing.SwingUtilities;
    4951
     
    100102     */
    101103    public static final BooleanProperty PROP_DYNAMIC_BUTTONS = new BooleanProperty("dialog.dynamic.buttons", false);
     104    private static final String SELECTED = "selected";
    102105
    103106    private final transient ParametrizedEnumProperty<ButtonHidingType> propButtonHiding =
    104             new ParametrizedEnumProperty<ToggleDialog.ButtonHidingType>(ButtonHidingType.class, ButtonHidingType.DYNAMIC) {
    105         @Override
    106         protected String getKey(String... params) {
    107             return preferencePrefix + ".buttonhiding";
    108         }
    109 
    110         @Override
    111         protected ButtonHidingType parse(String s) {
    112             try {
    113                 return super.parse(s);
    114             } catch (IllegalArgumentException e) {
    115                 // Legacy settings
    116                 Logging.trace(e);
    117                 return Boolean.parseBoolean(s) ? ButtonHidingType.DYNAMIC : ButtonHidingType.ALWAYS_SHOWN;
    118             }
    119         }
    120     };
     107            new ParametrizedEnumProperty<>(ButtonHidingType.class, ButtonHidingType.DYNAMIC) {
     108                @Override
     109                protected String getKey(String... params) {
     110                    return preferencePrefix + ".buttonhiding";
     111                }
     112
     113                @Override
     114                protected ButtonHidingType parse(String s) {
     115                    try {
     116                        return super.parse(s);
     117                    } catch (IllegalArgumentException e) {
     118                        // Legacy settings
     119                        Logging.trace(e);
     120                        return Boolean.parseBoolean(s) ? ButtonHidingType.DYNAMIC : ButtonHidingType.ALWAYS_SHOWN;
     121                    }
     122                }
     123            };
    121124
    122125    /** The action to toggle this dialog */
     
    354357            windowMenuItem.setState(true);
    355358        }
    356         toggleAction.putValue("selected", Boolean.FALSE);
    357         toggleAction.putValue("selected", Boolean.TRUE);
     359        toggleAction.putValue(SELECTED, Boolean.FALSE);
     360        toggleAction.putValue(SELECTED, Boolean.TRUE);
    358361    }
    359362
     
    382385    @Override
    383386    public void buttonHidden() {
    384         if (Boolean.TRUE.equals(toggleAction.getValue("selected"))) {
     387        if (Boolean.TRUE.equals(toggleAction.getValue(SELECTED))) {
    385388            toggleAction.actionPerformed(null);
    386389        }
     
    402405        }
    403406        setIsShowing(false);
    404         toggleAction.putValue("selected", Boolean.FALSE);
     407        toggleAction.putValue(SELECTED, Boolean.FALSE);
    405408    }
    406409
     
    551554            // scale down the dialog icon
    552555            ImageIcon icon = ImageProvider.get("dialogs", iconName, ImageProvider.ImageSizes.SMALLICON);
    553             lblTitle = new JLabel("", icon, JLabel.TRAILING);
     556            lblTitle = new JLabel("", icon, SwingConstants.TRAILING);
    554557            lblTitle.setIconTextGap(8);
    555558
     
    569572            lblTitleWeak.setPreferredSize(new Dimension(Integer.MAX_VALUE, 20));
    570573            lblTitleWeak.setMinimumSize(new Dimension(0, 20));
    571             add(lblTitleWeak, GBC.std().fill(GBC.HORIZONTAL));
     574            add(lblTitleWeak, GBC.std().fill(GridBagConstraints.HORIZONTAL));
    572575
    573576            buttonsHide = new JButton(ImageProvider.get("misc", buttonHiding != ButtonHidingType.ALWAYS_SHOWN
  • trunk/src/org/openstreetmap/josm/gui/dialogs/ValidatorDialog.java

    r19016 r19106  
    176176        buttons.add(new SideButton(fixAction));
    177177
    178         if (ValidatorPrefHelper.PREF_USE_IGNORE.get()) {
     178        if (Boolean.TRUE.equals(ValidatorPrefHelper.PREF_USE_IGNORE.get())) {
    179179            ignoreAction = new AbstractAction() {
    180180                {
     
    430430        OsmDataLayer editLayer = e.getSource().getEditLayer();
    431431        if (editLayer == null) {
    432             tree.setErrorList(new ArrayList<TestError>());
     432            tree.setErrorList(new ArrayList<>());
    433433        } else {
    434434            tree.setErrorList(editLayer.validationErrors);
  • trunk/src/org/openstreetmap/josm/gui/dialogs/relation/MemberTransferHandler.java

    r16438 r19106  
    101101        final RelationMemberTransferable.Data memberData = (RelationMemberTransferable.Data)
    102102                support.getTransferable().getTransferData(RelationMemberTransferable.RELATION_MEMBER_DATA);
    103         importData(destination, insertRow, memberData.getRelationMemberData(), new AbstractRelationMemberConverter<RelationMemberData>() {
     103        importData(destination, insertRow, memberData.getRelationMemberData(), new AbstractRelationMemberConverter<>() {
    104104            @Override
    105105            protected RelationMember getMember(MemberTable destination, RelationMemberData data, OsmPrimitive p) {
     
    113113        final PrimitiveTransferData data = (PrimitiveTransferData)
    114114                support.getTransferable().getTransferData(PrimitiveTransferData.DATA_FLAVOR);
    115         importData(destination, insertRow, data.getDirectlyAdded(), new AbstractRelationMemberConverter<PrimitiveData>() {
     115        importData(destination, insertRow, data.getDirectlyAdded(), new AbstractRelationMemberConverter<>() {
    116116            @Override
    117117            protected RelationMember getMember(MemberTable destination, PrimitiveData data, OsmPrimitive p) {
  • trunk/src/org/openstreetmap/josm/gui/download/BookmarkList.java

    r17721 r19106  
    242242     */
    243243    public BookmarkList() {
    244         setModel(new DefaultListModel<Bookmark>());
     244        setModel(new DefaultListModel<>());
    245245        load();
    246246        setVisibleRowCount(7);
  • trunk/src/org/openstreetmap/josm/gui/download/OSMDownloadSource.java

    r19050 r19106  
    110110                            bounds.extend(b);
    111111                        }
    112                     } catch (InterruptedException | ExecutionException ex) {
     112                    } catch (InterruptedException ex) {
     113                        Thread.currentThread().interrupt();
     114                        Logging.warn(ex);
     115                    } catch (ExecutionException ex) {
    113116                        Logging.warn(ex);
    114117                    }
     
    215218            checkboxChangeListener = e -> {
    216219                rememberSettings();
    217                 dialog.getSelectedDownloadArea().ifPresent(OSMDownloadSourcePanel.this::boundingBoxChanged);
     220                dialog.getSelectedDownloadArea().ifPresent(this::boundingBoxChanged);
    218221            };
    219222
     
    273276             * It is mandatory to specify the area to download from OSM.
    274277             */
    275             if (!settings.getDownloadBounds().isPresent()) {
     278            if (settings.getDownloadBounds().isEmpty()) {
    276279                JOptionPane.showMessageDialog(
    277280                        this.getParent(),
  • trunk/src/org/openstreetmap/josm/gui/io/AbstractUploadTask.java

    r19050 r19106  
    33
    44import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
     5import static org.openstreetmap.josm.tools.I18n.marktr;
    56import static org.openstreetmap.josm.tools.I18n.tr;
    67
     
    1011import java.time.format.FormatStyle;
    1112import java.util.ArrayList;
    12 import java.util.Arrays;
    1313import java.util.Collection;
    1414import java.util.Collections;
     
    4545 */
    4646public abstract class AbstractUploadTask extends PleaseWaitRunnable {
     47    private static final String CANCEL_TR = marktr("Cancel");
     48    private static final String CANCEL = "cancel";
     49    private static final String UPDATE_DATA = "updatedata";
    4750
    4851    /**
     
    132135                new ButtonSpec(
    133136                        lbl,
    134                         new ImageProvider("updatedata"),
     137                        new ImageProvider(UPDATE_DATA),
    135138                        null, null),
    136139                new ButtonSpec(
    137140                        tr("Synchronize entire dataset"),
    138                         new ImageProvider("updatedata"),
     141                        new ImageProvider(UPDATE_DATA),
    139142                        null, null),
    140143                new ButtonSpec(
    141                         tr("Cancel"),
    142                         new ImageProvider("cancel"),
     144                        tr(CANCEL_TR),
     145                        new ImageProvider(CANCEL),
    143146                        null, null)
    144147        };
     
    167170        case 0: synchronizePrimitive(primitiveType, id); break;
    168171        case 1: synchronizeDataSet(); break;
    169         default: return;
     172        default: // Do nothing (just return)
    170173        }
    171174    }
     
    180183                new ButtonSpec(
    181184                        tr("Synchronize entire dataset"),
    182                         new ImageProvider("updatedata"),
     185                        new ImageProvider(UPDATE_DATA),
    183186                        null, null),
    184187                new ButtonSpec(
    185                         tr("Cancel"),
    186                         new ImageProvider("cancel"),
     188                        tr(CANCEL_TR),
     189                        new ImageProvider(CANCEL),
    187190                        null, null)
    188191        };
     
    244247                ),
    245248                new ButtonSpec(
    246                         tr("Cancel"),
    247                         new ImageProvider("cancel"),
     249                        tr(CANCEL_TR),
     250                        new ImageProvider(CANCEL),
    248251                        tr("Click to cancel and to resume editing the map"),
    249252                        null /* no specific help context */
     
    267270            if (msg.contains("to delete")) {
    268271                DownloadReferrersAction.downloadReferrers(MainApplication.getLayerManager().getEditLayer(),
    269                         Arrays.asList(conflict.a));
     272                        Collections.singletonList(conflict.a));
    270273            }
    271274            if (msg.contains("to upload") && !conflict.b.isEmpty()) {
  • trunk/src/org/openstreetmap/josm/gui/io/ChangesetManagementPanel.java

    r19050 r19106  
    3232import org.openstreetmap.josm.spi.preferences.Config;
    3333import org.openstreetmap.josm.tools.ImageProvider;
     34import org.openstreetmap.josm.tools.Logging;
    3435
    3536/**
    3637 * ChangesetManagementPanel allows to configure changeset to be used in the next upload.
    37  *
     38 * <p>
    3839 * It is displayed as one of the configuration panels in the {@link UploadDialog}.
    39  *
     40 * <p>
    4041 * ChangesetManagementPanel is a source for {@link java.beans.PropertyChangeEvent}s. Clients can listen to
    4142 * <ul>
     
    5051    static final String SELECTED_CHANGESET_PROP = ChangesetManagementPanel.class.getName() + ".selectedChangeset";
    5152    static final String CLOSE_CHANGESET_AFTER_UPLOAD = ChangesetManagementPanel.class.getName() + ".closeChangesetAfterUpload";
     53    private static final String UPLOAD_CHANGESET_CLOSE = "upload.changeset.close";
    5254
    5355    private JosmComboBox<Changeset> cbOpenChangesets;
     
    142144        cbOpenChangesets.addItemListener(closeChangesetAction);
    143145
    144         cbCloseAfterUpload.setSelected(Config.getPref().getBoolean("upload.changeset.close", true));
     146        cbCloseAfterUpload.setSelected(Config.getPref().getBoolean(UPLOAD_CHANGESET_CLOSE, true));
    145147        cbCloseAfterUpload.addItemListener(new CloseAfterUploadItemStateListener());
    146148
     
    198200            case ItemEvent.SELECTED:
    199201                firePropertyChange(CLOSE_CHANGESET_AFTER_UPLOAD, false, true);
    200                 Config.getPref().putBoolean("upload.changeset.close", true);
     202                Config.getPref().putBoolean(UPLOAD_CHANGESET_CLOSE, true);
    201203                break;
    202204            case ItemEvent.DESELECTED:
    203205                firePropertyChange(CLOSE_CHANGESET_AFTER_UPLOAD, true, false);
    204                 Config.getPref().putBoolean("upload.changeset.close", false);
     206                Config.getPref().putBoolean(UPLOAD_CHANGESET_CLOSE, false);
    205207                break;
    206208            default: // Do nothing
     
    262264            ChangesetCache.getInstance().refreshChangesetsFromServer();
    263265        } catch (OsmTransferException e) {
    264             return;
     266            Logging.trace(e);
    265267        }
    266268    }
  • trunk/src/org/openstreetmap/josm/gui/io/UploadSelectionDialog.java

    r16438 r19106  
    254254                return Collections.emptyList();
    255255            return Arrays.stream(indices).filter(i -> i >= 0)
    256                     .mapToObj(i -> data.get(i))
     256                    .mapToObj(data::get)
    257257                    .collect(Collectors.toList());
    258258        }
  • trunk/src/org/openstreetmap/josm/gui/io/importexport/GpxExporter.java

    r18801 r19106  
    44import static org.openstreetmap.josm.tools.I18n.tr;
    55
     6import java.awt.GridBagConstraints;
    67import java.awt.GridBagLayout;
    78import java.awt.event.ActionListener;
     
    5556    private static final String GPL_WARNING = "<html><font color='red' size='-2'>"
    5657        + tr("Note: GPL is not compatible with the OSM license. Do not upload GPL licensed tracks.") + "</html>";
     58    private static final String PUBLIC_DOMAIN = "public domain";
    5759
    5860    private static final String[] LICENSES = {
    5961            "Creative Commons By-SA",
    6062            "Open Database License (ODbL)",
    61             "public domain",
     63            PUBLIC_DOMAIN,
    6264            "GNU Lesser Public License (LGPL)",
    6365            "BSD License (MIT/X11)"};
     
    6567    private static final String[] URLS = {
    6668            "https://creativecommons.org/licenses/by-sa/3.0",
    67             "http://opendatacommons.org/licenses/odbl/1.0",
    68             "public domain",
     69            "https://opendatacommons.org/licenses/odbl/1-0/",
     70            PUBLIC_DOMAIN,
    6971            "https://www.gnu.org/copyleft/lesser.html",
    70             "http://www.opensource.org/licenses/bsd-license.php"};
     72            "https://opensource.org/license/BSD-2-Clause"};
    7173
    7274    /**
     
    108110        if (quiet) {
    109111            gpxData = getGpxData(layer, file);
    110             try (OutputStream fo = Compression.getCompressedFileOutputStream(file)) {
    111                 GpxWriter w = new GpxWriter(fo);
     112            try (OutputStream fo = Compression.getCompressedFileOutputStream(file);
     113                 GpxWriter w = new GpxWriter(fo)) {
    112114                w.write(gpxData);
    113                 w.close();
    114115                fo.flush();
    115116            }
     
    135136        desc.setLineWrap(true);
    136137        desc.setText(gpxData.getString(META_DESC));
    137         p.add(new JScrollPane(desc), GBC.eop().fill(GBC.BOTH));
     138        p.add(new JScrollPane(desc), GBC.eop().fill(GridBagConstraints.BOTH));
    138139
    139140        JCheckBox author = new JCheckBox(tr("Add author information"), Config.getPref().getBoolean("lastAddAuthor", true));
     
    143144        p.add(nameLabel, GBC.std().insets(10, 0, 5, 0));
    144145        JosmTextField authorName = new JosmTextField();
    145         p.add(authorName, GBC.eol().fill(GBC.HORIZONTAL));
     146        p.add(authorName, GBC.eol().fill(GridBagConstraints.HORIZONTAL));
    146147        nameLabel.setLabelFor(authorName);
    147148
     
    149150        p.add(emailLabel, GBC.std().insets(10, 0, 5, 0));
    150151        JosmTextField email = new JosmTextField();
    151         p.add(email, GBC.eol().fill(GBC.HORIZONTAL));
     152        p.add(email, GBC.eol().fill(GridBagConstraints.HORIZONTAL));
    152153        emailLabel.setLabelFor(email);
    153154
     
    155156        p.add(copyrightLabel, GBC.std().insets(10, 0, 5, 0));
    156157        JosmTextField copyright = new JosmTextField();
    157         p.add(copyright, GBC.std().fill(GBC.HORIZONTAL));
     158        p.add(copyright, GBC.std().fill(GridBagConstraints.HORIZONTAL));
    158159        copyrightLabel.setLabelFor(copyright);
    159160
     
    164165        p.add(copyrightYearLabel, GBC.std().insets(10, 0, 5, 5));
    165166        JosmTextField copyrightYear = new JosmTextField("");
    166         p.add(copyrightYear, GBC.eol().fill(GBC.HORIZONTAL));
     167        p.add(copyrightYear, GBC.eol().fill(GridBagConstraints.HORIZONTAL));
    167168        copyrightYearLabel.setLabelFor(copyrightYear);
    168169
    169170        JLabel warning = new JLabel("<html><font size='-2'>&nbsp;</html");
    170         p.add(warning, GBC.eol().fill(GBC.HORIZONTAL).insets(15, 0, 0, 0));
     171        p.add(warning, GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(15, 0, 0, 0));
    171172        addDependencies(gpxData, author, authorName, email, copyright, predefined, copyrightYear, nameLabel, emailLabel,
    172173                copyrightLabel, copyrightYearLabel, warning);
     
    175176        JosmTextField keywords = new JosmTextField();
    176177        keywords.setText(gpxData.getString(META_KEYWORDS));
    177         p.add(keywords, GBC.eol().fill(GBC.HORIZONTAL));
     178        p.add(keywords, GBC.eol().fill(GridBagConstraints.HORIZONTAL));
    178179
    179180        boolean sel = Config.getPref().getBoolean("gpx.export.colors", true);
    180181        JCheckBox colors = new JCheckBox(tr("Save track colors in GPX file"), sel);
    181         p.add(colors, GBC.eol().fill(GBC.HORIZONTAL));
     182        p.add(colors, GBC.eol().fill(GridBagConstraints.HORIZONTAL));
    182183        JCheckBox garmin = new JCheckBox(tr("Use Garmin compatible GPX extensions"),
    183184                Config.getPref().getBoolean("gpx.export.colors.garmin", false));
    184185        garmin.setEnabled(sel);
    185         p.add(garmin, GBC.eol().fill(GBC.HORIZONTAL).insets(20, 0, 0, 0));
     186        p.add(garmin, GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(20, 0, 0, 0));
    186187
    187188        boolean hasPrefs = !gpxData.getLayerPrefs().isEmpty();
     
    189190                hasPrefs && Config.getPref().getBoolean("gpx.export.prefs", true));
    190191        layerPrefs.setEnabled(hasPrefs);
    191         p.add(layerPrefs, GBC.eop().fill(GBC.HORIZONTAL));
     192        p.add(layerPrefs, GBC.eop().fill(GridBagConstraints.HORIZONTAL));
    192193
    193194        ExtendedDialog ed = new ExtendedDialog(MainApplication.getMainFrame(),
     
    197198            .setContent(p);
    198199
    199         colors.addActionListener(l -> {
    200             garmin.setEnabled(colors.isSelected());
    201         });
     200        colors.addActionListener(l -> garmin.setEnabled(colors.isSelected()));
    202201
    203202        garmin.addActionListener(l -> {
     
    268267        }
    269268
    270         try (OutputStream fo = Compression.getCompressedFileOutputStream(file)) {
    271             GpxWriter w = new GpxWriter(fo);
     269        try (OutputStream fo = Compression.getCompressedFileOutputStream(file);
     270            GpxWriter w = new GpxWriter(fo)) {
    272271            w.write(gpxData, cFormat, layerPrefs.isSelected());
    273             w.close();
    274272            fo.flush();
    275273        }
     
    409407            for (int i : l.getSelectedIndices()) {
    410408                if (i == 2) {
    411                     license = new StringBuilder("public domain");
     409                    license = new StringBuilder(PUBLIC_DOMAIN);
    412410                    break;
    413411                }
  • trunk/src/org/openstreetmap/josm/gui/layer/LayerManager.java

    r18466 r19106  
    2424 * <h1>Threading</h1>
    2525 * Synchronization of the layer manager is done by synchronizing all read/write access. All changes are internally done in the EDT thread.
    26  *
     26 * <p>
    2727 * Methods of this manager may be called from any thread in any order.
    2828 * Listeners are called while this layer manager is locked, so they should not block on other threads.
     
    189189    }
    190190
     191    private static final String LISTENER = "listener";
     192    private static final String EVENT = "event";
     193
    191194    /**
    192195     * This is the list of layers we manage. The list is unmodifiable. That way, read access does
    193196     * not need to be synchronized.
    194      *
     197     * <p>
    195198     * It is only changed in the EDT.
    196199     * @see LayerManager#updateLayers(Consumer)
     
    255258    protected synchronized void realRemoveLayer(Layer layer) {
    256259        GuiHelper.assertCallFromEdt();
    257         Set<Layer> toRemove = Collections.newSetFromMap(new IdentityHashMap<Layer, Boolean>());
     260        Set<Layer> toRemove = Collections.newSetFromMap(new IdentityHashMap<>());
    258261        toRemove.add(layer);
    259262
     
    361364    /**
    362365     * Replies an unmodifiable list of layers of a certain type.
    363      *
     366     * <p>
    364367     * Example:
    365368     * <pre>
     
    459462                l.layerAdded(e);
    460463            } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException t) {
    461                 throw BugReport.intercept(t).put("listener", l).put("event", e);
     464                throw BugReport.intercept(t).put(LISTENER, l).put(EVENT, e);
    462465            }
    463466        }
     
    476479                l.layerRemoving(e);
    477480            } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException t) {
    478                 throw BugReport.intercept(t).put("listener", l).put("event", e).put("layer", layer);
     481                throw BugReport.intercept(t).put(LISTENER, l).put(EVENT, e).put("layer", layer);
    479482            }
    480483        }
     
    492495                l.layerOrderChanged(e);
    493496            } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException t) {
    494                 throw BugReport.intercept(t).put("listener", l).put("event", e);
     497                throw BugReport.intercept(t).put(LISTENER, l).put(EVENT, e);
    495498            }
    496499        }
  • trunk/src/org/openstreetmap/josm/gui/layer/geoimage/SynchronizeTimeFromPhotoDialog.java

    r18051 r19106  
    163163        JPanel panelLst = new JPanel(new BorderLayout());
    164164
    165         JList<String> imgList = new JList<>(new AbstractListModel<String>() {
     165        JList<String> imgList = new JList<>(new AbstractListModel<>() {
    166166            @Override
    167167            public String getElementAt(int i) {
  • trunk/src/org/openstreetmap/josm/gui/layer/gpx/GpxDrawHelper.java

    r18871 r19106  
    593593                    for (WayPoint trkPnt : segment) {
    594594                        Object val = trkPnt.get(GpxConstants.PT_HDOP);
    595                         if (val != null) {
    596                             double hdop = ((Float) val).doubleValue();
     595                        if (val instanceof Float) {
     596                            double hdop = ((Float) val);
    597597                            if (hdop > maxval) {
    598598                                maxval = hdop;
     
    14661466
    14671467        // typical rendering rate -> use realtime preview instead of accurate display
    1468         final double maxSegm = 25_000, nrSegms = listSegm.size();
     1468        final double maxSegm = 25_000;
     1469        final double nrSegms = listSegm.size();
    14691470
    14701471        // determine random drop rate
     
    15111512
    15121513        // collect frequently used items
    1513         final long fromX = (long) fromPnt.getX(); final long deltaX = (long) (toPnt.getX() - fromX);
    1514         final long fromY = (long) fromPnt.getY(); final long deltaY = (long) (toPnt.getY() - fromY);
     1514        final long fromX = (long) fromPnt.getX();
     1515        final long fromY = (long) fromPnt.getY();
     1516        final long deltaX = (long) (toPnt.getX() - fromX);
     1517        final long deltaY = (long) (toPnt.getY() - fromY);
    15151518
    15161519        // use same random values for each point
  • trunk/src/org/openstreetmap/josm/gui/layer/imagery/TileSourceDisplaySettings.java

    r16488 r19106  
    8181     * Create a new {@link TileSourceDisplaySettings}
    8282     */
     83    @SuppressWarnings("PMD.UnnecessaryVarargsArrayCreation") // See https://github.com/pmd/pmd/issues/5069
    8384    public TileSourceDisplaySettings() {
    8485        this(new String[] {PREFERENCE_PREFIX});
  • trunk/src/org/openstreetmap/josm/gui/preferences/PreferenceTabbedPane.java

    r18211 r19106  
    8383 * @author imi
    8484 */
    85 @SuppressWarnings("deprecation")
    8685public final class PreferenceTabbedPane extends JTabbedPane implements ExpertModeChangeListener, ChangeListener {
    8786
     
    118117            }
    119118            if (requiresRestart) {
    120                 sb.append(tr("You have to restart JOSM for some settings to take effect."));
    121                 sb.append("<br/><br/>");
    122                 sb.append(tr("Would you like to restart now?"));
     119                sb.append(tr("You have to restart JOSM for some settings to take effect."))
     120                    .append("<br/><br/>")
     121                    .append(tr("Would you like to restart now?"));
    123122            }
    124123            sb.append("</html>");
     
    358357            selectTabBy(tps -> tps.equals(tab));
    359358            return tab.selectSubTab(sub);
    360         } catch (NoSuchElementException ignore) {
    361             Logging.trace(ignore);
     359        } catch (NoSuchElementException e) {
     360            Logging.trace(e);
    362361            return false;
    363362        }
     
    564563    private int computeMaxTabWidth() {
    565564        FontMetrics fm = getFontMetrics(getFont());
    566         return settings.stream().filter(x -> x instanceof TabPreferenceSetting).map(x -> ((TabPreferenceSetting) x).getTitle())
     565        return settings.stream().filter(TabPreferenceSetting.class::isInstance)
     566                .map(TabPreferenceSetting.class::cast).map(TabPreferenceSetting::getTitle)
    567567                .filter(Objects::nonNull).mapToInt(fm::stringWidth).max().orElse(120);
    568568    }
  • trunk/src/org/openstreetmap/josm/gui/preferences/ToolbarPreferences.java

    r19101 r19106  
    859859            });
    860860
    861             ListCellRenderer<ActionDefinition> renderer = new ListCellRenderer<ActionDefinition>() {
     861            ListCellRenderer<ActionDefinition> renderer = new ListCellRenderer<>() {
    862862                private final DefaultListCellRenderer def = new DefaultListCellRenderer();
     863
    863864                @Override
    864865                public Component getListCellRendererComponent(JList<? extends ActionDefinition> list,
    865                         ActionDefinition action, int index, boolean isSelected, boolean cellHasFocus) {
     866                                                              ActionDefinition action, int index, boolean isSelected, boolean cellHasFocus) {
    866867                    String s;
    867868                    Icon i;
  • trunk/src/org/openstreetmap/josm/gui/preferences/imagery/CacheSettingsPanel.java

    r18871 r19106  
    44import static org.openstreetmap.josm.tools.I18n.tr;
    55
     6import java.awt.GridBagConstraints;
    67import java.awt.GridBagLayout;
    78import java.awt.event.ActionEvent;
     
    6061    private final JosmTextField cacheDir = new JosmTextField(11);
    6162    private final JSpinner maxElementsOnDisk = new JSpinner(new SpinnerNumberModel(
    62             AbstractCachedTileSourceLayer.MAX_DISK_CACHE_SIZE.get().intValue(), 0, Integer.MAX_VALUE, 1));
     63            (int) AbstractCachedTileSourceLayer.MAX_DISK_CACHE_SIZE.get(), 0, Integer.MAX_VALUE, 1));
    6364
    6465    /**
     
    7071        add(new JLabel(tr("Tile cache directory: ")), GBC.std());
    7172        add(GBC.glue(5, 0), GBC.std());
    72         add(cacheDir, GBC.eol().fill(GBC.HORIZONTAL));
     73        add(cacheDir, GBC.eol().fill(GridBagConstraints.HORIZONTAL));
    7374
    7475        add(new JLabel(tr("Maximum size of disk cache (per imagery) in MB: ")), GBC.std());
     
    9495                GBC.eol().insets(5, 5, 0, 0));
    9596            add(new JScrollPane(getTableForCache(cache, tableModel)),
    96                 GBC.eol().fill(GBC.BOTH));
     97                GBC.eol().fill(GridBagConstraints.BOTH));
    9798        });
    9899    }
     
    212213    private static boolean removeCacheFiles(String path, long maxSize) {
    213214        File directory = new File(path);
    214         File[] cacheFiles = directory.listFiles((dir, name) -> name.endsWith(".data") || name.endsWith(".key"));
     215        final String data = ".data";
     216        final String key = ".key";
     217        File[] cacheFiles = directory.listFiles((dir, name) -> name.endsWith(data) || name.endsWith(key));
    215218        boolean restartRequired = false;
    216219        if (cacheFiles != null) {
     
    223226                    Utils.deleteFile(cacheFile);
    224227                    File otherFile = null;
    225                     if (cacheFile.getName().endsWith(".data")) {
    226                         otherFile = new File(cacheFile.getPath().replaceAll("\\.data$", ".key"));
    227                     } else if (cacheFile.getName().endsWith(".key")) {
    228                         otherFile = new File(cacheFile.getPath().replaceAll("\\.key$", ".data"));
     228                    if (cacheFile.getName().endsWith(data)) {
     229                        otherFile = new File(cacheFile.getPath().replaceAll("\\.data$", key));
     230                    } else if (cacheFile.getName().endsWith(key)) {
     231                        otherFile = new File(cacheFile.getPath().replaceAll("\\.key$", data));
    229232                    }
    230233                    if (otherFile != null) {
  • trunk/src/org/openstreetmap/josm/gui/preferences/imagery/TMSSettingsPanel.java

    r19103 r19106  
    4949                TMSLayer.MAX_ZOOM, 1));
    5050        maxConcurrentDownloads = new JSpinner(new SpinnerNumberModel(
    51                 TMSCachedTileLoader.THREAD_LIMIT.get().intValue(), 0, Integer.MAX_VALUE, 1));
     51                (int) TMSCachedTileLoader.THREAD_LIMIT.get(), 0, Integer.MAX_VALUE, 1));
    5252        maxDownloadsPerHost = new JSpinner(new SpinnerNumberModel(
    53                 TMSCachedTileLoader.HOST_LIMIT.get().intValue(), 0, Integer.MAX_VALUE, 1));
     53                (int) TMSCachedTileLoader.HOST_LIMIT.get(), 0, Integer.MAX_VALUE, 1));
    5454
    5555
  • trunk/src/org/openstreetmap/josm/gui/preferences/plugin/PluginPreference.java

    r18871 r19106  
    33
    44import static java.awt.GridBagConstraints.HORIZONTAL;
     5import static org.openstreetmap.josm.tools.I18n.marktr;
    56import static org.openstreetmap.josm.tools.I18n.tr;
    67import static org.openstreetmap.josm.tools.I18n.trc;
     
    7172 */
    7273public final class PluginPreference extends ExtensibleTabPreferenceSetting {
     74    private static final String HTML_START = "<html>";
     75    private static final String HTML_END = "</html>";
     76    private static final String UPDATE_PLUGINS = marktr("Update plugins");
    7377
    7478    /**
     
    112116                    downloaded.size(),
    113117                    downloaded.size()
    114                     ));
    115             sb.append("<ul>");
     118                    ))
     119                .append("<ul>");
    116120            for (PluginInformation pi: downloaded) {
    117121                sb.append("<li>").append(pi.name).append(" (").append(pi.version).append(")</li>");
     
    125129                    failed.size(),
    126130                    failed.size()
    127                     ));
    128             sb.append("<ul>");
     131                    ))
     132                .append("<ul>");
    129133            for (PluginInformation pi: failed) {
    130134                sb.append("<li>").append(pi.name).append("</li>");
     
    149153        final Collection<PluginInformation> failed = task.getFailedPlugins();
    150154        final StringBuilder sb = new StringBuilder();
    151         sb.append("<html>")
     155        sb.append(HTML_START)
    152156          .append(buildDownloadSummary(task));
    153157        if (restartRequired) {
    154158            sb.append(tr("Please restart JOSM to activate the downloaded plugins."));
    155159        }
    156         sb.append("</html>");
     160        sb.append(HTML_END);
    157161        GuiHelper.runInEDTAndWait(() -> HelpAwareOptionPane.showOptionDialog(
    158162                parent,
    159163                sb.toString(),
    160                 tr("Update plugins"),
     164                tr(UPDATE_PLUGINS),
    161165                !failed.isEmpty() ? JOptionPane.WARNING_MESSAGE : JOptionPane.INFORMATION_MESSAGE,
    162166                        HelpUtil.ht("/Preferences/Plugins")
     
    375379    class UpdateSelectedPluginsAction extends AbstractAction {
    376380        UpdateSelectedPluginsAction() {
    377             putValue(NAME, tr("Update plugins"));
     381            putValue(NAME, tr(UPDATE_PLUGINS));
    378382            putValue(SHORT_DESCRIPTION, tr("Update the selected plugins"));
    379383            new ImageProvider("dialogs", "refresh").getResource().attachImageIcon(this);
     
    388392                        JOptionPane.INFORMATION_MESSAGE,
    389393                        null // FIXME: provide help context
    390                         ));
    391             } catch (InterruptedException | InvocationTargetException e) {
     394                ));
     395            } catch (InterruptedException e) {
     396                Thread.currentThread().interrupt();
     397                Logging.error(e);
     398            } catch (InvocationTargetException e) {
    392399                Logging.error(e);
    393400            }
     
    401408                    pnlPluginPreferences,
    402409                    toUpdate,
    403                     tr("Update plugins")
     410                    tr(UPDATE_PLUGINS)
    404411                    );
    405412            // the async task for downloading plugin information
     
    444451                            // Time to find the missing plugins...
    445452                            toAdd.addAll(pi.getRequiredPlugins().stream().filter(plugin -> PluginHandler.getPlugin(plugin) == null)
    446                                     .map(plugin -> model.getPluginInformation(plugin))
     453                                    .map(model::getPluginInformation)
    447454                                    .collect(Collectors.toSet()));
    448455                        }
     
    502509            JCheckBox deleteNotInList = new JCheckBox(tr("Disable all other plugins"));
    503510
    504             JLabel helpLabel = new JLabel("<html>" + String.join("<br/>",
     511            JLabel helpLabel = new JLabel(HTML_START + String.join("<br/>",
    505512                    tr("Enter a list of plugins you want to download."),
    506513                    tr("You should add one plugin id per line, version information is ignored."),
    507                     tr("You can copy+paste the list of a status report here.")) + "</html>");
     514                    tr("You can copy+paste the list of a status report here.")) + HTML_END);
    508515
    509516            if (JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog(GuiHelper.getFrameForComponent(getTabPane()),
     
    556563        private boolean confirmIgnoreNotFound(List<String> notFound) {
    557564            String list = "<ul><li>" + String.join("</li><li>", notFound) + "</li></ul>";
    558             String message = "<html>" + tr("The following plugins were not found. Continue anyway?") + list + "</html>";
     565            String message = HTML_START + tr("The following plugins were not found. Continue anyway?") + list + HTML_END;
    559566            return JOptionPane.showConfirmDialog(GuiHelper.getFrameForComponent(getTabPane()),
    560567                    message) == JOptionPane.OK_OPTION;
  • trunk/src/org/openstreetmap/josm/gui/tagging/ac/AutoCompComboBox.java

    r18305 r19106  
    3232     */
    3333    public AutoCompComboBox() {
    34         this(new AutoCompComboBoxModel<E>());
     34        this(new AutoCompComboBoxModel<>());
    3535    }
    3636
     
    4242    public AutoCompComboBox(AutoCompComboBoxModel<E> model) {
    4343        super(model);
    44         setEditor(new AutoCompComboBoxEditor<E>());
     44        setEditor(new AutoCompComboBoxEditor<>());
    4545        setEditable(true);
    4646        getEditorComponent().setModel(model);
  • trunk/src/org/openstreetmap/josm/gui/tagging/presets/TaggingPresetItemGuiSupport.java

    r18801 r19106  
    135135        Tagged tagged = Tagged.ofMap(selected.iterator().next().getKeys());
    136136        // update changed tags
    137         changedTagsSupplier.get().forEach(tag -> tagged.put(tag));
     137        changedTagsSupplier.get().forEach(tagged::put);
    138138        return tagged;
    139139    }
  • trunk/src/org/openstreetmap/josm/io/GpxWriter.java

    r19050 r19106  
    147147                .collect(Collectors.toList());
    148148
    149         validprefixes = namespaces.stream().map(n -> n.getPrefix()).collect(Collectors.toList());
     149        validprefixes = namespaces.stream().map(XMLNamespace::getPrefix).collect(Collectors.toList());
    150150
    151151        data.creator = JOSM_CREATOR_NAME;
  • trunk/src/org/openstreetmap/josm/io/MaxChangesetSizeExceededPolicy.java

    r12687 r19106  
    66 * @since 12687 (moved from {@code gui.io} package)
    77 */
     8@SuppressWarnings("PMD.LongVariable")
    89public enum MaxChangesetSizeExceededPolicy {
    910    /**
  • trunk/src/org/openstreetmap/josm/io/MultiFetchServerObjectReader.java

    r19050 r19106  
    357357                Logging.error(e);
    358358                if (e.getCause() instanceof OsmTransferException)
    359                     throw (OsmTransferException) e.getCause();
     359                    throw (OsmTransferException) e.getCause(); // NOPMD
    360360            }
    361361        }
  • trunk/src/org/openstreetmap/josm/io/OsmPbfReader.java

    r19077 r19106  
    77import java.io.IOException;
    88import java.io.InputStream;
    9 import java.io.OutputStream;
    109import java.util.ArrayList;
    1110import java.util.Arrays;
     
    6867        @Override
    6968        public int read() throws IOException {
    70             count++;
    71             return this.source.read();
     69            final int read = this.source.read();
     70            if (read > 0) {
     71                count++;
     72            }
     73            return read;
     74        }
     75
     76        @Override
     77        public int read(@Nonnull byte[] b, int off, int len) throws IOException {
     78            final int read = this.source.read(b, off, len);
     79            if (read > 0) {
     80                this.count += read;
     81            }
     82            return read;
    7283        }
    7384
     
    104115        public boolean markSupported() {
    105116            return this.source.markSupported();
    106         }
    107 
    108         @Override
    109         public long transferTo(OutputStream out) throws IOException {
    110             return super.transferTo(out);
    111117        }
    112118
     
    251257        int size = Integer.MIN_VALUE;
    252258        Blob.CompressionType type = null;
    253         ProtobufRecord current;
    254259        // Needed since size and compression type + compression data may be in a different order
    255260        byte[] bytes = null;
    256261        while (parser.hasNext() && cis.getCount() - start < header.dataSize()) {
    257             current = new ProtobufRecord(baos, parser);
    258             switch (current.getField()) {
    259                 case 1:
    260                     type = Blob.CompressionType.raw;
    261                     bytes = current.getBytes();
    262                     break;
    263                 case 2:
    264                     size = current.asUnsignedVarInt().intValue();
    265                     break;
    266                 case 3:
    267                     type = Blob.CompressionType.zlib;
    268                     bytes = current.getBytes();
    269                     break;
    270                 case 4:
    271                     type = Blob.CompressionType.lzma;
    272                     bytes = current.getBytes();
    273                     break;
    274                 case 5:
    275                     type = Blob.CompressionType.bzip2;
    276                     bytes = current.getBytes();
    277                     break;
    278                 case 6:
    279                     type = Blob.CompressionType.lz4;
    280                     bytes = current.getBytes();
    281                     break;
    282                 case 7:
    283                     type = Blob.CompressionType.zstd;
    284                     bytes = current.getBytes();
    285                     break;
    286                 default:
    287                     throw new IllegalStateException("Unknown compression type: " + current.getField());
     262            try (ProtobufRecord current = new ProtobufRecord(baos, parser)) {
     263                switch (current.getField()) {
     264                    case 1:
     265                        type = Blob.CompressionType.raw;
     266                        bytes = current.getBytes();
     267                        break;
     268                    case 2:
     269                        size = current.asUnsignedVarInt().intValue();
     270                        break;
     271                    case 3:
     272                        type = Blob.CompressionType.zlib;
     273                        bytes = current.getBytes();
     274                        break;
     275                    case 4:
     276                        type = Blob.CompressionType.lzma;
     277                        bytes = current.getBytes();
     278                        break;
     279                    case 5:
     280                        type = Blob.CompressionType.bzip2;
     281                        bytes = current.getBytes();
     282                        break;
     283                    case 6:
     284                        type = Blob.CompressionType.lz4;
     285                        bytes = current.getBytes();
     286                        break;
     287                    case 7:
     288                        type = Blob.CompressionType.zstd;
     289                        bytes = current.getBytes();
     290                        break;
     291                    default:
     292                        throw new IllegalStateException("Unknown compression type: " + current.getField());
     293                }
    288294            }
    289295        }
     
    421427        }
    422428        for (ProtobufRecord primitiveGroup : primitiveGroups) {
    423             try {
     429            try (primitiveGroup) {
    424430                ds.beginUpdate();
    425431                parsePrimitiveGroup(baos, primitiveGroup.getBytes(), primitiveBlockRecord);
  • trunk/src/org/openstreetmap/josm/io/session/GpxTracksSessionExporter.java

    r18466 r19106  
    7979
    8080    @Override
    81     @SuppressWarnings("resource")
     81    // The new closable resources in this method will close the input OutputStream
     82    @SuppressWarnings({"squid:S2095", "PMD.CloseResource"})
    8283    protected void addDataFile(OutputStream out) {
    8384        Writer writer = new OutputStreamWriter(out, StandardCharsets.UTF_8);
  • trunk/src/org/openstreetmap/josm/io/session/MarkerSessionExporter.java

    r18466 r19106  
    33
    44import java.awt.Component;
     5import java.awt.GridBagConstraints;
    56import java.awt.GridBagLayout;
    67import java.io.IOException;
     
    1819import javax.swing.SwingConstants;
    1920
     21import org.openstreetmap.josm.data.gpx.GpxConstants;
    2022import org.openstreetmap.josm.data.gpx.GpxData;
    2123import org.openstreetmap.josm.gui.MainApplication;
     
    6668        p.add(export, GBC.std());
    6769        p.add(lbl, GBC.std());
    68         p.add(GBC.glue(1, 0), GBC.std().fill(GBC.HORIZONTAL));
     70        p.add(GBC.glue(1, 0), GBC.std().fill(GridBagConstraints.HORIZONTAL));
    6971        return p;
    7072    }
     
    9395    }
    9496
    95     @SuppressWarnings("resource")
     97    // The new closable resources in this method will close the input OutputStream
     98    @SuppressWarnings({"squid:S2095", "PMD.CloseResource"})
    9699    protected void addDataFile(OutputStream out) {
    97100        Writer writer = new OutputStreamWriter(out, StandardCharsets.UTF_8);
     
    132135                }
    133136            });
    134             data.put(GpxData.META_DESC, "exported JOSM marker layer");
     137            data.put(GpxConstants.META_DESC, "exported JOSM marker layer");
    135138            for (Marker m : layer.data) {
    136139                data.waypoints.add(m.convertToWayPoint());
  • trunk/src/org/openstreetmap/josm/plugins/PluginClassLoader.java

    r17664 r19106  
    5959        Class<?> result = findLoadedClass(name);
    6060        if (result == null) {
    61             for (PluginClassLoader dep : dependencies) {
    62                 try {
    63                     result = dep.loadClass(name, resolve);
    64                     if (result != null) {
    65                         return result;
    66                     }
    67                 } catch (ClassNotFoundException e) {
    68                     Logging.trace("Plugin class not found in dep {0}: {1}", dep, e.getMessage());
    69                     Logging.trace(e);
    70                 }
    71             }
     61            result = findClassInDependencies(name, resolve);
    7262            try {
    7363                // Will delegate to parent.loadClass(name, resolve) if needed
     
    9383    }
    9484
     85    /**
     86     * Try to find the specified class in this classes dependencies
     87     * @param name The name of the class to find
     88     * @param resolve {@code true} to resolve the class
     89     * @return the class, if found, otherwise {@code null}
     90     */
     91    @SuppressWarnings("PMD.CloseResource") // NOSONAR We do *not* want to close class loaders in this method...
     92    private Class<?> findClassInDependencies(String name, boolean resolve) {
     93        for (PluginClassLoader dep : dependencies) {
     94            try {
     95                Class<?> result = dep.loadClass(name, resolve);
     96                if (result != null) {
     97                    return result;
     98                }
     99            } catch (ClassNotFoundException e) {
     100                Logging.trace("Plugin class not found in dep {0}: {1}", dep, e.getMessage());
     101                Logging.trace(e);
     102            }
     103        }
     104        return null;
     105    }
     106
    95107    @Override
     108    @SuppressWarnings("PMD.CloseResource") // NOSONAR We do *not* want to close class loaders in this method...
    96109    public URL findResource(String name) {
    97110        URL resource = super.findResource(name);
  • trunk/src/org/openstreetmap/josm/plugins/PluginHandler.java

    r19101 r19106  
    5656import javax.swing.UIManager;
    5757
     58import jakarta.annotation.Nullable;
    5859import org.openstreetmap.josm.actions.RestartAction;
    5960import org.openstreetmap.josm.data.Preferences;
     
    770771
    771772        // make sure the dependencies to other plugins are not broken
    772         //
    773773        if (requires != null) {
    774             Set<String> pluginNames = new HashSet<>();
    775             for (PluginInformation pi: plugins) {
    776                 pluginNames.add(pi.name);
    777                 if (pi.provides != null) {
    778                     pluginNames.add(pi.provides);
    779                 }
    780             }
    781             Set<String> missingPlugins = new HashSet<>();
    782             List<String> requiredPlugins = local ? plugin.getLocalRequiredPlugins() : plugin.getRequiredPlugins();
    783             for (String requiredPlugin : requiredPlugins) {
    784                 if (!pluginNames.contains(requiredPlugin)) {
    785                     missingPlugins.add(requiredPlugin);
    786                 }
    787             }
     774            Set<String> missingPlugins = findMissingPlugins(plugins, plugin, local);
    788775            if (!missingPlugins.isEmpty()) {
    789776                if (parent != null) {
     
    794781        }
    795782        return true;
     783    }
     784
     785    /**
     786     * Find the missing plugin(s) for a specified plugin
     787     * @param plugins The currently loaded plugins
     788     * @param plugin The plugin to find the missing information for
     789     * @param local Determines if the local or up-to-date plugin dependencies are to be checked.
     790     * @return A set of missing plugins for the given plugin
     791     */
     792    private static Set<String> findMissingPlugins(Collection<PluginInformation> plugins, PluginInformation plugin, boolean local) {
     793        Set<String> pluginNames = new HashSet<>();
     794        for (PluginInformation pi: plugins) {
     795            pluginNames.add(pi.name);
     796            if (pi.provides != null) {
     797                pluginNames.add(pi.provides);
     798            }
     799        }
     800        Set<String> missingPlugins = new HashSet<>();
     801        List<String> requiredPlugins = local ? plugin.getLocalRequiredPlugins() : plugin.getRequiredPlugins();
     802        for (String requiredPlugin : requiredPlugins) {
     803            if (!pluginNames.contains(requiredPlugin)) {
     804                missingPlugins.add(requiredPlugin);
     805            }
     806        }
     807        return missingPlugins;
    796808    }
    797809
     
    818830     * @param plugins the plugins to add
    819831     */
     832    @SuppressWarnings("PMD.CloseResource") // NOSONAR We do *not* want to close class loaders in this method...
    820833    private static void extendJoinedPluginResourceCL(Collection<PluginInformation> plugins) {
    821834        // iterate all plugins and collect all libraries of all plugins:
     
    901914                return;
    902915
    903             for (PluginInformation info : toLoad) {
    904                 PluginClassLoader cl = AccessController.doPrivileged((PrivilegedAction<PluginClassLoader>)
    905                     () -> new PluginClassLoader(
    906                         info.libraries.toArray(new URL[0]),
    907                         PluginHandler.class.getClassLoader(),
    908                         null));
    909                 classLoaders.put(info.name, cl);
    910             }
     916            generateClassloaders(toLoad);
    911917
    912918            // resolve dependencies
    913             for (PluginInformation info : toLoad) {
    914                 PluginClassLoader cl = classLoaders.get(info.name);
    915                 DEPENDENCIES:
    916                 for (String depName : info.getLocalRequiredPlugins()) {
    917                     for (PluginInformation depInfo : toLoad) {
    918                         if (isDependency(depInfo, depName)) {
    919                             cl.addDependency(classLoaders.get(depInfo.name));
    920                             continue DEPENDENCIES;
    921                         }
    922                     }
    923                     for (PluginProxy proxy : pluginList) {
    924                         if (isDependency(proxy.getPluginInformation(), depName)) {
    925                             cl.addDependency(proxy.getClassLoader());
    926                             continue DEPENDENCIES;
    927                         }
    928                     }
    929                     Logging.error("unable to find dependency " + depName + " for plugin " + info.getName());
    930                 }
    931             }
     919            resolveDependencies(toLoad);
    932920
    933921            extendJoinedPluginResourceCL(toLoad);
     
    944932    }
    945933
     934    /**
     935     * Generate classloaders for a list of plugins
     936     * @param toLoad The plugins to generate the classloaders for
     937     */
     938    @SuppressWarnings({"squid:S2095", "PMD.CloseResource"}) // NOSONAR the classloaders and put in a map which we want to keep.
     939    private static void generateClassloaders(List<PluginInformation> toLoad) {
     940        for (PluginInformation info : toLoad) {
     941            PluginClassLoader cl = AccessController.doPrivileged((PrivilegedAction<PluginClassLoader>)
     942                    () -> new PluginClassLoader(
     943                            info.libraries.toArray(new URL[0]),
     944                            PluginHandler.class.getClassLoader(),
     945                            null));
     946            classLoaders.put(info.name, cl);
     947        }
     948    }
     949
     950    /**
     951     * Resolve dependencies for a list of plugins
     952     * @param toLoad The plugins to resolve dependencies for
     953     */
     954    @SuppressWarnings({"squid:S2095", "PMD.CloseResource"}) // NOSONAR the classloaders are from a persistent map
     955    private static void resolveDependencies(List<PluginInformation> toLoad) {
     956        for (PluginInformation info : toLoad) {
     957            PluginClassLoader cl = classLoaders.get(info.name);
     958            for (String depName : info.getLocalRequiredPlugins()) {
     959                boolean finished = false;
     960                for (PluginInformation depInfo : toLoad) {
     961                    if (isDependency(depInfo, depName)) {
     962                        cl.addDependency(classLoaders.get(depInfo.name));
     963                        finished = true;
     964                        break;
     965                    }
     966                }
     967                if (finished) {
     968                    continue;
     969                }
     970                for (PluginProxy proxy : pluginList) {
     971                    if (isDependency(proxy.getPluginInformation(), depName)) {
     972                        cl.addDependency(proxy.getClassLoader());
     973                        break;
     974                    }
     975                }
     976                Logging.error("unable to find dependency " + depName + " for plugin " + info.getName());
     977            }
     978        }
     979    }
     980
    946981    private static boolean isDependency(PluginInformation pi, String depName) {
    947982        return depName.equals(pi.getName()) || depName.equals(pi.provides);
     
    9991034     *
    10001035     */
     1036    @Nullable
     1037    @SuppressWarnings("squid:S1168") // The null return is part of the API for this method.
    10011038    private static Map<String, PluginInformation> loadLocallyAvailablePluginInformation(ProgressMonitor monitor) {
    10021039        if (monitor == null) {
     
    10121049                return null;
    10131050            } catch (InterruptedException e) {
     1051                Thread.currentThread().interrupt();
    10141052                Logging.warn("InterruptedException in " + PluginHandler.class.getSimpleName()
    10151053                        + " while loading locally available plugin information");
     
    10271065
    10281066    private static void alertMissingPluginInformation(Component parent, Collection<String> plugins) {
    1029         StringBuilder sb = new StringBuilder();
    1030         sb.append(HTML_START)
    1031           .append(trn("JOSM could not find information about the following plugin:",
    1032                 "JOSM could not find information about the following plugins:",
    1033                 plugins.size()))
    1034           .append(Utils.joinAsHtmlUnorderedList(plugins))
    1035           .append(trn("The plugin is not going to be loaded.",
    1036                 "The plugins are not going to be loaded.",
    1037                 plugins.size()))
    1038           .append(HTML_END);
     1067        String sb = HTML_START +
     1068                trn("JOSM could not find information about the following plugin:",
     1069                        "JOSM could not find information about the following plugins:",
     1070                        plugins.size()) +
     1071                Utils.joinAsHtmlUnorderedList(plugins) +
     1072                trn("The plugin is not going to be loaded.",
     1073                        "The plugins are not going to be loaded.",
     1074                        plugins.size()) +
     1075                HTML_END;
    10391076        HelpAwareOptionPane.showOptionDialog(
    10401077                parent,
    1041                 sb.toString(),
     1078                sb,
    10421079                tr(WARNING),
    10431080                JOptionPane.WARNING_MESSAGE,
     
    11911228                // don't abort in case of error, continue with downloading plugins below
    11921229            } catch (InterruptedException e) {
     1230                Thread.currentThread().interrupt();
    11931231                Logging.warn(tr("Failed to download plugin information list") + ": InterruptedException");
    11941232                // don't abort in case of error, continue with downloading plugins below
     
    12401278                    return plugins;
    12411279                } catch (InterruptedException e) {
     1280                    Thread.currentThread().interrupt();
    12421281                    Logging.warn("InterruptedException in " + PluginHandler.class.getSimpleName()
    12431282                            + " while updating plugins");
     
    15351574            GuiHelper.runInEDT(task);
    15361575            return task.get();
    1537         } catch (InterruptedException | ExecutionException e) {
     1576        } catch (InterruptedException e) {
     1577            Thread.currentThread().interrupt();
     1578            Logging.warn(e);
     1579        } catch (ExecutionException e) {
    15381580            Logging.warn(e);
    15391581        }
  • trunk/src/org/openstreetmap/josm/spi/lifecycle/Lifecycle.java

    r17663 r19106  
    6767     * @since 14139
    6868     */
     69    // PMD wasn't detecting that we were trying to shutdown the ExecutorService
     70    @SuppressWarnings("PMD.CloseResource")
    6971    public static void initialize(InitializationSequence initSequence) {
    7072        // Initializes tasks that must be run before parallel tasks
     
    9092                Logging.log(Logging.LEVEL_ERROR, "Unable to shutdown executor service", e);
    9193            }
    92         } catch (InterruptedException | ExecutionException ex) {
     94        } catch (InterruptedException ex) {
     95            Thread.currentThread().interrupt();
     96            throw new JosmRuntimeException(ex);
     97        } catch (ExecutionException ex) {
    9398            throw new JosmRuntimeException(ex);
    9499        }
  • trunk/test/unit/org/openstreetmap/josm/tools/PlatformHookOsxTest.java

    r19103 r19106  
    66import static org.junit.jupiter.api.Assertions.assertNotNull;
    77import static org.junit.jupiter.api.Assertions.assertTrue;
    8 import static org.junit.jupiter.api.Assumptions.assumeTrue;
    98
    109import java.io.File;
     
    1312import org.junit.jupiter.api.BeforeAll;
    1413import org.junit.jupiter.api.Test;
    15 import org.junit.jupiter.api.condition.EnabledIf;
    1614import org.junit.jupiter.api.condition.EnabledOnOs;
    1715import org.junit.jupiter.api.condition.OS;
  • trunk/test/unit/org/openstreetmap/josm/tools/UtilsTest.java

    r19103 r19106  
    1010
    1111import java.io.File;
    12 import java.io.IOException;
    13 import java.io.InputStream;
    1412import java.util.ArrayList;
    1513import java.util.Arrays;
Note: See TracChangeset for help on using the changeset viewer.