Changeset 19108 in josm for trunk


Ignore:
Timestamp:
2024-06-17T19:37:02+02:00 (5 months ago)
Author:
taylor.smock
Message:

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

Location:
trunk
Files:
38 edited

Legend:

Unmodified
Added
Removed
  • trunk/scripts/TagInfoExtract.java

    r19050 r19108  
    224224
    225225    private abstract class Extractor {
    226         abstract void run() throws Exception;
     226        abstract void run() throws IOException, OsmTransferException, ParseException, SAXException;
    227227
    228228        void writeJson(String name, String description, Iterable<TagInfoTag> tags) throws IOException {
  • trunk/scripts/TaggingPresetSchemeWikiGenerator.java

    r19050 r19108  
    3535    }
    3636
    37     public static void main(String[] args) throws Exception {
     37    public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
    3838        document = parseTaggingPresetSchema();
    3939        xPath = XPathFactory.newInstance().newXPath();
  • trunk/src/org/openstreetmap/josm/actions/OpenFileAction.java

    r18871 r19108  
    8484        // If the user explicitly wants native file dialogs, let them use it.
    8585        // Rather unfortunately, this means that they will not be able to select files and directories.
    86         if (FileChooserManager.PROP_USE_NATIVE_FILE_DIALOG.get()
     86        if (Boolean.TRUE.equals(FileChooserManager.PROP_USE_NATIVE_FILE_DIALOG.get())
    8787                // This is almost redundant, as the JDK currently doesn't support this with (all?) native file choosers.
    8888                && !NativeFileChooser.supportsSelectionMode(FILES_AND_DIRECTORIES)) {
  • trunk/src/org/openstreetmap/josm/actions/SelectAllAction.java

    r17062 r19108  
    88import java.awt.event.KeyEvent;
    99
     10import org.openstreetmap.josm.data.osm.IPrimitive;
    1011import org.openstreetmap.josm.data.osm.OsmData;
    1112import org.openstreetmap.josm.tools.Shortcut;
     
    3031            return;
    3132        OsmData<?, ?, ?, ?> ds = getLayerManager().getActiveData();
    32         // Do not use method reference before the Java 11 migration
    33         // Otherwise we face a compiler bug, see below:
    34         // https://bugs.openjdk.java.net/browse/JDK-8141508
    35         // https://bugs.openjdk.java.net/browse/JDK-8142476
    36         // https://bugs.openjdk.java.net/browse/JDK-8191655
    37         ds.setSelected(ds.getPrimitives(t -> t.isSelectable()));
     33        ds.setSelected(ds.getPrimitives(IPrimitive::isSelectable));
    3834    }
    3935
  • trunk/src/org/openstreetmap/josm/actions/SelectByInternalPointAction.java

    r13434 r19108  
    104104        final Collection<OsmPrimitive> surroundingObjects = getSurroundingObjects(internalPoint);
    105105        final DataSet ds = MainApplication.getLayerManager().getActiveDataSet();
    106         if (surroundingObjects.isEmpty()) {
    107             return;
    108         } else if (doRemove) {
    109             final Collection<OsmPrimitive> newSelection = new ArrayList<>(ds.getSelected());
    110             newSelection.removeAll(surroundingObjects);
    111             ds.setSelected(newSelection);
    112         } else if (doAdd) {
    113             final Collection<OsmPrimitive> newSelection = new ArrayList<>(ds.getSelected());
    114             newSelection.add(surroundingObjects.iterator().next());
    115             ds.setSelected(newSelection);
    116         } else {
    117             ds.setSelected(surroundingObjects.iterator().next());
     106        if (!surroundingObjects.isEmpty()) {
     107            if (doRemove) {
     108                final Collection<OsmPrimitive> newSelection = new ArrayList<>(ds.getSelected());
     109                newSelection.removeAll(surroundingObjects);
     110                ds.setSelected(newSelection);
     111            } else if (doAdd) {
     112                final Collection<OsmPrimitive> newSelection = new ArrayList<>(ds.getSelected());
     113                newSelection.add(surroundingObjects.iterator().next());
     114                ds.setSelected(newSelection);
     115            } else {
     116                ds.setSelected(surroundingObjects.iterator().next());
     117            }
    118118        }
    119119    }
  • trunk/src/org/openstreetmap/josm/actions/SelectNonBranchingWaySequences.java

    r18211 r19108  
    5656    private void addNodes(Node node) {
    5757        if (node == null) return;
    58         else if (!nodes.add(node))
     58        if (!nodes.add(node)) {
    5959            outerNodes.remove(node);
    60         else
     60        } else {
    6161            outerNodes.add(node);
     62        }
    6263    }
    6364
  • trunk/src/org/openstreetmap/josm/actions/SessionSaveAction.java

    r18942 r19108  
    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;
    67import static org.openstreetmap.josm.tools.I18n.trn;
     
    89import java.awt.Component;
    910import java.awt.Dimension;
     11import java.awt.GridBagConstraints;
    1012import java.awt.GridBagLayout;
    1113import java.awt.event.ActionEvent;
     
    8486    private static final BooleanProperty SAVE_PLUGIN_INFORMATION_PROPERTY = new BooleanProperty("session.saveplugins", false);
    8587    private static final String TOOLTIP_DEFAULT = tr("Save the current session.");
     88    private static final String SAVE_SESSION = marktr("Save Session");
    8689
    8790    protected transient FileFilter joz = new ExtensionFileFilter("joz", "joz", tr("Session file (archive) (*.joz)"));
     
    120123     */
    121124    protected SessionSaveAction(boolean toolbar, boolean installAdapters) {
    122         this(tr("Save Session"), "session", TOOLTIP_DEFAULT,
     125        this(tr(SAVE_SESSION), "session", TOOLTIP_DEFAULT,
    123126                Shortcut.registerShortcut("system:savesession", tr("File: {0}", tr("Save Session...")), KeyEvent.VK_S, Shortcut.ALT_CTRL),
    124127                toolbar, "save-session", installAdapters);
     
    183186                .collect(Collectors.toList());
    184187
    185         boolean zipRequired = layersOut.stream().map(l -> exporters.get(l))
     188        boolean zipRequired = layersOut.stream().map(exporters::get)
    186189                .anyMatch(ex -> ex != null && ex.requiresZip()) || pluginsWantToSave();
    187190
     
    333336
    334337        if (zipRequired) {
    335             fc = createAndOpenFileChooser(false, false, tr("Save Session"), joz, JFileChooser.FILES_ONLY, "lastDirectory");
     338            fc = createAndOpenFileChooser(false, false, tr(SAVE_SESSION), joz, JFileChooser.FILES_ONLY, "lastDirectory");
    336339        } else {
    337             fc = createAndOpenFileChooser(false, false, tr("Save Session"), Arrays.asList(jos, joz), jos,
     340            fc = createAndOpenFileChooser(false, false, tr(SAVE_SESSION), Arrays.asList(jos, joz), jos,
    338341                    JFileChooser.FILES_ONLY, "lastDirectory");
    339342        }
     
    366369         */
    367370        public SessionSaveAsDialog() {
    368             super(MainApplication.getMainFrame(), tr("Save Session"), tr("Save As"), tr("Cancel"));
     371            super(MainApplication.getMainFrame(), tr(SAVE_SESSION), tr("Save As"), tr("Cancel"));
    369372            configureContextsensitiveHelp("Action/SessionSaveAs", true /* show help button */);
    370373            initialize();
     
    442445                JPanel wrapper = new JPanel(new GridBagLayout());
    443446                wrapper.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
    444                 wrapper.add(exportPanel, GBC.std().fill(GBC.HORIZONTAL));
    445                 ip.add(wrapper, GBC.eol().fill(GBC.HORIZONTAL).insets(2, 2, 4, 2));
    446             }
    447             ip.add(GBC.glue(0, 1), GBC.eol().fill(GBC.VERTICAL));
     447                wrapper.add(exportPanel, GBC.std().fill(GridBagConstraints.HORIZONTAL));
     448                ip.add(wrapper, GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(2, 2, 4, 2));
     449            }
     450            ip.add(GBC.glue(0, 1), GBC.eol().fill(GridBagConstraints.VERTICAL));
    448451            JScrollPane sp = new JScrollPane(ip);
    449452            sp.setBorder(BorderFactory.createEmptyBorder());
     
    475478            p.add(include, GBC.std());
    476479            p.add(lbl, GBC.std());
    477             p.add(GBC.glue(1, 0), GBC.std().fill(GBC.HORIZONTAL));
     480            p.add(GBC.glue(1, 0), GBC.std().fill(GridBagConstraints.HORIZONTAL));
    478481            return p;
    479482        }
     
    538541     * @deprecated since 18833, use {@link #setCurrentSession(File, List, SessionWriter.SessionWriterFlags...)} instead
    539542     */
    540     @Deprecated
     543    @Deprecated(since = "18833")
    541544    public static void setCurrentSession(File file, boolean zip, List<Layer> layers) {
    542545        if (zip) {
  • trunk/src/org/openstreetmap/josm/actions/downloadtasks/AbstractDownloadTask.java

    r18830 r19108  
    6161
    6262    protected static <T extends Enum<T> & UrlPattern> String[] patterns(Class<T> urlPatternEnum) {
    63         // Do not use a method reference until we switch to Java 11, as we face JDK-8141508 with Java 8
    64         return Arrays.stream(urlPatternEnum.getEnumConstants()).map(/* JDK-8141508 */ t -> t.pattern()).toArray(String[]::new);
     63        return Arrays.stream(urlPatternEnum.getEnumConstants()).map(UrlPattern::pattern).toArray(String[]::new);
    6564    }
    6665
  • trunk/src/org/openstreetmap/josm/actions/downloadtasks/DownloadTaskList.java

    r17330 r19108  
    213213    public Set<OsmPrimitive> getDownloadedPrimitives() {
    214214        return tasks.stream()
    215                 .filter(t -> t instanceof DownloadOsmTask)
    216                 .map(t -> ((DownloadOsmTask) t).getDownloadedData())
     215                .filter(DownloadOsmTask.class::isInstance)
     216                .map(DownloadOsmTask.class::cast)
     217                .map(DownloadOsmTask::getDownloadedData)
    217218                .filter(Objects::nonNull)
    218219                .flatMap(ds -> ds.allPrimitives().stream())
     
    240241                try {
    241242                    future.get();
    242                 } catch (InterruptedException | ExecutionException | CancellationException e) {
     243                } catch (InterruptedException interruptedException) {
     244                    Thread.currentThread().interrupt();
     245                    Logging.error(interruptedException);
     246                    return;
     247                } catch (ExecutionException | CancellationException e) {
    243248                    Logging.error(e);
    244249                    return;
     
    255260                                        Utils.joinAsHtmlUnorderedList(errors)) + "</html>",
    256261                                tr("Errors during download"), JOptionPane.ERROR_MESSAGE);
    257                         return;
    258262                    }
    259263                });
     
    269273            if (editDataSet != null && osmData) {
    270274                final List<DownloadOsmTask> osmTasks = tasks.stream()
    271                         .filter(t -> t instanceof DownloadOsmTask).map(t -> (DownloadOsmTask) t)
     275                        .filter(DownloadOsmTask.class::isInstance).map(DownloadOsmTask.class::cast)
    272276                        .filter(t -> t.getDownloadedData() != null)
    273277                        .collect(Collectors.toList());
  • trunk/src/org/openstreetmap/josm/actions/mapmode/ExtrudeAction.java

    r18987 r19108  
    390390        if (!map.mapView.isActiveLayerVisible())
    391391            return;
    392         if (!(Boolean) this.getValue("active"))
     392        if (Boolean.FALSE.equals(this.getValue("active")))
    393393            return;
    394394        if (e.getButton() != MouseEvent.BUTTON1)
     
    512512                    if (moveCommand == null) {
    513513                        //make a new move command
    514                         moveCommand = new MoveCommand(new ArrayList<OsmPrimitive>(movingNodeList), bestMovement);
     514                        moveCommand = new MoveCommand(new ArrayList<>(movingNodeList), bestMovement);
    515515                        UndoRedoHandler.getInstance().add(moveCommand);
    516516                    } else {
     
    939939    private EastNorth calculateBestMovementAndNewNodes(EastNorth mouseEn) {
    940940        EastNorth bestMovement = calculateBestMovement(mouseEn);
    941         EastNorth n1movedEn = initialN1en.add(bestMovement), n2movedEn;
     941        EastNorth n1movedEn = initialN1en.add(bestMovement);
     942        EastNorth n2movedEn;
    942943
    943944        // find out the movement distance, in metres
     
    11581159        double raoffsety = symbolSize*factor*normal.getY();
    11591160
    1160         double cx = center.getX(), cy = center.getY();
     1161        final double cx = center.getX();
     1162        final double cy = center.getY();
    11611163        double k = mirror ? -1 : 1;
    11621164        Point2D ra1 = new Point2D.Double(cx + raoffsetx, cy + raoffsety);
  • trunk/src/org/openstreetmap/josm/actions/search/SearchAction.java

    r19050 r19108  
    398398                    all = ds.allPrimitives();
    399399                } else {
    400                     all = ds.getPrimitives(p -> p.isSelectable()); // Do not use method reference before Java 11!
     400                    all = ds.getPrimitives(IPrimitive::isSelectable);
    401401                }
    402402                final ProgressMonitor subMonitor = getProgressMonitor().createSubTaskMonitor(all.size(), false);
  • trunk/src/org/openstreetmap/josm/data/StructUtils.java

    r18871 r19108  
    267267    }
    268268
    269     @SuppressWarnings("rawtypes")
    270     private static String mapToJson(Map map) {
     269    private static String mapToJson(Map<?, ?> map) {
    271270        StringWriter stringWriter = new StringWriter();
    272271        try (JsonWriter writer = Json.createWriter(stringWriter)) {
    273272            JsonObjectBuilder object = Json.createObjectBuilder();
    274             for (Object o: map.entrySet()) {
    275                 Map.Entry e = (Map.Entry) o;
     273            for (Map.Entry<?, ?> e: map.entrySet()) {
    276274                Object evalue = e.getValue();
    277275                object.add(e.getKey().toString(), evalue.toString());
     
    282280    }
    283281
    284     @SuppressWarnings({ "rawtypes", "unchecked" })
    285     private static Map mapFromJson(String s) {
    286         Map ret;
     282    private static Map<String, String> mapFromJson(String s) {
     283        Map<String, String> ret;
    287284        try (JsonReader reader = Json.createReader(new StringReader(s))) {
    288285            JsonObject object = reader.readObject();
    289             ret = new HashMap(Utils.hashMapInitialCapacity(object.size()));
     286            ret = new HashMap<>(Utils.hashMapInitialCapacity(object.size()));
    290287            for (Map.Entry<String, JsonValue> e: object.entrySet()) {
    291288                JsonValue value = e.getValue();
     
    301298    }
    302299
    303     @SuppressWarnings("rawtypes")
    304     private static String multiMapToJson(MultiMap map) {
     300    private static String multiMapToJson(MultiMap<?, ?> map) {
    305301        StringWriter stringWriter = new StringWriter();
    306302        try (JsonWriter writer = Json.createWriter(stringWriter)) {
    307303            JsonObjectBuilder object = Json.createObjectBuilder();
    308             for (Object o: map.entrySet()) {
    309                 Map.Entry e = (Map.Entry) o;
    310                 Set evalue = (Set) e.getValue();
     304            for (Map.Entry<?, ?> e : map.entrySet()) {
     305                Set<?> evalue = (Set<?>) e.getValue();
    311306                JsonArrayBuilder a = Json.createArrayBuilder();
    312307                for (Object evo: evalue) {
     
    320315    }
    321316
    322     @SuppressWarnings({ "rawtypes", "unchecked" })
    323     private static MultiMap multiMapFromJson(String s) {
    324         MultiMap ret;
     317    private static MultiMap<String, String> multiMapFromJson(String s) {
     318        MultiMap<String, String> ret;
    325319        try (JsonReader reader = Json.createReader(new StringReader(s))) {
    326320            JsonObject object = reader.readObject();
    327             ret = new MultiMap(object.size());
     321            ret = new MultiMap<>(object.size());
    328322            for (Map.Entry<String, JsonValue> e: object.entrySet()) {
    329323                JsonValue value = e.getValue();
  • trunk/src/org/openstreetmap/josm/data/cache/JCSCacheManager.java

    r18434 r19108  
    174174     */
    175175    public static <K, V> CacheAccess<K, V> getCache(String cacheName) {
    176         return getCache(cacheName, DEFAULT_MAX_OBJECTS_IN_MEMORY.get().intValue(), 0, null);
     176        return getCache(cacheName, DEFAULT_MAX_OBJECTS_IN_MEMORY.get(), 0, null);
    177177    }
    178178
  • trunk/src/org/openstreetmap/josm/data/cache/JCSCachedTileLoaderJob.java

    r19050 r19108  
    474474     * Check if the object is loadable. This means, if the data will be parsed, and if this response
    475475     * will finish as successful retrieve.
    476      *
     476     * <p>
    477477     * This simple implementation doesn't load empty response, nor client (4xx) and server (5xx) errors
    478478     *
     
    544544        }
    545545
    546         final boolean noCache = force
    547                 // To remove when switching to Java 11
    548                 // Workaround for https://bugs.openjdk.java.net/browse/JDK-8146450
    549                 || (Utils.getJavaVersion() == 8 && Utils.isRunningJavaWebStart());
     546        final boolean noCache = force;
    550547        urlConn.useCache(!noCache);
    551548
  • trunk/src/org/openstreetmap/josm/data/imagery/vectortile/mapbox/Layer.java

    r18473 r19108  
    9999     * @throws IOException - if an IO error occurs
    100100     */
     101    @SuppressWarnings("PMD.CloseResource") // The resources _are_ closed after use; it just isn't detect with PMD 7.2.x.
    101102    public Layer(Collection<ProtobufRecord> records) throws IOException {
    102103        // Do the unique required fields first
     
    137138        }
    138139        // Cleanup bytes (for memory)
    139         for (ProtobufRecord protobufRecord : records) {
     140        for (ProtobufRecord protobufRecord : records) { // NOSONAR -- this shouldn't be combined since this is a cleanup loop.
    140141            protobufRecord.close();
    141142        }
  • trunk/src/org/openstreetmap/josm/data/imagery/vectortile/mapbox/style/Layers.java

    r19103 r19108  
    307307                    stringBuffer.append(",\"");
    308308                }
    309                 stringBuffer.append(tail);
    310                 stringBuffer.append('"');
     309                stringBuffer.append(tail).append('"');
    311310            }
    312311
  • trunk/src/org/openstreetmap/josm/data/osm/AbstractPrimitive.java

    r19096 r19108  
    310310    }
    311311
    312     @Deprecated
     312    @Deprecated(since = "17749")
    313313    @Override
    314314    public void setTimestamp(Date timestamp) {
     
    326326    }
    327327
    328     @Deprecated
     328    @Deprecated(since = "17749")
    329329    @Override
    330330    public Date getTimestamp() {
     
    648648        if (key == null || Utils.isStripEmpty(key))
    649649            return;
    650         else if (value == null) {
     650        if (value == null) {
    651651            remove(key);
    652652        } else if (keys == null) {
     
    808808
    809809    @Override
     810    @SuppressWarnings("PMD.UseArraysAsList") // See https://github.com/pmd/pmd/issues/5071
    810811    public final Collection<String> keySet() {
    811812        String[] tKeys = this.keys;
  • trunk/src/org/openstreetmap/josm/data/osm/DataSetMerger.java

    r19078 r19108  
    5050    /**
    5151     * constructor
    52      *
     52     * <p>
    5353     * The visitor will merge <code>sourceDataSet</code> onto <code>targetDataSet</code>
    5454     *
     
    6969    /**
    7070     * Merges a primitive onto primitives dataset.
    71      *
     71     * <p>
    7272     * If other.id != 0 it tries to merge it with an corresponding primitive from
    7373     * my dataset with the same id. If this is not possible a conflict is remembered
    7474     * in {@link #conflicts}.
    75      *
     75     * <p>
    7676     * If other.id == 0 (new primitive) it tries to find a primitive in my dataset with id == 0 which
    7777     * is semantically equal. If it finds one it merges its technical attributes onto
     
    239239                newNodes.add(targetNode);
    240240                if (targetNode.isDeleted() && !conflicts.hasConflictForMy(targetNode)) {
    241                     addConflict(new Conflict<OsmPrimitive>(targetNode, sourceNode, true));
     241                    addConflict(new Conflict<>(targetNode, sourceNode, true));
    242242                    targetNode.setDeleted(false);
    243243                }
     
    383383     * Runs the merge operation. Successfully merged {@link OsmPrimitive}s are in
    384384     * {@link #getTargetDataSet()}.
    385      *
     385     * <p>
    386386     * See {@link #getConflicts()} for a map of conflicts after the merge operation.
    387387     */
     
    393393     * Runs the merge operation. Successfully merged {@link OsmPrimitive}s are in
    394394     * {@link #getTargetDataSet()}.
    395      *
     395     * <p>
    396396     * See {@link #getConflicts()} for a map of conflicts after the merge operation.
    397397     * @param progressMonitor The progress monitor
     
    404404     * Runs the merge operation. Successfully merged {@link OsmPrimitive}s are in
    405405     * {@link #getTargetDataSet()}.
    406      *
     406     * <p>
    407407     * See {@link #getConflicts()} for a map of conflicts after the merge operation.
    408408     * @param progressMonitor The progress monitor
  • trunk/src/org/openstreetmap/josm/data/osm/DefaultNameFormatter.java

    r18811 r19108  
    226226            }
    227227            if (node.isLatLonKnown() && Boolean.TRUE.equals(PROPERTY_SHOW_COOR.get())) {
    228                 name.append(" \u200E(");
    229                 name.append(CoordinateFormatManager.getDefaultFormat().toString(node, ", "));
    230                 name.append(")\u200C");
     228                name.append(" \u200E(")
     229                    .append(CoordinateFormatManager.getDefaultFormat().toString(node, ", "))
     230                    .append(")\u200C");
    231231            }
    232232        }
  • trunk/src/org/openstreetmap/josm/data/osm/IPrimitive.java

    r19078 r19108  
    299299     * @deprecated since 17749, use {@link #getInstant} instead
    300300     */
    301     @Deprecated
     301    @Deprecated(since = "17749")
    302302    Date getTimestamp();
    303303
     
    328328     * @deprecated since 17749, use {@link #setInstant} instead
    329329     */
    330     @Deprecated
     330    @Deprecated(since = "17749")
    331331    void setTimestamp(Date timestamp);
    332332
  • trunk/src/org/openstreetmap/josm/data/osm/IRelation.java

    r18814 r19108  
    1313 * @since 4098
    1414 */
    15 public interface IRelation<M extends IRelationMember<?>> extends IPrimitive {
     15public interface IRelation<M extends IRelationMember<? extends IPrimitive>> extends IPrimitive {
    1616
    1717    /**
     
    129129    default Collection<? extends IPrimitive> getIncompleteMembers() {
    130130        return getMembers().stream()
    131                 .filter(rm -> rm.getMember().isIncomplete())
    132                 .map(rm -> rm.getMember())
     131                .map(IRelationMember::getMember)
     132                .filter(IPrimitive::isIncomplete)
    133133                .collect(Collectors.toSet());
    134134    }
  • trunk/src/org/openstreetmap/josm/data/osm/OsmPrimitive.java

    r19078 r19108  
    3333/**
    3434 * The base class for OSM objects ({@link Node}, {@link Way}, {@link Relation}).
    35  *
     35 * <p>
    3636 * It can be created, deleted and uploaded to the OSM-Server.
    37  *
     37 * <p>
    3838 * Although OsmPrimitive is designed as a base class, it is not to be meant to subclass
    3939 * it by any other than from the package {@link org.openstreetmap.josm.data.osm}. The available primitives are a fixed
     
    9696    /**
    9797     * Creates a new primitive for the given id.
    98      *
     98     * <p>
    9999     * If allowNegativeId is set, provided id can be &lt; 0 and will be set to primitive without any processing.
    100100     * If allowNegativeId is not set, then id will have to be 0 (in that case new unique id will be generated) or
     
    124124    /**
    125125     * Creates a new primitive for the given id and version.
    126      *
     126     * <p>
    127127     * If allowNegativeId is set, provided id can be &lt; 0 and will be set to primitive without any processing.
    128128     * If allowNegativeId is not set, then id will have to be 0 (in that case new unique id will be generated) or
    129129     * positive number.
    130      *
     130     * <p>
    131131     * If id is not &gt; 0 version is ignored and set to 0.
    132132     *
     
    225225    /**
    226226     * Sets the id and the version of this primitive if it is known to the OSM API.
    227      *
     227     * <p>
    228228     * Since we know the id and its version it can't be incomplete anymore. incomplete
    229229     * is set to false.
     
    261261     * The id is a new unique id. The version, changeset and timestamp are set to 0.
    262262     * incomplete and deleted are set to false. It's preferred to use copy constructor with clearMetadata set to true instead
    263      *
     263     * <p>
    264264     * <strong>Caution</strong>: Do not use this method on primitives which are already added to a {@link DataSet}.
    265265     *
     
    300300    }
    301301
    302     @Deprecated
     302    @Deprecated(since = "17749", forRemoval = true)
    303303    @Override
    304304    public void setTimestamp(Date timestamp) {
     
    713713
    714714    private void doVisitReferrers(Consumer<OsmPrimitive> visitor) {
    715         if (this.referrers == null)
    716             return;
    717         else if (this.referrers instanceof OsmPrimitive) {
    718             OsmPrimitive ref = (OsmPrimitive) this.referrers;
    719             if (ref.dataSet == dataSet) {
    720                 visitor.accept(ref);
    721             }
    722         } else if (this.referrers instanceof OsmPrimitive[]) {
    723             OsmPrimitive[] refs = (OsmPrimitive[]) this.referrers;
    724             for (OsmPrimitive ref: refs) {
     715        if (this.referrers != null) {
     716            if (this.referrers instanceof OsmPrimitive) {
     717                OsmPrimitive ref = (OsmPrimitive) this.referrers;
    725718                if (ref.dataSet == dataSet) {
    726719                    visitor.accept(ref);
     720                }
     721            } else if (this.referrers instanceof OsmPrimitive[]) {
     722                OsmPrimitive[] refs = (OsmPrimitive[]) this.referrers;
     723                for (OsmPrimitive ref : refs) {
     724                    if (ref.dataSet == dataSet) {
     725                        visitor.accept(ref);
     726                    }
    727727                }
    728728            }
     
    791791    /**
    792792     * Merges the technical and semantic attributes from <code>other</code> onto this.
    793      *
     793     * <p>
    794794     * Both this and other must be new, or both must be assigned an OSM ID. If both this and <code>other</code>
    795795     * have an assigned OSM id, the IDs have to be the same.
  • trunk/src/org/openstreetmap/josm/data/osm/OsmPrimitiveType.java

    r16626 r19108  
    161161     * @since 15820
    162162     */
    163     public final UniqueIdGenerator getIdGenerator() {
     163    public UniqueIdGenerator getIdGenerator() {
    164164        return idGenerator;
    165165    }
  • trunk/src/org/openstreetmap/josm/data/osm/Storage.java

    r18801 r19108  
    1818 * It is useful wherever one would use self-mapping construct like
    1919 * <code>Map&lt;T,T&gt;.put(t,t)</code>, that is, for caches, uniqueness filters or similar.
    20  *
     20 * <p>
    2121 * The semantics of equivalency can be external to the object, using the
    2222 * {@link Hash} interface. The set also supports querying for entries using
     
    400400     */
    401401    public static <O> Hash<O, O> defaultHash() {
    402         return new Hash<O, O>() {
     402        return new Hash<>() {
    403403            @Override
    404404            public int getHashCode(O t) {
  • trunk/src/org/openstreetmap/josm/data/osm/TagMap.java

    r18006 r19108  
    277277                stringBuilder.append(',');
    278278            }
    279             stringBuilder.append(e.getKey());
    280             stringBuilder.append('=');
    281             stringBuilder.append(e.getValue());
     279            stringBuilder.append(e.getKey())
     280                .append('=')
     281                .append(e.getValue());
    282282            first = false;
    283283        }
  • trunk/src/org/openstreetmap/josm/data/osm/history/History.java

    r17903 r19108  
    294294    @Override
    295295    public String toString() {
    296         StringBuilder result = new StringBuilder("History ["
    297                 + (type != null ? ("type=" + type + ", ") : "") + "id=" + id);
     296        StringBuilder result = new StringBuilder("History [");
     297        if (type != null) {
     298            result.append("type=").append(type).append(", ");
     299        }
     300        result.append("id=").append(id);
    298301        if (versions != null) {
    299302            result.append(", versions=\n");
  • trunk/src/org/openstreetmap/josm/data/osm/visitor/paint/RenderBenchmarkCollector.java

    r16542 r19108  
    113113
    114114    public static long getCurrentTimeMilliseconds() {
    115         return System.nanoTime() / 1000000; // System.currentTimeMillis has low accuracy, sometimes multiples of 16ms
     115        return System.nanoTime() / 1_000_000; // System.currentTimeMillis has low accuracy, sometimes multiples of 16ms
    116116    }
    117117
     
    121121     */
    122122    public static class LoggingBenchmark extends RenderBenchmarkCollector.CapturingBenchmark {
    123         private final PrintStream outStream = System.err;
     123        private static final PrintStream outStream = System.err;
    124124        private double circum;
    125125
  • trunk/src/org/openstreetmap/josm/data/projection/CustomProjection.java

    r18494 r19108  
    4141/**
    4242 * Custom projection.
    43  *
     43 * <p>
    4444 * Inspired by PROJ.4 and Proj4J.
    4545 * @since 5072
     
    5959    /**
    6060     * pref String that defines the projection
    61      *
     61     * <p>
    6262     * null means fall back mode (Mercator)
    6363     */
     
    223223     * @param pref the string that defines the custom projection
    224224     */
     225    @SuppressWarnings("PMD.PreserveStackTrace") // PMD 7.2.x doesn't like log + new exception here for some reason.
    225226    public CustomProjection(String name, String code, String pref) {
    226227        this.name = name;
     
    874875    /**
    875876     * Return true, if a geographic coordinate reference system is represented.
    876      *
     877     * <p>
    877878     * I.e. if it returns latitude/longitude values rather than Cartesian
    878879     * east/north coordinates on a flat surface.
  • trunk/src/org/openstreetmap/josm/data/projection/datum/NTV2GridShiftFile.java

    r17374 r19108  
    171171        int topLevelCount = 0;
    172172        Map<String, List<NTV2SubGrid>> subGridMap = new HashMap<>();
    173         for (int i = 0; i < subGrid.length; i++) {
    174             if ("NONE".equalsIgnoreCase(subGrid[i].getParentSubGridName())) {
     173        for (NTV2SubGrid ntv2SubGrid : subGrid) {
     174            if ("NONE".equalsIgnoreCase(ntv2SubGrid.getParentSubGridName())) {
    175175                topLevelCount++;
    176176            }
    177             subGridMap.put(subGrid[i].getSubGridName(), new ArrayList<NTV2SubGrid>());
     177            subGridMap.put(ntv2SubGrid.getSubGridName(), new ArrayList<>());
    178178        }
    179179        NTV2SubGrid[] topLevelSubGrid = new NTV2SubGrid[topLevelCount];
    180180        topLevelCount = 0;
    181         for (int i = 0; i < subGrid.length; i++) {
    182             if ("NONE".equalsIgnoreCase(subGrid[i].getParentSubGridName())) {
    183                 topLevelSubGrid[topLevelCount++] = subGrid[i];
     181        for (NTV2SubGrid ntv2SubGrid : subGrid) {
     182            if ("NONE".equalsIgnoreCase(ntv2SubGrid.getParentSubGridName())) {
     183                topLevelSubGrid[topLevelCount++] = ntv2SubGrid;
    184184            } else {
    185                 List<NTV2SubGrid> parent = subGridMap.get(subGrid[i].getParentSubGridName());
    186                 parent.add(subGrid[i]);
     185                List<NTV2SubGrid> parent = subGridMap.get(ntv2SubGrid.getParentSubGridName());
     186                parent.add(ntv2SubGrid);
    187187            }
    188188        }
    189189        NTV2SubGrid[] nullArray = new NTV2SubGrid[0];
    190         for (int i = 0; i < subGrid.length; i++) {
    191             List<NTV2SubGrid> subSubGrids = subGridMap.get(subGrid[i].getSubGridName());
     190        for (NTV2SubGrid ntv2SubGrid : subGrid) {
     191            List<NTV2SubGrid> subSubGrids = subGridMap.get(ntv2SubGrid.getSubGridName());
    192192            if (!subSubGrids.isEmpty()) {
    193193                NTV2SubGrid[] subGridArray = subSubGrids.toArray(nullArray);
    194                 subGrid[i].setSubGridArray(subGridArray);
     194                ntv2SubGrid.setSubGridArray(subGridArray);
    195195            }
    196196        }
  • trunk/src/org/openstreetmap/josm/data/validation/ValidatorCLI.java

    r19077 r19108  
    281281                // The first writeErrors catches anything that was written, for whatever reason. This is probably never
    282282                // going to be called.
    283                 final var validationTask = new ValidationTask(errors -> writeErrors(geoJSONMapRouletteWriter, fileOutputStream, errors),
     283                final ValidationTask validationTask =
     284                        new ValidationTask(errors -> writeErrors(geoJSONMapRouletteWriter, fileOutputStream, errors),
    284285                        progressMonitorFactory.get(), OsmValidator.getEnabledTests(false),
    285286                        dataSet.allPrimitives(), Collections.emptyList(), false);
  • trunk/src/org/openstreetmap/josm/data/validation/tests/CrossingWays.java

    r18963 r19108  
    342342                if (this instanceof CrossingWays.Boundaries) {
    343343                    List<Relation> relations = ds.searchRelations(wt.getBBox()).stream()
    344                             .filter(p -> isPrimitiveUsable(p)).collect(Collectors.toList());
     344                            .filter(this::isPrimitiveUsable).collect(Collectors.toList());
    345345                    for (Relation r: relations) {
    346346                        for (Way w : r.getMemberPrimitives(Way.class)) {
     
    360360
    361361    static boolean isWaterArea(OsmPrimitive w) {
    362         return w.hasTag("natural", "water") || w.hasTag("waterway", "riverbank") || w.hasTag(LANDUSE, "reservoir");
     362        return w.hasTag("natural", "water") || w.hasTag(WATERWAY, "riverbank") || w.hasTag(LANDUSE, "reservoir");
    363363    }
    364364
  • trunk/src/org/openstreetmap/josm/data/validation/tests/DuplicateNode.java

    r17665 r19108  
    8080            LatLon coorK = getLatLon(k);
    8181            LatLon coorT = getLatLon(t);
    82             return coorK == coorT || (coorK != null && coorT != null && coorK.equals(coorT));
     82            return Objects.equals(coorK, coorT);
    8383        }
    8484
  • trunk/src/org/openstreetmap/josm/data/validation/tests/OverlappingWays.java

    r17896 r19108  
    2121import java.util.stream.Collectors;
    2222
     23import org.openstreetmap.josm.data.osm.IWaySegment;
    2324import org.openstreetmap.josm.data.osm.Node;
    2425import org.openstreetmap.josm.data.osm.OsmPrimitive;
     
    122123            return;
    123124
    124         List<Way> currentWays = duplicated.stream().map(ws -> ws.getWay()).collect(Collectors.toList());
     125        List<Way> currentWays = duplicated.stream().map(IWaySegment::getWay).collect(Collectors.toList());
    125126        Collection<WaySegment> highlight;
    126127        if ((highlight = seenWays.get(currentWays)) != null) {
  • trunk/src/org/openstreetmap/josm/data/validation/tests/WayConnectedToArea.java

    r16445 r19108  
    5252
    5353    private void testForError(Way w, Node wayNode, OsmPrimitive p) {
    54         if (wayNode.isOutsideDownloadArea()
    55                 || wayNode.getReferrers().stream().anyMatch(p1 -> p1.hasTag("route", "ferry"))) {
    56             return;
    57         } else if (isArea(p)) {
    58             addPossibleError(w, wayNode, p, p);
    59         } else {
    60             p.referrers(Relation.class)
    61                     .filter(r -> r.isMultipolygon() && isArea(r))
    62                     .findFirst()
    63                     .ifPresent(r -> addPossibleError(w, wayNode, p, r));
     54        if (!wayNode.isOutsideDownloadArea()
     55                && wayNode.getReferrers().stream().noneMatch(p1 -> p1.hasTag("route", "ferry"))) {
     56            if (isArea(p)) {
     57                addPossibleError(w, wayNode, p, p);
     58            } else {
     59                p.referrers(Relation.class)
     60                        .filter(r -> r.isMultipolygon() && isArea(r))
     61                        .findFirst()
     62                        .ifPresent(r -> addPossibleError(w, wayNode, p, r));
     63            }
    6464        }
    6565    }
  • trunk/src/org/openstreetmap/josm/data/validation/tests/WronglyOrderedWays.java

    r13849 r19108  
    3737
    3838        String natural = w.get("natural");
    39         if (natural == null) {
    40             return;
    41         } else if ("coastline".equals(natural) && Geometry.isClockwise(w)) {
    42             reportError(w, tr("Reversed coastline: land not on left side"), WRONGLY_ORDERED_COAST);
    43         } else if ("land".equals(natural) && Geometry.isClockwise(w)) {
    44             reportError(w, tr("Reversed land: land not on left side"), WRONGLY_ORDERED_LAND);
     39        if (natural != null) {
     40            if ("coastline".equals(natural) && Geometry.isClockwise(w)) {
     41                reportError(w, tr("Reversed coastline: land not on left side"), WRONGLY_ORDERED_COAST);
     42            } else if ("land".equals(natural) && Geometry.isClockwise(w)) {
     43                reportError(w, tr("Reversed land: land not on left side"), WRONGLY_ORDERED_LAND);
     44            }
    4545        }
    4646    }
  • trunk/src/org/openstreetmap/josm/gui/MapStatus.java

    r18815 r19108  
    1414import java.awt.Font;
    1515import java.awt.GraphicsEnvironment;
     16import java.awt.GridBagConstraints;
    1617import java.awt.GridBagLayout;
    1718import java.awt.MouseInfo;
     
    5657import javax.swing.Popup;
    5758import javax.swing.PopupFactory;
     59import javax.swing.SwingConstants;
    5860import javax.swing.UIManager;
    5961import javax.swing.event.PopupMenuEvent;
     
    112114 * It keeps a status line below the map up to date and displays some tooltip
    113115 * information if the user hold the mouse long enough at some point.
    114  *
     116 * <p>
    115117 * All this is done in background to not disturb other processes.
    116  *
     118 * <p>
    117119 * The background thread does not alter any data of the map (read only thread).
    118120 * Also it is rather fail safe. In case of some error in the data, it just does
     
    316318            public void run() {
    317319                // Freeze display when holding down CTRL
    318                 if ((ms.modifiers & MouseEvent.CTRL_DOWN_MASK) != 0) {
     320                if ((ms.modifiers & InputEvent.CTRL_DOWN_MASK) != 0) {
    319321                    // update the information popup's labels though, because the selection might have changed from the outside
    320322                    popupUpdateLabels();
     
    327329                boolean mouseNotMoved = oldMousePos != null && oldMousePos.equals(ms.mousePos);
    328330                boolean isAtOldPosition = mouseNotMoved && popup != null;
    329                 boolean middleMouseDown = (ms.modifiers & MouseEvent.BUTTON2_DOWN_MASK) != 0;
     331                boolean middleMouseDown = (ms.modifiers & InputEvent.BUTTON2_DOWN_MASK) != 0;
    330332
    331333                DataSet ds = mv.getLayerManager().getActiveDataSet();
     
    361363                                        "Hold CTRL to select directly from this list with the mouse.<hr>")+"</html>",
    362364                                        null,
    363                                         JLabel.HORIZONTAL
     365                                        SwingConstants.CENTER
    364366                                );
    365                         lbl.setHorizontalAlignment(JLabel.LEADING);
     367                        lbl.setHorizontalAlignment(SwingConstants.LEADING);
    366368                        c.add(lbl, GBC.eol().insets(2, 0, 2, 0));
    367369
     
    379381                            JLabel l = popupBuildPrimitiveLabels(osm);
    380382                            lbls.add(l);
    381                             c.add(l, GBC.eol().fill(GBC.HORIZONTAL).insets(2, 0, 2, 2));
     383                            c.add(l, GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(2, 0, 2, 2));
    382384                        }
    383385
     
    537539            // pressed. Cannot use "setSelected()" because it will cause a
    538540            // fireSelectionChanged event which is unnecessary at this point.
    539             if ((mods & MouseEvent.SHIFT_DOWN_MASK) == 0) {
     541            if ((mods & InputEvent.SHIFT_DOWN_MASK) == 0) {
    540542                ds.clearSelection();
    541543            }
     
    648650                    "<html>" + text.toString() + "</html>",
    649651                    ImageProvider.get(osm.getDisplayType()),
    650                     JLabel.HORIZONTAL
     652                    SwingConstants.HORIZONTAL
    651653                    ) {
    652654                // This is necessary so the label updates its colors when the
     
    661663            popupSetLabelColors(l, osm);
    662664            l.setFont(l.getFont().deriveFont(Font.PLAIN));
    663             l.setVerticalTextPosition(JLabel.TOP);
    664             l.setHorizontalAlignment(JLabel.LEADING);
     665            l.setVerticalTextPosition(SwingConstants.TOP);
     666            l.setHorizontalAlignment(SwingConstants.LEADING);
    665667            l.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    666668            l.addMouseListener(new MouseAdapter() {
     
    902904                    return;
    903905                // Do not update the view if ctrl or right button is pressed.
    904                 if ((e.getModifiersEx() & (MouseEvent.CTRL_DOWN_MASK | MouseEvent.BUTTON3_DOWN_MASK)) == 0) {
     906                if ((e.getModifiersEx() & (InputEvent.CTRL_DOWN_MASK | InputEvent.BUTTON3_DOWN_MASK)) == 0) {
    905907                    updateLatLonText(e.getX(), e.getY());
    906908                }
     
    951953        helpText.setEditable(false);
    952954        add(nameText, GBC.std().insets(3, 0, 0, 0));
    953         add(helpText, GBC.std().insets(3, 0, 0, 0).fill(GBC.HORIZONTAL));
     955        add(helpText, GBC.std().insets(3, 0, 0, 0).fill(GridBagConstraints.HORIZONTAL));
    954956
    955957        progressBar.setMaximum(PleaseWaitProgressMonitor.PROGRESS_BAR_MAX);
     
    12261228            }
    12271229        }
    1228         setDist(new SubclassFilteredCollection<OsmPrimitive, Way>(newSelection, Way.class::isInstance));
     1230        setDist(new SubclassFilteredCollection<>(newSelection, Way.class::isInstance));
    12291231    }
    12301232
  • trunk/src/org/openstreetmap/josm/gui/MapView.java

    r19080 r19108  
    127127        private boolean ignoreRepaint;
    128128
    129         private final Set<MapViewPaintable> invalidatedLayers = Collections.newSetFromMap(new IdentityHashMap<MapViewPaintable, Boolean>());
     129        private final Set<MapViewPaintable> invalidatedLayers = Collections.newSetFromMap(new IdentityHashMap<>());
    130130
    131131        @Override
     
    176176         */
    177177        private synchronized Set<MapViewPaintable> collectInvalidatedLayers() {
    178             Set<MapViewPaintable> layers = Collections.newSetFromMap(new IdentityHashMap<MapViewPaintable, Boolean>());
     178            Set<MapViewPaintable> layers = Collections.newSetFromMap(new IdentityHashMap<>());
    179179            layers.addAll(invalidatedLayers);
    180180            invalidatedLayers.clear();
     
    299299        });
    300300
    301         setFocusTraversalKeysEnabled(!Shortcut.findShortcut(KeyEvent.VK_TAB, 0).isPresent());
     301        setFocusTraversalKeysEnabled(Shortcut.findShortcut(KeyEvent.VK_TAB, 0).isEmpty());
    302302
    303303        mapNavigationComponents = getMapNavigationComponents(this);
     
    321321        zoomSlider.setSize(size);
    322322        zoomSlider.setLocation(3, 0);
    323         zoomSlider.setFocusTraversalKeysEnabled(!Shortcut.findShortcut(KeyEvent.VK_TAB, 0).isPresent());
     323        zoomSlider.setFocusTraversalKeysEnabled(Shortcut.findShortcut(KeyEvent.VK_TAB, 0).isEmpty());
    324324
    325325        MapScaler scaler = new MapScaler(forMapView);
  • trunk/test/unit/org/openstreetmap/josm/data/projection/ProjectionRegressionTest.java

    r19050 r19108  
    2121import java.util.stream.Collectors;
    2222
    23 import org.junit.jupiter.api.Assumptions;
    2423import org.junit.jupiter.api.Test;
    2524import org.openstreetmap.josm.JOSMFixture;
     
    2928import org.openstreetmap.josm.testutils.annotations.ProjectionNadGrids;
    3029import org.openstreetmap.josm.tools.Pair;
    31 import org.openstreetmap.josm.tools.Platform;
    32 import org.openstreetmap.josm.tools.Utils;
    3330
    3431/**
     
    144141    @Test
    145142    void testNonRegression() throws IOException {
    146         // Disable on Github Windows runners + Java 8, minor differences appeared around 2021-07-20
    147         Assumptions.assumeFalse(
    148                 Utils.getJavaVersion() == 8
    149                 && Platform.determinePlatform() == Platform.WINDOWS
    150                 && System.getenv("GITHUB_WORKFLOW") != null);
    151143        List<TestData> allData = readData();
    152144        Set<String> dataCodes = allData.stream().map(data -> data.code).collect(Collectors.toSet());
     
    160152        }
    161153
    162         final boolean java9 = Utils.getJavaVersion() >= 9;
    163154        for (TestData data : allData) {
    164155            Projection proj = Projections.getProjectionByCode(data.code);
     
    169160            EastNorth en = proj.latlon2eastNorth(data.ll);
    170161            LatLon ll2 = proj.eastNorth2latlon(data.en);
    171             if (!(java9 ? equalsJava9(en, data.en) : en.equals(data.en))) {
     162            if (!equalsJava9(en, data.en)) {
    172163                String error = String.format("%s (%s): Projecting latlon(%s,%s):%n" +
    173164                        "        expected: eastnorth(%s,%s),%n" +
     
    176167                fail.append(error);
    177168            }
    178             if (!(java9 ? equalsJava9(ll2, data.ll2) : ll2.equals(data.ll2))) {
     169            if (!equalsJava9(ll2, data.ll2)) {
    179170                String error = String.format("%s (%s): Inverse projecting eastnorth(%s,%s):%n" +
    180171                        "        expected: latlon(%s,%s),%n" +
Note: See TracChangeset for help on using the changeset viewer.