From 6677750662b0b0b89534f44638c66de8fceb1422 Mon Sep 17 00:00:00 2001 From: "taylor.smock" Date: Fri, 19 Apr 2024 14:21:11 +0000 Subject: [PATCH] Dependency updates ivy.xml * org.eclipse.parsson:parsson: 1.1.5 -> 1.1.6 * org.apache.commons:commons-compress: 1.25.0 -> 1.26.1 * Note: This deprecated some functions * ch.poole:OpeningHoursParser: 0.28.1 -> 0.28.2 * org.jacoco:org.jacoco.ant: 0.8.11 -> 0.8.12 * com.github.spotbugs:spotbugs-annotations: 4.8.3 -> 4.8.4 * com.github.tomakehurst:wiremock: 2.35.0 -> 3.0.1 * io.github.classgraph:classgraph: 4.8.165 -> 4.8.171 * nl.jqno.equalsverifier:equalsverifier: 3.15.6 -> 3.16.1 * org.awaitility:awaitility: 4.2.0 -> 4.2.1 tools/ivy.xml * com.puppycrawl.tools:checkstyle: 9.3 -> 10.15.0 * com.github.spotbugs:spotbugs: 4.8.3 -> 4.8.4 * com.google.errorprone: 2.(10.0|24.1) -> 2.26.1 * net.sourceforge.pmd:pmd was not updated to 7.0.0 due to a significant number of false positives. There were some additional changes to cleanup new warnings and remove some additional Java 8 files. There are more warnings that need to be cleaned up. git-svn-id: https://josm.openstreetmap.de/svn/trunk@19048 0c6e7542-c601-0410-84e7-c038aed88b3b --- build.xml | 3 +- ivy.xml | 24 +-- ivysettings.xml | 3 - .../josm/actions/AddImageryLayerAction.java | 64 +++--- .../josm/actions/AutoScaleAction.java | 17 +- .../actions/ChangesetManagerToggleAction.java | 2 +- .../josm/actions/DownloadOsmInViewAction.java | 4 +- .../josm/actions/JoinAreasAction.java | 154 +++++++------- .../josm/actions/SplitWayAction.java | 27 +-- .../josm/data/osm/search/SearchCompiler.java | 35 ++-- .../josm/data/validation/ValidatorCLI.java | 52 +++-- .../dialogs/relation/sort/RelationSorter.java | 10 +- .../josm/gui/io/UploadPrimitivesTask.java | 14 +- .../geoimage/CorrelateGpxWithImages.java | 96 +++++---- .../josm/gui/layer/geoimage/RemoteEntry.java | 6 +- .../LabelCompositionStrategy.java | 26 ++- .../josm/gui/widgets/JosmTextField.java | 13 +- src/org/openstreetmap/josm/io/NoteReader.java | 16 +- .../openstreetmap/josm/io/OsmPbfReader.java | 150 +++++++------- .../josm/tools/ImageResizeMode.java | 5 +- src/org/openstreetmap/josm/tools/Utils.java | 189 +++++++++--------- tools/eclipse/JOSM (Java 8).launch | 18 -- tools/ivy.xml | 11 +- 23 files changed, 454 insertions(+), 485 deletions(-) delete mode 100644 tools/eclipse/JOSM (Java 8).launch diff --git a/build.xml b/build.xml index d30c9034200..fbb8779ea5a 100644 --- a/build.xml +++ b/build.xml @@ -905,7 +905,7 @@ Build-Date: ${build.tstamp} - + ${pmd.dir}/josm-ruleset.xml @@ -917,6 +917,7 @@ Build-Date: ${build.tstamp} + diff --git a/ivy.xml b/ivy.xml index bba30a1d32b..c06d87065ed 100644 --- a/ivy.xml +++ b/ivy.xml @@ -26,9 +26,9 @@ - + - + @@ -36,7 +36,7 @@ - + @@ -44,9 +44,9 @@ - + - + @@ -54,20 +54,20 @@ - + - + - + - - + + @@ -76,8 +76,8 @@ - + - + diff --git a/ivysettings.xml b/ivysettings.xml index 22e66b609bd..6e9cdfcff9f 100644 --- a/ivysettings.xml +++ b/ivysettings.xml @@ -5,7 +5,4 @@ - - - diff --git a/src/org/openstreetmap/josm/actions/AddImageryLayerAction.java b/src/org/openstreetmap/josm/actions/AddImageryLayerAction.java index 7465565f3f0..b011489d69d 100644 --- a/src/org/openstreetmap/josm/actions/AddImageryLayerAction.java +++ b/src/org/openstreetmap/josm/actions/AddImageryLayerAction.java @@ -6,6 +6,7 @@ import java.awt.Dimension; import java.awt.GraphicsEnvironment; +import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.io.IOException; @@ -13,7 +14,6 @@ import java.nio.file.InvalidPathException; import java.time.Year; import java.time.ZoneOffset; -import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.function.Function; @@ -25,8 +25,6 @@ import javax.swing.JPanel; import javax.swing.JScrollPane; -import org.openstreetmap.josm.data.coor.LatLon; -import org.openstreetmap.josm.data.imagery.DefaultLayer; import org.openstreetmap.josm.data.imagery.ImageryInfo; import org.openstreetmap.josm.data.imagery.ImageryInfo.ImageryType; import org.openstreetmap.josm.data.imagery.LayerDetails; @@ -61,11 +59,11 @@ public class AddImageryLayerAction extends JosmAction implements AdaptableAction static class SelectWmsLayersDialog extends ExtendedDialog { SelectWmsLayersDialog(WMSLayerTree tree, JComboBox formats) { super(MainApplication.getMainFrame(), tr("Select WMS layers"), tr("Add layers"), tr("Cancel")); - final JScrollPane scrollPane = new JScrollPane(tree.getLayerTree()); + final var scrollPane = new JScrollPane(tree.getLayerTree()); scrollPane.setPreferredSize(new Dimension(400, 400)); - final JPanel panel = new JPanel(new GridBagLayout()); + final var panel = new JPanel(new GridBagLayout()); panel.add(scrollPane, GBC.eol().fill()); - panel.add(formats, GBC.eol().fill(GBC.HORIZONTAL)); + panel.add(formats, GBC.eol().fill(GridBagConstraints.HORIZONTAL)); setContent(panel); } } @@ -83,7 +81,7 @@ public AddImageryLayerAction(ImageryInfo info) { installAdapters(); // change toolbar icon from if specified - String icon = info.getIcon(); + var icon = info.getIcon(); if (icon != null) { new ImageProvider(icon).setOptional(true).getResourceAsync(result -> { if (result != null) { @@ -102,10 +100,10 @@ public AddImageryLayerAction(ImageryInfo info) { private static ImageryInfo convertImagery(ImageryInfo info) { try { if (info.getUrl() != null && info.getUrl().contains("{time}")) { - final String instant = Year.now(ZoneOffset.UTC).atDay(1).atStartOfDay(ZoneOffset.UTC).toInstant().toString(); - final String example = String.join("/", instant, instant); - final String initialSelectionValue = info.getDate() != null ? info.getDate() : example; - final String userDate = JOptionPane.showInputDialog(MainApplication.getMainFrame(), + final var instant = Year.now(ZoneOffset.UTC).atDay(1).atStartOfDay(ZoneOffset.UTC).toInstant().toString(); + final var example = String.join("/", instant, instant); + final var initialSelectionValue = info.getDate() != null ? info.getDate() : example; + final var userDate = JOptionPane.showInputDialog(MainApplication.getMainFrame(), tr("Time filter for \"{0}\" such as \"{1}\"", info.getName(), example), initialSelectionValue); if (userDate == null) { @@ -114,7 +112,7 @@ private static ImageryInfo convertImagery(ImageryInfo info) { info.setDate(userDate); // TODO persist new {time} value (via ImageryLayerInfo.save?) } - switch(info.getImageryType()) { + switch (info.getImageryType()) { case WMS_ENDPOINT: // convert to WMS type if (Utils.isEmpty(info.getDefaultLayers())) { @@ -125,12 +123,12 @@ private static ImageryInfo convertImagery(ImageryInfo info) { case WMTS: // specify which layer to use if (Utils.isEmpty(info.getDefaultLayers())) { - WMTSTileSource tileSource = new WMTSTileSource(info); - DefaultLayer layerId = tileSource.userSelectLayer(); + var tileSource = new WMTSTileSource(info); + var layerId = tileSource.userSelectLayer(); if (layerId != null) { - ImageryInfo copy = new ImageryInfo(info); + var copy = new ImageryInfo(info); copy.setDefaultLayers(Collections.singletonList(layerId)); - String layerName = tileSource.getLayers().stream() + var layerName = tileSource.getLayers().stream() .filter(x -> x.getIdentifier().equals(layerId.getLayerName())) .map(Layer::getUserTitle) .findFirst() @@ -164,7 +162,7 @@ public void actionPerformed(ActionEvent e) { if (!isEnabled()) return; ImageryLayer layer = null; try { - final ImageryInfo infoToAdd = convertImagery(info); + final var infoToAdd = convertImagery(info); if (infoToAdd != null) { layer = ImageryLayer.create(infoToAdd); getLayerManager().addLayer(layer); @@ -206,16 +204,16 @@ public LayerSelection(List layers, String format, boolean transpar } private static LayerSelection askToSelectLayers(WMSImagery wms) { - final WMSLayerTree tree = new WMSLayerTree(); + final var tree = new WMSLayerTree(); - Collection wmsFormats = wms.getFormats(); - final JComboBox formats = new JComboBox<>(wmsFormats.toArray(new String[0])); + var wmsFormats = wms.getFormats(); + final var formats = new JComboBox(wmsFormats.toArray(new String[0])); formats.setSelectedItem(wms.getPreferredFormat()); formats.setToolTipText(tr("Select image format for WMS layer")); - JCheckBox checkBounds = new JCheckBox(tr("Show only layers for current view"), true); + var checkBounds = new JCheckBox(tr("Show only layers for current view"), true); Runnable updateTree = () -> { - LatLon latLon = checkBounds.isSelected() && MainApplication.isDisplayingMapView() + var latLon = checkBounds.isSelected() && MainApplication.isDisplayingMapView() ? MainApplication.getMap().mapView.getProjection().eastNorth2latlon(MainApplication.getMap().mapView.getCenter()) : null; tree.setCheckBounds(latLon); @@ -226,14 +224,14 @@ private static LayerSelection askToSelectLayers(WMSImagery wms) { updateTree.run(); if (!GraphicsEnvironment.isHeadless()) { - ExtendedDialog dialog = new ExtendedDialog(MainApplication.getMainFrame(), + var dialog = new ExtendedDialog(MainApplication.getMainFrame(), tr("Select WMS layers"), tr("Add layers"), tr("Cancel")); - final JScrollPane scrollPane = new JScrollPane(tree.getLayerTree()); + final var scrollPane = new JScrollPane(tree.getLayerTree()); scrollPane.setPreferredSize(new Dimension(400, 400)); - final JPanel panel = new JPanel(new GridBagLayout()); + final var panel = new JPanel(new GridBagLayout()); panel.add(scrollPane, GBC.eol().fill()); - panel.add(checkBounds, GBC.eol().fill(GBC.HORIZONTAL)); - panel.add(formats, GBC.eol().fill(GBC.HORIZONTAL)); + panel.add(checkBounds, GBC.eol().fill(GridBagConstraints.HORIZONTAL)); + panel.add(formats, GBC.eol().fill(GridBagConstraints.HORIZONTAL)); dialog.setContent(panel); if (dialog.showDialog().getValue() != 1) { @@ -282,25 +280,25 @@ public static ImageryInfo getWMSLayerInfo(ImageryInfo info, Function) null, selection.format, selection.transparent ); - String selectedLayers = selection.layers.stream() + var selectedLayers = selection.layers.stream() .map(LayerDetails::getName) .collect(Collectors.joining(", ")); // Use full copy of original Imagery info to copy all attributes. Only overwrite what's different - ImageryInfo ret = new ImageryInfo(info); + var ret = new ImageryInfo(info); ret.setUrl(url); ret.setImageryType(ImageryType.WMS); ret.setName(info.getName() + " - " + selectedLayers); diff --git a/src/org/openstreetmap/josm/actions/AutoScaleAction.java b/src/org/openstreetmap/josm/actions/AutoScaleAction.java index 7e92317caa4..b4dd5184c5d 100644 --- a/src/org/openstreetmap/josm/actions/AutoScaleAction.java +++ b/src/org/openstreetmap/josm/actions/AutoScaleAction.java @@ -7,7 +7,6 @@ import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; -import java.awt.geom.Area; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; @@ -22,7 +21,6 @@ import org.openstreetmap.josm.data.Bounds; import org.openstreetmap.josm.data.DataSource; import org.openstreetmap.josm.data.conflict.Conflict; -import org.openstreetmap.josm.data.osm.DataSet; import org.openstreetmap.josm.data.osm.IPrimitive; import org.openstreetmap.josm.data.osm.OsmData; import org.openstreetmap.josm.data.osm.OsmPrimitive; @@ -33,7 +31,6 @@ import org.openstreetmap.josm.gui.MapFrameListener; import org.openstreetmap.josm.gui.MapView; import org.openstreetmap.josm.gui.NavigatableComponent.ZoomChangeListener; -import org.openstreetmap.josm.gui.dialogs.ConflictDialog; import org.openstreetmap.josm.gui.dialogs.LayerListDialog; import org.openstreetmap.josm.gui.dialogs.ValidatorDialog.ValidatorBoundingXYVisitor; import org.openstreetmap.josm.gui.layer.Layer; @@ -145,7 +142,7 @@ public static void zoomToSelection() { * @param sel The primitives to zoom to, e.g. the current selection. */ public static void zoomTo(Collection sel) { - BoundingXYVisitor bboxCalculator = new BoundingXYVisitor(); + final var bboxCalculator = new BoundingXYVisitor(); bboxCalculator.computeBoundingBox(sel); if (bboxCalculator.getBounds() != null) { MainApplication.getMap().mapView.zoomTo(bboxCalculator); @@ -243,7 +240,7 @@ public AutoScaleAction(final AutoScaleMode mode) { */ public void autoScale() { if (MainApplication.isDisplayingMapView()) { - MapView mapView = MainApplication.getMap().mapView; + final var mapView = MainApplication.getMap().mapView; switch (mode) { case PREVIOUS: mapView.zoomPrevious(); @@ -311,7 +308,7 @@ private static void modeData(BoundingXYVisitor v) { private void modeLayer(BoundingXYVisitor v) { // try to zoom to the first selected layer - Layer l = getFirstSelectedLayer(); + final var l = getFirstSelectedLayer(); if (l == null) return; l.visitBoundingBox(v); @@ -326,7 +323,7 @@ private void modeSelectionOrConflict(BoundingXYVisitor v) { sel.addAll(dataSet.getSelected()); } } else { - ConflictDialog conflictDialog = MainApplication.getMap().conflictDialog; + final var conflictDialog = MainApplication.getMap().conflictDialog; Conflict c = conflictDialog.getSelectedConflict(); if (c != null) { sel.add(c.getMy()); @@ -358,7 +355,7 @@ private void modeDownload() { lastZoomTime = -1; } Bounds bbox = null; - final DataSet dataset = getLayerManager().getActiveDataSet(); + final var dataset = getLayerManager().getActiveDataSet(); if (dataset != null) { List dataSources = new ArrayList<>(dataset.getDataSources()); int s = dataSources.size(); @@ -371,7 +368,7 @@ private void modeDownload() { bbox = dataSources.get(lastZoomArea).bounds; } else { lastZoomArea = -1; - Area sourceArea = getLayerManager().getActiveDataSet().getDataSourceArea(); + final var sourceArea = getLayerManager().getActiveDataSet().getDataSourceArea(); if (sourceArea != null) { bbox = new Bounds(sourceArea.getBounds2D()); } @@ -438,7 +435,7 @@ protected final void installAdapters() { /** * Adapter for zoom change events */ - private class ZoomChangeAdapter implements ZoomChangeListener { + private final class ZoomChangeAdapter implements ZoomChangeListener { @Override public void zoomChanged() { updateEnabledState(); diff --git a/src/org/openstreetmap/josm/actions/ChangesetManagerToggleAction.java b/src/org/openstreetmap/josm/actions/ChangesetManagerToggleAction.java index 6d1387d735c..aef8c62c1a3 100644 --- a/src/org/openstreetmap/josm/actions/ChangesetManagerToggleAction.java +++ b/src/org/openstreetmap/josm/actions/ChangesetManagerToggleAction.java @@ -48,7 +48,7 @@ public void actionPerformed(ActionEvent e) { } } - private class ChangesetCacheManagerClosedHandler extends WindowAdapter { + private final class ChangesetCacheManagerClosedHandler extends WindowAdapter { @Override public void windowClosed(WindowEvent e) { setSelected(false); diff --git a/src/org/openstreetmap/josm/actions/DownloadOsmInViewAction.java b/src/org/openstreetmap/josm/actions/DownloadOsmInViewAction.java index baf75f358bd..34ab6838c6f 100644 --- a/src/org/openstreetmap/josm/actions/DownloadOsmInViewAction.java +++ b/src/org/openstreetmap/josm/actions/DownloadOsmInViewAction.java @@ -36,8 +36,8 @@ public DownloadOsmInViewAction() { @Override public void actionPerformed(ActionEvent e) { - final Bounds bounds = MainApplication.getMap().mapView.getRealBounds(); - DownloadOsmInViewTask task = new DownloadOsmInViewTask(); + final var bounds = MainApplication.getMap().mapView.getRealBounds(); + final var task = new DownloadOsmInViewTask(); task.setZoomAfterDownload(false); Future future = task.download(bounds); MainApplication.worker.submit(new PostDownloadHandler(task, future)); diff --git a/src/org/openstreetmap/josm/actions/JoinAreasAction.java b/src/org/openstreetmap/josm/actions/JoinAreasAction.java index a4f648e1f26..4d605faf373 100644 --- a/src/org/openstreetmap/josm/actions/JoinAreasAction.java +++ b/src/org/openstreetmap/josm/actions/JoinAreasAction.java @@ -209,11 +209,11 @@ public AssembledPolygon(List boundary) { } public List getNodes() { - List nodes = new ArrayList<>(); + final var nodes = new ArrayList(); for (WayInPolygon way : this.ways) { //do not add the last node as it will be repeated in the next way if (way.insideToTheRight) { - for (int pos = 0; pos < way.way.getNodesCount() - 1; pos++) { + for (var pos = 0; pos < way.way.getNodesCount() - 1; pos++) { nodes.add(way.way.getNode(pos)); } } else { @@ -342,9 +342,9 @@ private Node getPrevNode() { * @return oriented angle (N1N2, N1N3) in range [0; 2*Math.PI[ */ private static double getAngle(Node n1, Node n2, Node n3) { - EastNorth en1 = n1.getEastNorth(); - EastNorth en2 = n2.getEastNorth(); - EastNorth en3 = n3.getEastNorth(); + final var en1 = n1.getEastNorth(); + final var en2 = n2.getEastNorth(); + final var en3 = n3.getEastNorth(); double angle = Math.atan2(en3.getY() - en1.getY(), en3.getX() - en1.getX()) - Math.atan2(en2.getY() - en1.getY(), en2.getX() - en1.getX()); while (angle >= 2*Math.PI) { @@ -361,8 +361,8 @@ private static double getAngle(Node n1, Node n2, Node n3) { * @return The next way. */ public WayInPolygon walk() { - Node headNode = getHeadNode(); - Node prevNode = getPrevNode(); + final var headNode = getHeadNode(); + final var prevNode = getPrevNode(); double headAngle = Math.atan2(headNode.getEastNorth().east() - prevNode.getEastNorth().east(), headNode.getEastNorth().north() - prevNode.getEastNorth().north()); @@ -370,7 +370,7 @@ public WayInPolygon walk() { //find best next way WayInPolygon bestWay = null; - boolean bestWayReverse = false; + var bestWayReverse = false; for (WayInPolygon way : availableWays) { Node nextNode; @@ -417,11 +417,11 @@ public WayInPolygon walk() { * @return left way or null if none found */ public WayInPolygon leftComingWay() { - Node headNode = getHeadNode(); - Node prevNode = getPrevNode(); + final var headNode = getHeadNode(); + final var prevNode = getPrevNode(); WayInPolygon mostLeft = null; // most left way connected to head node - boolean comingToHead = false; // true if candidate come to head node + var comingToHead = false; // true if candidate come to head node double angle = 2*Math.PI; for (WayInPolygon candidateWay : availableWays) { @@ -648,11 +648,11 @@ private JoinAreasResult joinAreas(List areas) throws UserCancelExc ds = areas.get(0).getOuterWay().getDataSet(); } - boolean hasChanges = false; + var hasChanges = false; - List allStartingWays = new ArrayList<>(); - List innerStartingWays = new ArrayList<>(); - List outerStartingWays = new ArrayList<>(); + final var allStartingWays = new ArrayList(); + final var innerStartingWays = new ArrayList(); + final var outerStartingWays = new ArrayList(); for (Multipolygon area : areas) { outerStartingWays.add(area.outerWay); @@ -720,12 +720,12 @@ private JoinAreasResult joinAreas(List areas) throws UserCancelExc // see #9599 if (discardedWays.stream().anyMatch(w -> !w.isNew())) { for (AssembledPolygon ring : boundaries) { - for (int k = 0; k < ring.ways.size(); k++) { + for (var k = 0; k < ring.ways.size(); k++) { WayInPolygon ringWay = ring.ways.get(k); Way older = keepOlder(ringWay.way, oldestWayMap, discardedWays); if (ringWay.way != older) { - WayInPolygon repl = new WayInPolygon(older, ringWay.insideToTheRight); + final var repl = new WayInPolygon(older, ringWay.insideToTheRight); ring.ways.set(k, repl); } } @@ -768,7 +768,7 @@ private JoinAreasResult joinAreas(List areas) throws UserCancelExc // Delete the discarded inner ways if (!discardedWays.isEmpty()) { - Command deleteCmd = DeleteCommand.delete(discardedWays, true); + final var deleteCmd = DeleteCommand.delete(discardedWays, true); if (deleteCmd != null) { cmds.add(deleteCmd); commitCommands(marktr("Delete Ways that are not part of an inner multipolygon")); @@ -795,8 +795,8 @@ private JoinAreasResult joinAreas(List areas) throws UserCancelExc */ private Way keepOlder(Way way, Map oldestWayMap, List discardedWays) { Way oldest = null; - for (Node n : way.getNodes()) { - Way orig = oldestWayMap .get(n); + for (var n : way.getNodes()) { + final var orig = oldestWayMap .get(n); if (orig != null && (oldest == null || oldest.getUniqueId() > orig.getUniqueId()) && discardedWays.contains(orig)) { oldest = orig; @@ -829,7 +829,7 @@ private boolean resolveTagConflicts(List polygons) { return true; } - TagCollection wayTags = TagCollection.unionOfAllPrimitives(ways); + final var wayTags = TagCollection.unionOfAllPrimitives(ways); try { cmds.addAll(CombinePrimitiveResolverDialog.launchIfNecessary(wayTags, ways, ways)); commitCommands(marktr("Fix tag conflicts")); @@ -846,20 +846,20 @@ private boolean resolveTagConflicts(List polygons) { * @return {@code true} if any changes where made */ private boolean removeDuplicateNodes(List ways) { - Map nodeMap = new TreeMap<>(new NodePositionComparator()); - int totalWaysModified = 0; + final var nodeMap = new TreeMap(new NodePositionComparator()); + var totalWaysModified = 0; for (Way way : ways) { if (way.getNodes().size() < 2) { continue; } - List newNodes = new ArrayList<>(); + final var newNodes = new ArrayList(); Node prevNode = null; - boolean modifyWay = false; + var modifyWay = false; for (Node node : way.getNodes()) { - Node representator = nodeMap.get(node); + var representator = nodeMap.get(node); if (representator == null) { //new node nodeMap.put(node, node); @@ -897,7 +897,7 @@ private boolean removeDuplicateNodes(List ways) { * @param description The description of what the commands do */ private void commitCommands(String description) { - switch(cmds.size()) { + switch (cmds.size()) { case 0: return; case 1: @@ -922,7 +922,7 @@ private void commitCommand(Command c) { private void commitExecuted() { cmds.clear(); if (addUndoRedo && !executedCmds.isEmpty()) { - UndoRedoHandler ur = UndoRedoHandler.getInstance(); + final var ur = UndoRedoHandler.getInstance(); if (executedCmds.size() == 1) { ur.add(executedCmds.getFirst(), false); } else { @@ -944,7 +944,7 @@ private static List markWayInsideSide(List parts, boolean isI //prepare next map Map nextWayMap = new HashMap<>(); - for (int pos = 0; pos < parts.size(); pos++) { + for (var pos = 0; pos < parts.size(); pos++) { if (!parts.get(pos).lastNode().equals(parts.get((pos + 1) % parts.size()).firstNode())) throw new IllegalArgumentException("Way not circular"); @@ -955,12 +955,12 @@ private static List markWayInsideSide(List parts, boolean isI //find the node with minimum y - it's guaranteed to be outer. (What about the south pole?) Way topWay = null; Node topNode = null; - int topIndex = 0; + var topIndex = 0; double minY = Double.POSITIVE_INFINITY; for (Way way : parts) { - for (int pos = 0; pos < way.getNodesCount(); pos++) { - Node node = way.getNode(pos); + for (var pos = 0; pos < way.getNodesCount(); pos++) { + final var node = way.getNode(pos); if (node.getEastNorth().getY() < minY) { minY = node.getEastNorth().getY(); @@ -995,7 +995,7 @@ private static List markWayInsideSide(List parts, boolean isI for (Way way : parts) { if (way.firstNode().equals(headNode)) { - Node nextNode = way.getNode(1); + final var nextNode = way.getNode(1); if (topWay == null || !Geometry.isToTheRightSideOfLine(prevNode, headNode, bestWayNextNode, nextNode)) { //the new way is better @@ -1007,7 +1007,7 @@ private static List markWayInsideSide(List parts, boolean isI if (way.lastNode().equals(headNode)) { //end adjacent to headNode - Node nextNode = way.getNode(way.getNodesCount() - 2); + final var nextNode = way.getNode(way.getNodesCount() - 2); if (topWay == null || !Geometry.isToTheRightSideOfLine(prevNode, headNode, bestWayNextNode, nextNode)) { //the new way is better @@ -1019,14 +1019,14 @@ private static List markWayInsideSide(List parts, boolean isI } } else { //node is inside way - pick the clockwise going end. - Node prev = topWay.getNode(topIndex - 1); - Node next = topWay.getNode(topIndex + 1); + final var prev = topWay.getNode(topIndex - 1); + final var next = topWay.getNode(topIndex + 1); //there will be no parallel segments in the middle of way, so all fine. wayClockwise = Geometry.angleIsClockwise(prev, topNode, next); } - Way curWay = topWay; + var curWay = topWay; boolean curWayInsideToTheRight = wayClockwise ^ isInner; List result = new ArrayList<>(); @@ -1034,14 +1034,14 @@ private static List markWayInsideSide(List parts, boolean isI while (curWay != null) { //add cur way - WayInPolygon resultWay = new WayInPolygon(curWay, curWayInsideToTheRight); + final var resultWay = new WayInPolygon(curWay, curWayInsideToTheRight); result.add(resultWay); //process next way - Way nextWay = nextWayMap.get(curWay); - Node prevNode = curWay.getNode(curWay.getNodesCount() - 2); - Node headNode = curWay.lastNode(); - Node nextNode = nextWay.getNode(1); + final var nextWay = nextWayMap.get(curWay); + final var prevNode = curWay.getNode(curWay.getNodesCount() - 2); + final var headNode = curWay.lastNode(); + final var nextNode = nextWay.getNode(1); if (nextWay == topWay) { //full loop traversed - all done. @@ -1067,7 +1067,7 @@ private static List markWayInsideSide(List parts, boolean isI // X wayANode // | - int intersectionCount = 0; + var intersectionCount = 0; for (Way wayA : parts) { @@ -1077,12 +1077,12 @@ private static List markWayInsideSide(List parts, boolean isI if (wayA.lastNode().equals(headNode)) { - Way wayB = nextWayMap.get(wayA); + final var wayB = nextWayMap.get(wayA); //test if wayA is opposite wayB relative to curWay and nextWay - Node wayANode = wayA.getNode(wayA.getNodesCount() - 2); - Node wayBNode = wayB.getNode(1); + final var wayANode = wayA.getNode(wayA.getNodesCount() - 2); + final var wayBNode = wayB.getNode(1); boolean wayAToTheRight = Geometry.isToTheRightSideOfLine(prevNode, headNode, nextNode, wayANode); boolean wayBToTheRight = Geometry.isToTheRightSideOfLine(prevNode, headNode, nextNode, wayBNode); @@ -1116,7 +1116,7 @@ private static List markWayInsideSide(List parts, boolean isI * @param parts the parts of a single closed way */ private static void revertDuplicateTwoNodeWays(List parts) { - for (int i = 0; i < parts.size(); i++) { + for (var i = 0; i < parts.size(); i++) { WayInPolygon w1 = parts.get(i); if (w1.way.getNodesCount() != 2) continue; @@ -1140,11 +1140,11 @@ private static void revertDuplicateTwoNodeWays(List parts) { */ private List splitWayOnNodes(Way way, Set nodes, Map oldestWayMap) { - List result = new ArrayList<>(); + final var result = new ArrayList(); List> chunks = buildNodeChunks(way, nodes); if (chunks.size() > 1) { - SplitWayCommand split = SplitWayCommand.splitWay(way, chunks, + final var split = SplitWayCommand.splitWay(way, chunks, Collections.emptyList(), SplitWayCommand.Strategy.keepFirstChunk()); if (split != null) { @@ -1158,8 +1158,8 @@ private List splitWayOnNodes(Way way, Set nodes, Map oldes // see #9599 if (!way.isNew() && result.size() > 1) { for (Way part : result) { - Node n = part.firstNode(); - Way old = oldestWayMap.get(n); + final var n = part.firstNode(); + final var old = oldestWayMap.get(n); if (old == null || old.getUniqueId() > way.getUniqueId()) { oldestWayMap.put(n, way); } @@ -1230,12 +1230,12 @@ private static List findPolygons(Collection findOuterWaysImpl(int level, Collection boundaryWays) { //TODO: bad performance for deep nestings... - List result = new ArrayList<>(); + final var result = new ArrayList(); for (AssembledPolygon outerWay : boundaryWays) { - boolean outerGood = true; - List innerCandidates = new ArrayList<>(); + var outerGood = true; + final var innerCandidates = new ArrayList(); for (AssembledPolygon innerWay : boundaryWays) { if (innerWay == outerWay) { @@ -1255,8 +1255,8 @@ private static List findOuterWaysImpl(int level, Collection findBoundaryPolygons(Collection cleanMultigonWays = new ArrayList<>(); + final var cleanMultigonWays = new ArrayList(); for (WayInPolygon way: multigonWays) { if (way.way.getNodesCount() != 2 || !way.way.isClosed()) cleanMultigonWays.add(way); } - WayTraverser traverser = new WayTraverser(cleanMultigonWays); - List result = new ArrayList<>(); + final var traverser = new WayTraverser(cleanMultigonWays); + final var result = new ArrayList(); WayInPolygon startWay; while ((startWay = traverser.startNewWay()) != null) { - List path = new ArrayList<>(); - List startWays = new ArrayList<>(); + final var path = new ArrayList(); + final var startWays = new ArrayList(); path.add(startWay); while (true) { WayInPolygon leftComing; @@ -1317,7 +1317,7 @@ public static List findBoundaryPolygons(Collection stop here - AssembledPolygon ring = new AssembledPolygon(path); + final var ring = new AssembledPolygon(path); if (ring.getNodes().size() <= 2) { // Invalid ring (2 nodes) -> remove traverser.removeWays(path); @@ -1356,15 +1356,15 @@ public static List findBoundaryPolygons(Collection fixTouchingPolygons(List polygons) { - List newPolygons = new ArrayList<>(); + final var newPolygons = new ArrayList(); for (AssembledPolygon ring : polygons) { ring.reverse(); - WayTraverser traverser = new WayTraverser(ring.ways); + final var traverser = new WayTraverser(ring.ways); WayInPolygon startWay; while ((startWay = traverser.startNewWay()) != null) { - List simpleRingWays = new ArrayList<>(); + final var simpleRingWays = new ArrayList(); simpleRingWays.add(startWay); WayInPolygon nextWay; while ((nextWay = traverser.walk()) != startWay) { @@ -1373,7 +1373,7 @@ public static List fixTouchingPolygons(List simpleRingWays.add(nextWay); } traverser.removeWays(simpleRingWays); - AssembledPolygon simpleRing = new AssembledPolygon(simpleRingWays); + final var simpleRing = new AssembledPolygon(simpleRingWays); simpleRing.reverse(); newPolygons.add(simpleRing); } @@ -1410,7 +1410,7 @@ public static boolean wayInsideWay(AssembledPolygon inside, AssembledPolygon out * @throws UserCancelException if user cancels the operation */ private Multipolygon joinPolygon(AssembledMultipolygon polygon) throws UserCancelException { - Multipolygon result = new Multipolygon(joinWays(polygon.outerWay.ways)); + final var result = new Multipolygon(joinWays(polygon.outerWay.ways)); for (AssembledPolygon pol : polygon.innerWays) { result.innerWays.add(joinWays(pol.ways)); @@ -1428,7 +1428,7 @@ private Multipolygon joinPolygon(AssembledMultipolygon polygon) throws UserCance private Way joinWays(List ways) throws UserCancelException { //leave original orientation, if all paths are reverse. - boolean allReverse = true; + var allReverse = true; for (WayInPolygon way : ways) { allReverse &= !way.insideToTheRight; } @@ -1439,7 +1439,7 @@ private Way joinWays(List ways) throws UserCancelException { } } - Way joinedWay = joinOrientedWays(ways); + final var joinedWay = joinOrientedWays(ways); //should not happen if (joinedWay == null || !joinedWay.isClosed()) @@ -1461,8 +1461,8 @@ private Way joinOrientedWays(List ways) throws UserCancelException // This will turn ways so all of them point in the same direction and CombineAction won't bug // the user about this. - List actionWays = new ArrayList<>(ways.size()); - int oldestPos = 0; + final var actionWays = new ArrayList(ways.size()); + var oldestPos = 0; Way oldest = ways.get(0).way; for (WayInPolygon way : ways) { actionWays.add(way.way); @@ -1510,7 +1510,7 @@ public static List collectMultipolygons(Collection selectedWa continue; } - boolean hasKnownOuter = false; + var hasKnownOuter = false; outerWays.clear(); innerWays.clear(); @@ -1537,7 +1537,7 @@ public static List collectMultipolygons(Collection selectedWa return null; } - Way outerWay = outerWays.get(0); + final var outerWay = outerWays.get(0); //retain only selected inner ways innerWays.retainAll(selectedWays); @@ -1587,7 +1587,7 @@ public static List collectMultipolygons(Collection selectedWa processedOuterWays.add(outerWay); processedInnerWays.addAll(innerWays); - Multipolygon pol = new Multipolygon(outerWay); + final var pol = new Multipolygon(outerWay); pol.innerWays.addAll(innerWays); result.add(pol); @@ -1614,7 +1614,7 @@ private RelationRole addOwnMultipolygonRelation(Collection inner) { if (inner.isEmpty()) return null; OsmDataLayer layer = getLayerManager().getEditLayer(); // Create new multipolygon relation and add all inner ways to it - Relation newRel = new Relation(); + final var newRel = new Relation(); newRel.put("type", "multipolygon"); for (Way w : inner) { newRel.addMember(new RelationMember("inner", w)); @@ -1649,7 +1649,7 @@ private List removeFromAllRelations(OsmPrimitive osm) { members.remove(rm); cmds.add(new ChangeMembersCommand(r, members)); - RelationRole saverel = new RelationRole(r, rm.getRole()); + final var saverel = new RelationRole(r, rm.getRole()); if (!result.contains(saverel)) { result.add(saverel); } @@ -1700,7 +1700,7 @@ private void fixRelations(List rels, Way outer, RelationRole ownMu return; default: // Create a new relation with all previous members and (Way)outer as outer. - Relation newRel = new Relation(); + final var newRel = new Relation(); for (RelationRole r : multiouters) { // Add members for (RelationMember rm : r.rel.getMembers()) { diff --git a/src/org/openstreetmap/josm/actions/SplitWayAction.java b/src/org/openstreetmap/josm/actions/SplitWayAction.java index a4985c23bcb..85a94f0844c 100644 --- a/src/org/openstreetmap/josm/actions/SplitWayAction.java +++ b/src/org/openstreetmap/josm/actions/SplitWayAction.java @@ -6,6 +6,7 @@ import static org.openstreetmap.josm.tools.I18n.trn; import java.awt.Component; +import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; @@ -145,8 +146,8 @@ public static void runOn(DataSet ds) { } // Finally, applicableWays contains only one perfect way - final Way selectedWay = applicableWays.get(0); - final List sel = new ArrayList<>(ds.getSelectedRelations()); + final var selectedWay = applicableWays.get(0); + final var sel = new ArrayList(ds.getSelectedRelations()); sel.addAll(selectedWays); doSplitWayShowSegmentSelection(selectedWay, selectedNodes, sel); } @@ -163,7 +164,7 @@ public static void doSplitWayShowSegmentSelection(Way splitWay, List split final List> wayChunks = SplitWayCommand.buildSplitChunks(splitWay, splitNodes); if (wayChunks != null) { final List newWays = SplitWayCommand.createNewWaysFromChunks(splitWay, wayChunks); - final Way wayToKeep = SplitWayCommand.Strategy.keepLongestChunk().determineWayToKeep(newWays); + final var wayToKeep = SplitWayCommand.Strategy.keepLongestChunk().determineWayToKeep(newWays); if (ExpertToggleAction.isExpert() && !splitWay.isNew()) { final ExtendedDialog dialog = new SegmentToKeepSelectionDialog(splitWay, newWays, wayToKeep, splitNodes, selection); @@ -209,9 +210,9 @@ static class SegmentToKeepSelectionDialog extends ExtendedDialog { configureList(); setButtonIcons("ok", "cancel"); - final JPanel pane = new JPanel(new GridBagLayout()); - pane.add(new JLabel(getTitle()), GBC.eol().fill(GBC.HORIZONTAL)); - pane.add(list, GBC.eop().fill(GBC.HORIZONTAL)); + final var pane = new JPanel(new GridBagLayout()); + pane.add(new JLabel(getTitle()), GBC.eol().fill(GridBagConstraints.HORIZONTAL)); + pane.add(list, GBC.eop().fill(GridBagConstraints.HORIZONTAL)); setContent(pane); setDefaultCloseOperation(HIDE_ON_CLOSE); } @@ -223,9 +224,9 @@ private void configureList() { if (selected != null && MainApplication.isDisplayingMapView() && selected.getNodesCount() > 1) { final Collection segments = new ArrayList<>(selected.getNodesCount() - 1); final Iterator it = selected.getNodes().iterator(); - Node previousNode = it.next(); + var previousNode = it.next(); while (it.hasNext()) { - final Node node = it.next(); + final var node = it.next(); segments.add(WaySegment.forNodePair(selectedWay, previousNode, node)); previousNode = node; } @@ -236,7 +237,7 @@ private void configureList() { } protected void setHighlightedWaySegments(Collection segments) { - DataSet ds = selectedWay.getDataSet(); + final var ds = selectedWay.getDataSet(); if (ds != null) { ds.setHighlightedWaySegments(segments); MainApplication.getMap().mapView.repaint(); @@ -246,7 +247,7 @@ protected void setHighlightedWaySegments(Collection segments) { @Override public void setVisible(boolean visible) { super.setVisible(visible); - DataSet ds = selectedWay.getDataSet(); + final var ds = selectedWay.getDataSet(); if (visible) { DISPLAY_COUNT.incrementAndGet(); list.setSelectedValue(wayToKeep, true); @@ -275,7 +276,7 @@ protected void buttonAction(int buttonIndex, ActionEvent evt) { } } - private class SplitWayDataSetListener implements DataSetListener { + private final class SplitWayDataSetListener implements DataSetListener { @Override public void primitivesAdded(PrimitivesAddedEvent event) { @@ -335,7 +336,7 @@ private void updateWaySegments() { static class SegmentListCellRenderer extends DefaultListCellRenderer { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - final Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + final var c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); final String name = DefaultNameFormatter.getInstance().format((Way) value); // get rid of id from DefaultNameFormatter.decorateNameWithId() final String nameWithoutId = name @@ -358,7 +359,7 @@ static List getApplicableWays(List selectedWays, List selectedNo // Special case - one of the selected ways touches (not cross) way that we want to split if (selectedNodes.size() == 1) { - Node n = selectedNodes.get(0); + final var n = selectedNodes.get(0); List referredWays = n.getParentWays(); Way inTheMiddle = null; for (Way w: referredWays) { diff --git a/src/org/openstreetmap/josm/data/osm/search/SearchCompiler.java b/src/org/openstreetmap/josm/data/osm/search/SearchCompiler.java index 4f059811c45..b6d59952e32 100644 --- a/src/org/openstreetmap/josm/data/osm/search/SearchCompiler.java +++ b/src/org/openstreetmap/josm/data/osm/search/SearchCompiler.java @@ -22,7 +22,6 @@ import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; -import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import java.util.stream.Collectors; @@ -159,7 +158,7 @@ public static class CoreSimpleMatchFactory implements SimpleMatchFactory { @Override public Match get(String keyword, boolean caseSensitive, boolean regexSearch, PushbackTokenizer tokenizer) throws SearchParseError { - switch(keyword) { + switch (keyword) { case MODIFIED: return new Modified(); case DELETED: @@ -1139,8 +1138,8 @@ public boolean match(Tagged osm) { value = Normalizer.normalize(value, Normalizer.Form.NFC); - Matcher keyMatcher = searchRegex.matcher(key); - Matcher valMatcher = searchRegex.matcher(value); + final var keyMatcher = searchRegex.matcher(key); + final var valMatcher = searchRegex.matcher(value); boolean keyMatchFound = keyMatcher.find(); boolean valMatchFound = valMatcher.find(); @@ -1622,7 +1621,7 @@ public boolean equals(Object obj) { /** * Matches objects that are new (i.e. have not been uploaded to the server) */ - private static class New extends Match { + private static final class New extends Match { @Override public boolean match(OsmPrimitive osm) { return osm.isNew(); @@ -1637,7 +1636,7 @@ public String toString() { /** * Matches all objects that have been modified, created, or undeleted */ - private static class Modified extends Match { + private static final class Modified extends Match { @Override public boolean match(OsmPrimitive osm) { return osm.isModified() || osm.isNewOrUndeleted(); @@ -1652,7 +1651,7 @@ public String toString() { /** * Matches all objects that have been deleted */ - private static class Deleted extends Match { + private static final class Deleted extends Match { @Override public boolean match(OsmPrimitive osm) { return osm.isDeleted(); @@ -1667,7 +1666,7 @@ public String toString() { /** * Matches all objects currently selected */ - private static class Selected extends Match { + private static final class Selected extends Match { @Override public boolean match(OsmPrimitive osm) { return osm.getDataSet().isSelected(osm); @@ -1684,7 +1683,7 @@ public String toString() { * Typically, some members of a relation are incomplete until they are * fetched from the server. */ - private static class Incomplete extends Match { + private static final class Incomplete extends Match { @Override public boolean match(OsmPrimitive osm) { return osm.isIncomplete() || (osm instanceof Relation && ((Relation) osm).hasIncompleteMembers()); @@ -1701,7 +1700,7 @@ public String toString() { * fixme, etc.). The complete list of uninteresting tags can be found here: * org.openstreetmap.josm.data.osm.OsmPrimitive.getUninterestingKeys() */ - private static class Untagged extends Match { + private static final class Untagged extends Match { @Override public boolean match(OsmPrimitive osm) { return !osm.isTagged() && !osm.isIncomplete(); @@ -1716,7 +1715,7 @@ public String toString() { /** * Matches ways which are closed (i.e. first and last node are the same) */ - private static class Closed extends Match { + private static final class Closed extends Match { @Override public boolean match(OsmPrimitive osm) { return osm instanceof Way && ((Way) osm).isClosed(); @@ -1817,7 +1816,7 @@ private static class WayLength extends RangeMatch { protected Long getNumber(OsmPrimitive osm) { if (!(osm instanceof Way)) return null; - Way way = (Way) osm; + final var way = (Way) osm; return (long) way.getLength(); } @@ -1970,7 +1969,7 @@ private static boolean presetNameMatch(String name, TaggingPreset preset, boolea } try { - String groupSuffix = name.substring(0, name.length() - 2); // try to remove '/*' + final var groupSuffix = name.substring(0, name.length() - 2); // try to remove '/*' TaggingPresetMenu group = preset.group; return group != null && groupSuffix.equalsIgnoreCase(group.getRawName()); @@ -2178,11 +2177,11 @@ private Match parseFactor() throws SearchParseError { return new ValueComparison(key, tokenizer.readTextOrNumber(), +1).validate(); } else if (tokenizer.readIfEqual(Token.COLON)) { // see if we have a Match that takes a data parameter - SimpleMatchFactory factory = simpleMatchFactoryMap.get(key); + final var factory = simpleMatchFactoryMap.get(key); if (factory != null) return factory.get(key, caseSensitive, regexSearch, tokenizer); - UnaryMatchFactory unaryFactory = unaryMatchFactoryMap.get(key); + final var unaryFactory = unaryMatchFactoryMap.get(key); if (unaryFactory != null) return getValidate(unaryFactory, key, tokenizer); @@ -2195,11 +2194,11 @@ private Match parseFactor() throws SearchParseError { } else if (tokenizer.readIfEqual(Token.QUESTION_MARK)) return new BooleanMatch(key, false); else { - SimpleMatchFactory factory = simpleMatchFactoryMap.get(key); + final var factory = simpleMatchFactoryMap.get(key); if (factory != null) return factory.get(key, caseSensitive, regexSearch, null).validate(); - UnaryMatchFactory unaryFactory = unaryMatchFactoryMap.get(key); + final var unaryFactory = unaryMatchFactoryMap.get(key); if (unaryFactory != null) return getValidate(unaryFactory, key, null); @@ -2221,7 +2220,7 @@ private Match getValidate(UnaryMatchFactory unaryFactory, String key, PushbackTo } private static int regexFlags(boolean caseSensitive) { - int searchFlags = 0; + var searchFlags = 0; // Enables canonical Unicode equivalence so that e.g. the two // forms of "\u00e9gal" and "e\u0301gal" will match. diff --git a/src/org/openstreetmap/josm/data/validation/ValidatorCLI.java b/src/org/openstreetmap/josm/data/validation/ValidatorCLI.java index 3fcdf355943..d3fd83b69c6 100644 --- a/src/org/openstreetmap/josm/data/validation/ValidatorCLI.java +++ b/src/org/openstreetmap/josm/data/validation/ValidatorCLI.java @@ -10,7 +10,6 @@ import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; -import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; @@ -26,11 +25,10 @@ import java.util.logging.Level; import java.util.stream.Collectors; -import org.apache.commons.compress.utils.FileNameUtils; +import org.apache.commons.io.FilenameUtils; import org.openstreetmap.josm.actions.ExtensionFileFilter; import org.openstreetmap.josm.cli.CLIModule; import org.openstreetmap.josm.data.Preferences; -import org.openstreetmap.josm.data.osm.DataSet; import org.openstreetmap.josm.data.preferences.JosmBaseDirectories; import org.openstreetmap.josm.data.preferences.JosmUrls; import org.openstreetmap.josm.data.projection.ProjectionRegistry; @@ -175,7 +173,7 @@ public void processArguments(final String[] argArray) { throw new IllegalArgumentException(tr("Missing argument - input data file ({0})", "--input|-i")); } this.initialize(); - final ProgressMonitor fileMonitor = progressMonitorFactory.get(); + final var fileMonitor = progressMonitorFactory.get(); fileMonitor.beginTask(tr("Processing files..."), this.input.size()); for (String inputFile : this.input) { if (inputFile.endsWith(".validator.mapcss")) { @@ -201,7 +199,7 @@ public void processArguments(final String[] argArray) { * @throws ParseException if the file does not match the mapcss syntax */ private static void processMapcssFile(final String inputFile) throws ParseException { - final MapCSSStyleSource styleSource = new MapCSSStyleSource(new File(inputFile).toURI().getPath(), inputFile, inputFile); + final var styleSource = new MapCSSStyleSource(new File(inputFile).toURI().getPath(), inputFile, inputFile); styleSource.loadStyleSource(); if (!styleSource.getErrors().isEmpty()) { throw new ParseException(trn("{0} had {1} error", "{0} had {1} errors", styleSource.getErrors().size(), @@ -220,8 +218,8 @@ private static void processMapcssFile(final String inputFile) throws ParseExcept private static void processValidatorFile(final String inputFile) throws ParseException, IOException { // Check asserts Config.getPref().putBoolean("validator.check_assert_local_rules", true); - final MapCSSTagChecker mapCSSTagChecker = new MapCSSTagChecker(); - final Collection assertionErrors = new ArrayList<>(); + final var mapCSSTagChecker = new MapCSSTagChecker(); + final var assertionErrors = new ArrayList(); final MapCSSTagChecker.ParseResult result = mapCSSTagChecker.addMapCSS(new File(inputFile).toURI().getPath(), assertionErrors::add); if (!result.parseErrors.isEmpty() || !assertionErrors.isEmpty()) { @@ -246,10 +244,10 @@ private static void processValidatorFile(final String inputFile) throws ParseExc * @throws IOException If a file could not be read or written */ private void processFile(final String inputFile) throws IllegalDataException, IOException { - final File inputFileFile = new File(inputFile); + final var inputFileFile = new File(inputFile); final List inputFileImporters = ExtensionFileFilter.getImporters().stream() .filter(importer -> importer.acceptFile(inputFileFile)).collect(Collectors.toList()); - final Stopwatch stopwatch = Stopwatch.createStarted(); + final var stopwatch = Stopwatch.createStarted(); if (inputFileImporters.stream().noneMatch(fileImporter -> fileImporter.importDataHandleExceptions(inputFileFile, progressMonitorFactory.get()))) { throw new IOException(tr("Could not load input file: {0}", inputFile)); @@ -262,26 +260,26 @@ private void processFile(final String inputFile) throws IllegalDataException, IO dataLayer = MainApplication.getLayerManager().getLayersOfType(OsmDataLayer.class) .stream().filter(layer -> inputFileFile.equals(layer.getAssociatedFile())) .findFirst().orElseThrow(() -> new JosmRuntimeException(tr("Could not find a layer for {0}", inputFile))); - final DataSet dataSet = dataLayer.getDataSet(); + final var dataSet = dataLayer.getDataSet(); if (this.changeFiles.containsKey(inputFile)) { - ProgressMonitor changeFilesMonitor = progressMonitorFactory.get(); + final var changeFilesMonitor = progressMonitorFactory.get(); for (String changeFile : this.changeFiles.getOrDefault(inputFile, Collections.emptyList())) { - try (InputStream changeStream = Compression.getUncompressedFileInputStream(Paths.get(changeFile))) { + try (var changeStream = Compression.getUncompressedFileInputStream(Paths.get(changeFile))) { dataSet.mergeFrom(OsmChangeReader.parseDataSet(changeStream, changeFilesMonitor)); } } } - Path path = Paths.get(outputFile); + final var path = Paths.get(outputFile); if (path.toFile().isFile() && !Files.deleteIfExists(path)) { Logging.error("Could not delete {0}, attempting to append", outputFile); } - GeoJSONMapRouletteWriter geoJSONMapRouletteWriter = new GeoJSONMapRouletteWriter(dataSet); + final var geoJSONMapRouletteWriter = new GeoJSONMapRouletteWriter(dataSet); OsmValidator.initializeTests(); - try (OutputStream fileOutputStream = Files.newOutputStream(path)) { + try (var fileOutputStream = Files.newOutputStream(path)) { // The first writeErrors catches anything that was written, for whatever reason. This is probably never // going to be called. - ValidationTask validationTask = new ValidationTask(errors -> writeErrors(geoJSONMapRouletteWriter, fileOutputStream, errors), + final var validationTask = new ValidationTask(errors -> writeErrors(geoJSONMapRouletteWriter, fileOutputStream, errors), progressMonitorFactory.get(), OsmValidator.getEnabledTests(false), dataSet.allPrimitives(), Collections.emptyList(), false); // This avoids keeping errors in memory @@ -319,14 +317,14 @@ private void writeErrors(GeoJSONMapRouletteWriter geoJSONMapRouletteWriter, Outp * @return The default output name for the input file (extension stripped, ".geojson" added) */ private static String getDefaultOutputName(final String inputString) { - final String extension = FileNameUtils.getExtension(inputString); + final String extension = FilenameUtils.getExtension(inputString); if (!Arrays.asList("zip", "bz", "xz", "geojson").contains(extension)) { - return FileNameUtils.getBaseName(inputString) + ".geojson"; + return FilenameUtils.getBaseName(inputString) + ".geojson"; } else if ("geojson".equals(extension)) { // Account for geojson input files - return FileNameUtils.getBaseName(inputString) + ".validated.geojson"; + return FilenameUtils.getBaseName(inputString) + ".validated.geojson"; } - return FileNameUtils.getBaseName(FileNameUtils.getBaseName(inputString)) + ".geojson"; + return FilenameUtils.getBaseName(FilenameUtils.getBaseName(inputString)) + ".geojson"; } /** @@ -347,7 +345,7 @@ private synchronized void writeToFile(final OutputStream fileOutputStream, final /** * Initialize everything that might be needed - * + *

* Arguments may need to be parsed first. */ void initialize() { @@ -368,8 +366,8 @@ void initialize() { void parseArguments(String[] argArray) { Logging.setLogLevel(Level.INFO); - OptionParser parser = new OptionParser("JOSM validate"); - final AtomicReference currentInput = new AtomicReference<>(null); + final var parser = new OptionParser("JOSM validate"); + final var currentInput = new AtomicReference(null); for (Option o : Option.values()) { if (o.requiresArgument()) { parser.addArgumentParameter(o.getName(), @@ -424,9 +422,9 @@ private Optional handleOption(final String currentInput, final Option op I18n.set(argument); break; case LOAD_PREFERENCES: - final Preferences tempPreferences = new Preferences(); + final var tempPreferences = new Preferences(); tempPreferences.enableSaveOnPut(false); - CustomConfigurator.XMLCommandProcessor config = new CustomConfigurator.XMLCommandProcessor(tempPreferences); + final var config = new CustomConfigurator.XMLCommandProcessor(tempPreferences); try (InputStream is = Utils.openStream(new File(argument).toURI().toURL())) { config.openAndReadXML(is); } catch (IOException e) { @@ -434,7 +432,7 @@ private Optional handleOption(final String currentInput, final Option op } final IPreferences pref = Config.getPref(); if (pref instanceof MemoryPreferences) { - final MemoryPreferences memoryPreferences = (MemoryPreferences) pref; + final var memoryPreferences = (MemoryPreferences) pref; tempPreferences.getAllSettings().forEach(memoryPreferences::putSetting); } else { throw new JosmRuntimeException(tr("Preferences are not the expected type")); @@ -453,7 +451,7 @@ private static void showHelp() { } private static String getHelp() { - final String helpPadding = "\t "; + final var helpPadding = "\t "; // CHECKSTYLE.OFF: SingleSpaceSeparator return tr("JOSM Validation command line interface") + "\n\n" + tr("Usage") + ":\n" + diff --git a/src/org/openstreetmap/josm/gui/dialogs/relation/sort/RelationSorter.java b/src/org/openstreetmap/josm/gui/dialogs/relation/sort/RelationSorter.java index 5752800b297..e59b418f9d5 100644 --- a/src/org/openstreetmap/josm/gui/dialogs/relation/sort/RelationSorter.java +++ b/src/org/openstreetmap/josm/gui/dialogs/relation/sort/RelationSorter.java @@ -47,7 +47,7 @@ private interface AdditionalSorter { * Class that sorts the {@code street} members of * {@code type=associatedStreet} and {@code type=street} relations. */ - private static class AssociatedStreetRoleStreetSorter implements AdditionalSorter { + private static final class AssociatedStreetRoleStreetSorter implements AdditionalSorter { @Override public boolean acceptsMember(List relationMembers, RelationMember m) { @@ -64,7 +64,7 @@ public List sortMembers(List list) { * Class that sorts the {@code address} and {@code house} members of * {@code type=associatedStreet} and {@code type=street} relations. */ - private static class AssociatedStreetRoleAddressHouseSorter implements AdditionalSorter { + private static final class AssociatedStreetRoleAddressHouseSorter implements AdditionalSorter { @Override public boolean acceptsMember(List relationMembers, RelationMember m) { @@ -92,7 +92,7 @@ public List sortMembers(List list) { * Class that sorts the {@code platform} and {@code stop} members of * {@code type=public_transport} relations. */ - private static class PublicTransportRoleStopPlatformSorter implements AdditionalSorter { + private static final class PublicTransportRoleStopPlatformSorter implements AdditionalSorter { @Override public boolean acceptsMember(List relationMembers, RelationMember m) { @@ -139,7 +139,7 @@ public List sortMembers(List list) { * Class that sorts the {@code from}, {@code via} and {@code to} members of * {@code type=restriction} relations. */ - private static class FromViaToSorter implements AdditionalSorter { + private static final class FromViaToSorter implements AdditionalSorter { private static final List ROLES = Arrays.asList("from", "via", "to"); @@ -172,7 +172,7 @@ public List sortMembers(List relationMembers) { // Dispatch members to the first adequate sorter for (RelationMember m : relationMembers) { - boolean wasAdded = false; + var wasAdded = false; for (AdditionalSorter sorter : ADDITIONAL_SORTERS) { if (sorter.acceptsMember(relationMembers, m)) { wasAdded = customMap.computeIfAbsent(sorter, k -> new LinkedList<>()).add(m); diff --git a/src/org/openstreetmap/josm/gui/io/UploadPrimitivesTask.java b/src/org/openstreetmap/josm/gui/io/UploadPrimitivesTask.java index b23018d65cf..419b7a1d894 100644 --- a/src/org/openstreetmap/josm/gui/io/UploadPrimitivesTask.java +++ b/src/org/openstreetmap/josm/gui/io/UploadPrimitivesTask.java @@ -140,7 +140,7 @@ protected MaxChangesetSizeExceededPolicy promptUserForPolicy() { specs[0], ht("/Action/Upload#ChangesetFull") ); - switch(ret) { + switch (ret) { case 0: return MaxChangesetSizeExceededPolicy.AUTOMATICALLY_OPEN_NEW_CHANGESETS; case 1: return MaxChangesetSizeExceededPolicy.FILL_ONE_CHANGESET_AND_RETURN_TO_UPLOAD_DIALOG; case 2: @@ -167,9 +167,9 @@ protected boolean handleChangesetFullResponse() throws OsmTransferException { if (strategy.getPolicy() == null || strategy.getPolicy() == MaxChangesetSizeExceededPolicy.ABORT) { strategy.setPolicy(promptUserForPolicy()); } - switch(strategy.getPolicy()) { + switch (strategy.getPolicy()) { case AUTOMATICALLY_OPEN_NEW_CHANGESETS: - Changeset newChangeSet = new Changeset(); + final var newChangeSet = new Changeset(); newChangeSet.setKeys(changeset.getKeys()); closeChangeset(); this.changeset = newChangeSet; @@ -279,7 +279,7 @@ protected void realRun() { if (writer != null) { processedPrimitives.addAll(writer.getProcessedPrimitives()); // OsmPrimitive in => OsmPrimitive out } - switch(e.getSource()) { + switch (e.getSource()) { case UPLOAD_DATA: // Most likely the changeset is full. Try to recover and continue // with a new changeset, but let the user decide first. @@ -318,7 +318,7 @@ protected void realRun() { lastException = e; } } finally { - if (MessageNotifier.PROP_NOTIFIER_ENABLED.get()) { + if (Boolean.TRUE.equals(MessageNotifier.PROP_NOTIFIER_ENABLED.get())) { MessageNotifier.start(); } } @@ -371,7 +371,7 @@ protected void finish() { } if (uploadCanceled) return; if (lastException == null) { - HtmlPanel panel = new HtmlPanel( + final var panel = new HtmlPanel( "

" + tr("Upload successful!") + "

"); panel.enableClickableHyperlinks(); @@ -392,7 +392,7 @@ protected void finish() { /* do nothing if unknown policy */ return; if (e.getSource() == ChangesetClosedException.Source.UPLOAD_DATA) { - switch(strategy.getPolicy()) { + switch (strategy.getPolicy()) { case ABORT: break; /* do nothing - we return to map editing */ case AUTOMATICALLY_OPEN_NEW_CHANGESETS: diff --git a/src/org/openstreetmap/josm/gui/layer/geoimage/CorrelateGpxWithImages.java b/src/org/openstreetmap/josm/gui/layer/geoimage/CorrelateGpxWithImages.java index 4cb612e1911..0b0a20d6579 100644 --- a/src/org/openstreetmap/josm/gui/layer/geoimage/CorrelateGpxWithImages.java +++ b/src/org/openstreetmap/josm/gui/layer/geoimage/CorrelateGpxWithImages.java @@ -66,7 +66,6 @@ import org.openstreetmap.josm.gui.layer.LayerManager.LayerOrderChangeEvent; import org.openstreetmap.josm.gui.layer.LayerManager.LayerRemoveEvent; import org.openstreetmap.josm.gui.layer.geoimage.AdjustTimezoneAndOffsetDialog.AdjustListener; -import org.openstreetmap.josm.gui.layer.geoimage.SynchronizeTimeFromPhotoDialog.TimeZoneItem; import org.openstreetmap.josm.gui.layer.gpx.GpxDataHelper; import org.openstreetmap.josm.gui.widgets.JosmComboBox; import org.openstreetmap.josm.gui.widgets.JosmComboBoxModel; @@ -172,10 +171,10 @@ public void windowDeactivated(WindowEvent e) { // Search whether an other layer has yet defined some bounding box. // If none, we'll zoom to the bounding box of the layer with the photos. - boolean boundingBoxedLayerFound = false; + var boundingBoxedLayerFound = false; for (Layer l: MainApplication.getLayerManager().getLayers()) { if (l != yLayer) { - BoundingXYVisitor bbox = new BoundingXYVisitor(); + final var bbox = new BoundingXYVisitor(); l.visitBoundingBox(bbox); if (bbox.getBounds() != null) { boundingBoxedLayerFound = true; @@ -184,7 +183,7 @@ public void windowDeactivated(WindowEvent e) { } } if (!boundingBoxedLayerFound) { - BoundingXYVisitor bbox = new BoundingXYVisitor(); + final var bbox = new BoundingXYVisitor(); yLayer.visitBoundingBox(bbox); MainApplication.getMap().mapView.zoomTo(bbox); } @@ -260,18 +259,18 @@ public String toString() { * This class is called when the user doesn't find the GPX file he needs in the files that have * been loaded yet. It displays a FileChooser dialog to select the GPX file to be loaded. */ - private class LoadGpxDataActionListener implements ActionListener { + private final class LoadGpxDataActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { - File sel = GpxDataHelper.chooseGpxDataFile(); + final var sel = GpxDataHelper.chooseGpxDataFile(); if (sel != null) { try { outerPanel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); removeDuplicates(sel); - GpxData data = GpxDataHelper.loadGpxData(sel); + final var data = GpxDataHelper.loadGpxData(sel); if (data != null) { - GpxDataWrapper elem = new GpxDataWrapper(sel.getName(), data, sel); + final var elem = new GpxDataWrapper(sel.getName(), data, sel); gpxModel.addElement(elem); gpxModel.setSelectedItem(elem); statusBarUpdater.matchAndUpdateStatusBar(); @@ -283,7 +282,7 @@ public void actionPerformed(ActionEvent e) { } } - private class UseSupportLayerActionListener implements ActionListener { + private final class UseSupportLayerActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { @@ -295,11 +294,11 @@ public void actionPerformed(ActionEvent e) { } } - private class AdvancedSettingsActionListener implements ActionListener { + private final class AdvancedSettingsActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { - AdvancedCorrelationSettingsDialog ed = new AdvancedCorrelationSettingsDialog(MainApplication.getMainFrame(), forceTags); + final var ed = new AdvancedCorrelationSettingsDialog(MainApplication.getMainFrame(), forceTags); if (ed.showDialog().getValue() == 1) { forceTags = ed.isForceTaggingSelected(); // This setting is not supposed to be saved permanently @@ -316,14 +315,13 @@ public void actionPerformed(ActionEvent e) { * Then values of timezone and delta are set. * @author chris */ - private class SetOffsetActionListener implements ActionListener { + private final class SetOffsetActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { - boolean isOk = false; + var isOk = false; while (!isOk) { - SynchronizeTimeFromPhotoDialog ed = new SynchronizeTimeFromPhotoDialog( - MainApplication.getMainFrame(), yLayer.getImageData().getImages()); + final var ed = new SynchronizeTimeFromPhotoDialog(MainApplication.getMainFrame(), yLayer.getImageData().getImages()); int answer = ed.showDialog().getValue(); if (answer != 1) return; @@ -339,7 +337,7 @@ public void actionPerformed(ActionEvent e) { continue; } - TimeZoneItem selectedTz = ed.getTimeZoneItem(); + final var selectedTz = ed.getTimeZoneItem(); Config.getPref().put("geoimage.timezoneid", selectedTz.getID()); Config.getPref().putBoolean("geoimage.timezoneid.dst", ed.isDstSelected()); @@ -353,15 +351,15 @@ public void actionPerformed(ActionEvent e) { } } - private static class GpxLayerAddedListener implements LayerChangeListener { + private static final class GpxLayerAddedListener implements LayerChangeListener { @Override public void layerAdded(LayerAddEvent e) { - Layer layer = e.getAddedLayer(); + final var layer = e.getAddedLayer(); if (layer instanceof GpxDataContainer) { - GpxData gpx = ((GpxDataContainer) layer).getGpxData(); - File file = gpx.storageFile; + final var gpx = ((GpxDataContainer) layer).getGpxData(); + final var file = gpx.storageFile; removeDuplicates(file); - GpxDataWrapper gdw = new GpxDataWrapper(layer.getName(), gpx, file); + final var gdw = new GpxDataWrapper(layer.getName(), gpx, file); layer.addPropertyChangeListener(new GpxLayerRenamedListener(gdw)); gpxModel.addElement(gdw); forEachLayer(correlateAction -> { @@ -375,9 +373,9 @@ public void layerAdded(LayerAddEvent e) { @Override public void layerRemoving(LayerRemoveEvent e) { - Layer layer = e.getRemovedLayer(); + final var layer = e.getRemovedLayer(); if (layer instanceof GpxDataContainer) { - GpxData removedGpxData = ((GpxDataContainer) layer).getGpxData(); + final var removedGpxData = ((GpxDataContainer) layer).getGpxData(); for (int i = gpxModel.getSize() - 1; i >= 0; i--) { GpxData data = gpxModel.getElementAt(i).data; // removedGpxData can be null if gpx layer has been destroyed before this listener @@ -427,8 +425,8 @@ private void constructGpxModel(NoGpxDataWrapper nogdw) { GpxDataWrapper defaultItem = null; for (AbstractModifiableLayer cur : MainApplication.getLayerManager().getLayersOfType(AbstractModifiableLayer.class)) { if (cur instanceof GpxDataContainer) { - GpxData data = ((GpxDataContainer) cur).getGpxData(); - GpxDataWrapper gdw = new GpxDataWrapper(cur.getName(), data, data.storageFile); + final var data = ((GpxDataContainer) cur).getGpxData(); + final var gdw = new GpxDataWrapper(cur.getName(), data, data.storageFile); cur.addPropertyChangeListener(new GpxLayerRenamedListener(gdw)); gpxModel.addElement(gdw); if (data.equals(yLayer.gpxData) || defaultItem == null) { @@ -470,12 +468,12 @@ static GpxTimeOffset loadDelta() { @Override public void actionPerformed(ActionEvent ae) { - NoGpxDataWrapper nogdw = new NoGpxDataWrapper(); + final var nogdw = new NoGpxDataWrapper(); if (gpxModel == null) { constructGpxModel(nogdw); } - JPanel panelCb = new JPanel(); + final var panelCb = new JPanel(); panelCb.add(new JLabel(tr("GPX track: "))); @@ -484,7 +482,7 @@ public void actionPerformed(ActionEvent ae) { cbGpx.addActionListener(statusBarUpdaterWithRepaint); panelCb.add(cbGpx); - JButton buttonOpen = new JButton(tr("Open another GPX trace")); + final var buttonOpen = new JButton(tr("Open another GPX trace")); buttonOpen.addActionListener(new LoadGpxDataActionListener()); panelCb.add(buttonOpen); @@ -492,7 +490,7 @@ public void actionPerformed(ActionEvent ae) { buttonSupport.addActionListener(new UseSupportLayerActionListener()); panelCb.add(buttonSupport); - JPanel panelTf = new JPanel(new GridBagLayout()); + final var panelTf = new JPanel(new GridBagLayout()); timezone = loadTimezone(); @@ -504,21 +502,21 @@ public void actionPerformed(ActionEvent ae) { tfOffset = new JosmTextField(10); tfOffset.setText(delta.formatOffset()); - JButton buttonViewGpsPhoto = new JButton(tr("Use photo of an accurate clock,
e.g. GPS receiver display")); + final var buttonViewGpsPhoto = new JButton(tr("Use photo of an accurate clock,
e.g. GPS receiver display")); buttonViewGpsPhoto.setIcon(ImageProvider.get("clock")); buttonViewGpsPhoto.addActionListener(new SetOffsetActionListener()); - JButton buttonAutoGuess = new JButton(tr("Auto-Guess")); + final var buttonAutoGuess = new JButton(tr("Auto-Guess")); buttonAutoGuess.setToolTipText(tr("Matches first photo with first gpx point")); buttonAutoGuess.addActionListener(new AutoGuessActionListener()); - JButton buttonAdjust = new JButton(tr("Manual adjust")); + final var buttonAdjust = new JButton(tr("Manual adjust")); buttonAdjust.addActionListener(new AdjustActionListener()); - JButton buttonAdvanced = new JButton(tr("Advanced settings...")); + final var buttonAdvanced = new JButton(tr("Advanced settings...")); buttonAdvanced.addActionListener(new AdvancedSettingsActionListener()); - JLabel labelPosition = new JLabel(tr("Override position for: ")); + final var labelPosition = new JLabel(tr("Override position for: ")); int numAll = yLayer.getSortedImgList(true, true).size(); int numExif = numAll - yLayer.getSortedImgList(false, true).size(); @@ -536,13 +534,13 @@ public void actionPerformed(ActionEvent ae) { cbShowThumbs = new JCheckBox(tr("Show Thumbnail images on the map"), ticked); cbShowThumbs.setEnabled(!yLayer.thumbsLoaded); - int y = 0; - GBC gbc = GBC.eol(); + var y = 0; + var gbc = GBC.eol(); gbc.gridx = 0; gbc.gridy = y++; panelTf.add(panelCb, gbc); - gbc = GBC.eol().fill(GBC.HORIZONTAL).insets(0, 0, 0, 12); + gbc = GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(0, 0, 0, 12); gbc.gridx = 0; gbc.gridy = y++; panelTf.add(new JSeparator(SwingConstants.HORIZONTAL), gbc); @@ -552,7 +550,7 @@ public void actionPerformed(ActionEvent ae) { gbc.gridy = y; panelTf.add(new JLabel(tr("Timezone: ")), gbc); - gbc = GBC.std().fill(GBC.HORIZONTAL); + gbc = GBC.std().fill(GridBagConstraints.HORIZONTAL); gbc.gridx = 1; gbc.gridy = y++; gbc.weightx = 1.; @@ -563,7 +561,7 @@ public void actionPerformed(ActionEvent ae) { gbc.gridy = y; panelTf.add(new JLabel(tr("Offset:")), gbc); - gbc = GBC.std().fill(GBC.HORIZONTAL); + gbc = GBC.std().fill(GridBagConstraints.HORIZONTAL); gbc.gridx = 1; gbc.gridy = y++; gbc.weightx = 1.; @@ -578,7 +576,7 @@ public void actionPerformed(ActionEvent ae) { gbc.weightx = 0.5; panelTf.add(buttonViewGpsPhoto, gbc); - gbc = GBC.std().fill(GBC.BOTH).insets(5, 5, 5, 5); + gbc = GBC.std().fill(GridBagConstraints.BOTH).insets(5, 5, 5, 5); gbc.gridx = 1; gbc.gridy = y++; gbc.weightx = 0.5; @@ -590,7 +588,7 @@ public void actionPerformed(ActionEvent ae) { gbc.gridx = 3; panelTf.add(buttonAdjust, gbc); - gbc = GBC.eol().fill(GBC.HORIZONTAL).insets(0, 12, 0, 0); + gbc = GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(0, 12, 0, 0); gbc.gridx = 0; gbc.gridy = y++; panelTf.add(new JSeparator(SwingConstants.HORIZONTAL), gbc); @@ -615,7 +613,7 @@ public void actionPerformed(ActionEvent ae) { gbc.gridy = y; panelTf.add(cbShowThumbs, gbc); - gbc = GBC.eol().fill(GBC.HORIZONTAL).insets(0, 12, 0, 0); + gbc = GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(0, 12, 0, 0); sepDirectionPosition = new JSeparator(SwingConstants.HORIZONTAL); panelTf.add(sepDirectionPosition, gbc); @@ -626,13 +624,13 @@ public void actionPerformed(ActionEvent ae) { expertChanged(ExpertToggleAction.isExpert()); - final JPanel statusBar = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); + final var statusBar = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); statusBar.setBorder(BorderFactory.createLoweredBevelBorder()); statusBarText = new JLabel(" "); statusBarText.setFont(statusBarText.getFont().deriveFont(Font.PLAIN, 8)); statusBar.add(statusBarText); - RepaintTheMapListener repaintTheMap = new RepaintTheMapListener(yLayer); + final var repaintTheMap = new RepaintTheMapListener(yLayer); pDirectionPosition.addFocusListenerOnComponent(repaintTheMap); tfTimezone.addFocusListener(repaintTheMap); tfOffset.addFocusListener(repaintTheMap); @@ -807,12 +805,12 @@ public void focusLost(FocusEvent e) { /** * Presents dialog with sliders for manual adjust. */ - private class AdjustActionListener implements ActionListener { + private final class AdjustActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { - final GpxTimeOffset offset = GpxTimeOffset.milliseconds( + final var offset = GpxTimeOffset.milliseconds( delta.getMilliseconds() + Math.round(timezone.getHours() * TimeUnit.HOURS.toMillis(1))); final int dayOffset = offset.getDayOffset(); final Pair timezoneOffsetPair = offset.withoutDayOffset().splitOutTimezone(); @@ -894,7 +892,7 @@ static Pair autoGuess(List imgs, GpxData return GpxTimeOffset.milliseconds(firstExifDate - firstGPXDate).splitOutTimezone(); } - private class AutoGuessActionListener implements ActionListener { + private final class AutoGuessActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { @@ -942,7 +940,7 @@ private List getSortedImgList() { return yLayer.getSortedImgList(cbExifImg.isSelected(), cbTaggedImg.isSelected()); } - private GpxDataWrapper selectedGPX(boolean complain) { + private static GpxDataWrapper selectedGPX(boolean complain) { Object item = gpxModel.getSelectedItem(); if (item == null || ((GpxDataWrapper) item).data == null) { @@ -960,7 +958,7 @@ public void destroy() { ExpertToggleAction.removeExpertModeChangeListener(this); if (cbGpx != null) { // Force the JCombobox to remove its eventListener from the static GpxDataWrapper - cbGpx.setModel(new DefaultComboBoxModel()); + cbGpx.setModel(new DefaultComboBoxModel<>()); cbGpx = null; } diff --git a/src/org/openstreetmap/josm/gui/layer/geoimage/RemoteEntry.java b/src/org/openstreetmap/josm/gui/layer/geoimage/RemoteEntry.java index 2db67421809..ea66e00932b 100644 --- a/src/org/openstreetmap/josm/gui/layer/geoimage/RemoteEntry.java +++ b/src/org/openstreetmap/josm/gui/layer/geoimage/RemoteEntry.java @@ -295,11 +295,11 @@ public Projections getProjectionType() { @Override public InputStream getInputStream() throws IOException { - URI u = getImageURI(); + final var u = getImageURI(); if (u.getScheme().contains("file")) { return Files.newInputStream(Paths.get(u)); } - HttpClient client = HttpClient.create(u.toURL()); + final var client = HttpClient.create(u.toURL()); InputStream actual = client.connect().getContent(); return new BufferedInputStream(actual) { @Override @@ -342,7 +342,7 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (super.equals(obj)) { + if (this == obj) { return true; } if (obj != null && obj.getClass() == this.getClass()) { diff --git a/src/org/openstreetmap/josm/gui/mappaint/styleelement/LabelCompositionStrategy.java b/src/org/openstreetmap/josm/gui/mappaint/styleelement/LabelCompositionStrategy.java index 140d50d76bc..2f0450be603 100644 --- a/src/org/openstreetmap/josm/gui/mappaint/styleelement/LabelCompositionStrategy.java +++ b/src/org/openstreetmap/josm/gui/mappaint/styleelement/LabelCompositionStrategy.java @@ -166,19 +166,17 @@ public DeriveLabelFromNameTagsCompositionStrategy() { /* Is joining an array really that complicated in Java? */ private static String[] getDefaultNameTags() { - ArrayList tags = new ArrayList(Arrays.asList(LanguageInfo.getOSMLocaleCodes("name:"))); - tags.addAll(Arrays.asList(new String[]{ - "name", - "int_name", - "distance", - "railway:position", - "ref", - "operator", - "brand", - "addr:unit", - "addr:flats", - "addr:housenumber" - })); + final var tags = new ArrayList(Arrays.asList(LanguageInfo.getOSMLocaleCodes("name:"))); + tags.addAll(Arrays.asList("name", + "int_name", + "distance", + "railway:position", + "ref", + "operator", + "brand", + "addr:unit", + "addr:flats", + "addr:housenumber")); return tags.toArray(String[]::new); } @@ -250,7 +248,7 @@ public final void initNameTagsFromPreferences() { } private String getPrimitiveName(IPrimitive n) { - StringBuilder name = new StringBuilder(); + final var name = new StringBuilder(); if (!n.hasKeys()) return null; nameTags.stream().map(n::get).filter(Objects::nonNull).findFirst() .ifPresent(name::append); diff --git a/src/org/openstreetmap/josm/gui/widgets/JosmTextField.java b/src/org/openstreetmap/josm/gui/widgets/JosmTextField.java index 3320917643b..2c0b944caeb 100644 --- a/src/org/openstreetmap/josm/gui/widgets/JosmTextField.java +++ b/src/org/openstreetmap/josm/gui/widgets/JosmTextField.java @@ -4,7 +4,6 @@ import java.awt.Color; import java.awt.ComponentOrientation; import java.awt.Font; -import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; @@ -18,10 +17,10 @@ import java.beans.PropertyChangeListener; import javax.swing.Icon; -import javax.swing.JTextField; -import javax.swing.RepaintManager; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; +import javax.swing.JTextField; +import javax.swing.RepaintManager; import javax.swing.UIManager; import javax.swing.text.BadLocationException; import javax.swing.text.Document; @@ -29,6 +28,7 @@ import org.openstreetmap.josm.gui.MainApplication; import org.openstreetmap.josm.gui.MapFrame; import org.openstreetmap.josm.tools.Destroyable; +import org.openstreetmap.josm.tools.Logging; import org.openstreetmap.josm.tools.Utils; /** @@ -253,7 +253,7 @@ public final void discardAllUndoableEdits() { * @return the Color for hint texts */ public static Color getHintTextColor() { - Color color = UIManager.getColor("TextField[Disabled].textForeground"); // Nimbus? + var color = UIManager.getColor("TextField[Disabled].textForeground"); // Nimbus? if (color == null) color = UIManager.getColor("TextField.inactiveForeground"); if (color == null) @@ -289,8 +289,9 @@ public void paintComponent(Graphics g) { public void drawHint(Graphics g) { int x; try { - x = modelToView(0).x; + x = (int) Math.round(modelToView2D(0).getX()); } catch (BadLocationException exc) { + Logging.trace(exc); return; // can't happen } // Taken from http://stackoverflow.com/a/24571681/2257172 @@ -303,7 +304,7 @@ public void drawHint(Graphics g) { if (getComponentOrientation().isLeftToRight()) { g.drawString(getHint(), x, getBaseline(getWidth(), getHeight())); } else { - FontMetrics metrics = g.getFontMetrics(g.getFont()); + final var metrics = g.getFontMetrics(g.getFont()); int dx = metrics.stringWidth(getHint()); g.drawString(getHint(), x - dx, getBaseline(getWidth(), getHeight())); } diff --git a/src/org/openstreetmap/josm/io/NoteReader.java b/src/org/openstreetmap/josm/io/NoteReader.java index 6020360afed..de84c6bd424 100644 --- a/src/org/openstreetmap/josm/io/NoteReader.java +++ b/src/org/openstreetmap/josm/io/NoteReader.java @@ -51,7 +51,7 @@ private enum NoteParseMode { * SAX handler to read note information from its XML representation. * Reads both API style and planet dump style formats. */ - private class Parser extends DefaultHandler { + private final class Parser extends DefaultHandler { private NoteParseMode parseMode; private final StringBuilder buffer = new StringBuilder(); @@ -72,7 +72,7 @@ public void characters(char[] ch, int start, int length) throws SAXException { @Override public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { buffer.setLength(0); - switch(qName) { + switch (qName) { case "osm": parseMode = NoteParseMode.API; notes = new ArrayList<>(100); @@ -91,7 +91,7 @@ public void startElement(String uri, String localName, String qName, Attributes } //The rest only applies for dump mode - switch(qName) { + switch (qName) { case "note": thisNote = parseNoteFull(attrs); break; @@ -112,9 +112,11 @@ public void endElement(String namespaceURI, String localName, String qName) { notes.add(thisNote); } if ("comment".equals(qName)) { - User commentUser = User.createOsmUser(commentUid, commentUsername); + final User commentUser; if (commentUid == 0) { commentUser = User.getAnonymous(); + } else { + commentUser = User.createOsmUser(commentUid, commentUsername); } if (parseMode == NoteParseMode.API) { commentIsNew = false; @@ -176,8 +178,8 @@ public void endDocument() throws SAXException { } static LatLon parseLatLon(UnaryOperator attrs) { - double lat = Double.parseDouble(attrs.apply("lat")); - double lon = Double.parseDouble(attrs.apply("lon")); + final var lat = Double.parseDouble(attrs.apply("lat")); + final var lon = Double.parseDouble(attrs.apply("lon")); return new LatLon(lat, lon); } @@ -194,7 +196,7 @@ static Note parseNoteFull(Attributes attrs) { } static Note parseNoteFull(UnaryOperator attrs) { - Note note = parseNoteBasic(attrs); + final var note = parseNoteBasic(attrs); String id = attrs.apply("id"); if (id != null) { note.setId(Long.parseLong(id)); diff --git a/src/org/openstreetmap/josm/io/OsmPbfReader.java b/src/org/openstreetmap/josm/io/OsmPbfReader.java index ffb7959e574..900e08a3015 100644 --- a/src/org/openstreetmap/josm/io/OsmPbfReader.java +++ b/src/org/openstreetmap/josm/io/OsmPbfReader.java @@ -15,7 +15,7 @@ import java.util.Map; import java.util.Set; -import org.apache.commons.compress.utils.CountingInputStream; +import org.apache.commons.io.input.BoundedInputStream; import org.openstreetmap.josm.data.Bounds; import org.openstreetmap.josm.data.DataSource; import org.openstreetmap.josm.data.coor.LatLon; @@ -87,14 +87,14 @@ protected DataSet doParseDataSet(InputStream source, ProgressMonitor progressMon } private void parse(InputStream source) throws IllegalDataException, IOException { - final CountingInputStream inputStream; + final BoundedInputStream inputStream; if (source.markSupported()) { - inputStream = new CountingInputStream(source); + inputStream = new BoundedInputStream(source); } else { - inputStream = new CountingInputStream(new BufferedInputStream(source)); + inputStream = new BoundedInputStream(new BufferedInputStream(source)); } - try (ProtobufParser parser = new ProtobufParser(inputStream)) { - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try (var parser = new ProtobufParser(inputStream)) { + final var baos = new ByteArrayOutputStream(); HeaderBlock headerBlock = null; BlobHeader blobHeader = null; while (parser.hasNext() && !this.cancel) { @@ -105,7 +105,7 @@ private void parse(InputStream source) throws IllegalDataException, IOException throw new IllegalDataException("Too many header blocks in protobuf"); } // OSM PBF is fun -- it has *nested* pbf data - Blob blob = parseBlob(blobHeader, inputStream, parser, baos); + final var blob = parseBlob(blobHeader, inputStream, parser, baos); headerBlock = parseHeaderBlock(blob, baos); checkRequiredFeatures(headerBlock); blobHeader = null; @@ -113,7 +113,7 @@ private void parse(InputStream source) throws IllegalDataException, IOException if (headerBlock == null) { throw new IllegalStateException("A header block must occur before the first data block"); } - Blob blob = parseBlob(blobHeader, inputStream, parser, baos); + final var blob = parseBlob(blobHeader, inputStream, parser, baos); parseDataBlock(baos, headerBlock, blob); blobHeader = null; } // Other software *may* extend the FileBlocks (from just "OSMHeader" and "OSMData"), so don't throw an error. @@ -132,15 +132,15 @@ private void parse(InputStream source) throws IllegalDataException, IOException * @throws IllegalDataException If the OSM PBF is (probably) corrupted */ @Nonnull - private static BlobHeader parseBlobHeader(CountingInputStream cis, ByteArrayOutputStream baos, ProtobufParser parser) + private static BlobHeader parseBlobHeader(BoundedInputStream cis, ByteArrayOutputStream baos, ProtobufParser parser) throws IOException, IllegalDataException { String type = null; byte[] indexData = null; int datasize = Integer.MIN_VALUE; - int length = 0; - long start = cis.getBytesRead(); - while (parser.hasNext() && (length == 0 || cis.getBytesRead() - start < length)) { - final ProtobufRecord current = new ProtobufRecord(baos, parser); + var length = 0; + long start = cis.getCount(); + while (parser.hasNext() && (length == 0 || cis.getCount() - start < length)) { + final var current = new ProtobufRecord(baos, parser); switch (current.getField()) { case 1: type = current.asString(); @@ -152,7 +152,7 @@ private static BlobHeader parseBlobHeader(CountingInputStream cis, ByteArrayOutp datasize = current.asUnsignedVarInt().intValue(); break; default: - start = cis.getBytesRead(); + start = cis.getCount(); length += current.asUnsignedVarInt().intValue(); if (length > MAX_BLOBHEADER_SIZE) { // There is a hard limit of 64 KiB for the BlobHeader. It *should* be less than 32 KiB. throw new IllegalDataException("OSM PBF BlobHeader is too large. PBF is probably corrupted. (" + @@ -180,15 +180,15 @@ private static BlobHeader parseBlobHeader(CountingInputStream cis, ByteArrayOutp * @throws IOException If one of the streams has an issue */ @Nonnull - private static Blob parseBlob(BlobHeader header, CountingInputStream cis, ProtobufParser parser, ByteArrayOutputStream baos) + private static Blob parseBlob(BlobHeader header, BoundedInputStream cis, ProtobufParser parser, ByteArrayOutputStream baos) throws IOException { - long start = cis.getBytesRead(); + long start = cis.getCount(); int size = Integer.MIN_VALUE; Blob.CompressionType type = null; ProtobufRecord current; // Needed since size and compression type + compression data may be in a different order byte[] bytes = null; - while (parser.hasNext() && cis.getBytesRead() - start < header.dataSize()) { + while (parser.hasNext() && cis.getCount() - start < header.dataSize()) { current = new ProtobufRecord(baos, parser); switch (current.getField()) { case 1: @@ -238,18 +238,18 @@ private static Blob parseBlob(BlobHeader header, CountingInputStream cis, Protob */ @Nonnull private static HeaderBlock parseHeaderBlock(Blob blob, ByteArrayOutputStream baos) throws IOException { - try (InputStream blobInput = blob.inputStream(); - ProtobufParser parser = new ProtobufParser(blobInput)) { + try (var blobInput = blob.inputStream(); + var parser = new ProtobufParser(blobInput)) { BBox bbox = null; - List required = new ArrayList<>(); - List optional = new ArrayList<>(); + final var required = new ArrayList(); + final var optional = new ArrayList(); String program = null; String source = null; Long osmosisReplicationTimestamp = null; Long osmosisReplicationSequenceNumber = null; String osmosisReplicationBaseUrl = null; while (parser.hasNext()) { - final ProtobufRecord current = new ProtobufRecord(baos, parser); + final var current = new ProtobufRecord(baos, parser); switch (current.getField()) { case 1: // bbox bbox = parseBBox(baos, current); @@ -310,15 +310,15 @@ private static void checkRequiredFeatures(HeaderBlock headerBlock) throws Illega private void parseDataBlock(ByteArrayOutputStream baos, HeaderBlock headerBlock, Blob blob) throws IOException, IllegalDataException { String[] stringTable = null; // field 1, note that stringTable[0] is a delimiter, so it is always blank and unused // field 2 -- we cannot parse these live just in case the following fields come later - List primitiveGroups = new ArrayList<>(); - int granularity = 100; // field 17 + final var primitiveGroups = new ArrayList(); + var granularity = 100; // field 17 long latOffset = 0; // field 19 long lonOffset = 0; // field 20 - int dateGranularity = 1000; // field 18, default is milliseconds since the 1970 epoch - try (InputStream inputStream = blob.inputStream(); - ProtobufParser parser = new ProtobufParser(inputStream)) { + var dateGranularity = 1000; // field 18, default is milliseconds since the 1970 epoch + try (var inputStream = blob.inputStream(); + var parser = new ProtobufParser(inputStream)) { while (parser.hasNext()) { - ProtobufRecord protobufRecord = new ProtobufRecord(baos, parser); + final var protobufRecord = new ProtobufRecord(baos, parser); switch (protobufRecord.getField()) { case 1: stringTable = parseStringTable(baos, protobufRecord.getBytes()); @@ -342,9 +342,9 @@ private void parseDataBlock(ByteArrayOutputStream baos, HeaderBlock headerBlock, } } } - final PrimitiveBlockRecord primitiveBlockRecord = new PrimitiveBlockRecord(stringTable, granularity, latOffset, lonOffset, + final var primitiveBlockRecord = new PrimitiveBlockRecord(stringTable, granularity, latOffset, lonOffset, dateGranularity); - final DataSet ds = getDataSet(); + final var ds = getDataSet(); if (!primitiveGroups.isEmpty() && headerBlock.bbox() != null) { try { ds.beginUpdate(); @@ -374,14 +374,14 @@ private void parseDataBlock(ByteArrayOutputStream baos, HeaderBlock headerBlock, */ @Nullable private static BBox parseBBox(ByteArrayOutputStream baos, ProtobufRecord current) throws IOException { - try (ByteArrayInputStream bboxInputStream = new ByteArrayInputStream(current.getBytes()); - ProtobufParser bboxParser = new ProtobufParser(bboxInputStream)) { + try (var bboxInputStream = new ByteArrayInputStream(current.getBytes()); + var bboxParser = new ProtobufParser(bboxInputStream)) { double left = Double.NaN; double right = Double.NaN; double top = Double.NaN; double bottom = Double.NaN; while (bboxParser.hasNext()) { - ProtobufRecord protobufRecord = new ProtobufRecord(baos, bboxParser); + final var protobufRecord = new ProtobufRecord(baos, bboxParser); if (protobufRecord.getType() == WireType.VARINT) { double value = protobufRecord.asSignedVarInt().longValue() * NANO_DEGREES; switch (protobufRecord.getField()) { @@ -418,11 +418,11 @@ private static BBox parseBBox(ByteArrayOutputStream baos, ProtobufRecord current */ @Nonnull private static String[] parseStringTable(ByteArrayOutputStream baos, byte[] bytes) throws IOException { - try (ByteArrayInputStream is = new ByteArrayInputStream(bytes); - ProtobufParser parser = new ProtobufParser(is)) { - List list = new ArrayList<>(); + try (var is = new ByteArrayInputStream(bytes); + var parser = new ProtobufParser(is)) { + final var list = new ArrayList(); while (parser.hasNext()) { - ProtobufRecord protobufRecord = new ProtobufRecord(baos, parser); + final var protobufRecord = new ProtobufRecord(baos, parser); if (protobufRecord.getField() == 1) { list.add(protobufRecord.asString().intern()); // field is technically repeated bytes } @@ -443,10 +443,10 @@ private static String[] parseStringTable(ByteArrayOutputStream baos, byte[] byte */ private void parsePrimitiveGroup(ByteArrayOutputStream baos, byte[] bytes, PrimitiveBlockRecord primitiveBlockRecord) throws IllegalDataException, IOException { - try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes); - ProtobufParser parser = new ProtobufParser(bais)) { + try (var bais = new ByteArrayInputStream(bytes); + var parser = new ProtobufParser(bais)) { while (parser.hasNext()) { - ProtobufRecord protobufRecord = new ProtobufRecord(baos, parser); + final var protobufRecord = new ProtobufRecord(baos, parser); switch (protobufRecord.getField()) { case 1: // Nodes, repeated parseNode(baos, protobufRecord.getBytes(), primitiveBlockRecord); @@ -479,16 +479,16 @@ private void parsePrimitiveGroup(ByteArrayOutputStream baos, byte[] bytes, Primi */ private void parseNode(ByteArrayOutputStream baos, byte[] bytes, PrimitiveBlockRecord primitiveBlockRecord) throws IllegalDataException, IOException { - try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes); - ProtobufParser parser = new ProtobufParser(bais)) { + try (var bais = new ByteArrayInputStream(bytes); + var parser = new ProtobufParser(bais)) { long id = Long.MIN_VALUE; - List keys = new ArrayList<>(); - List values = new ArrayList<>(); + final var keys = new ArrayList(); + final var values = new ArrayList(); Info info = null; long lat = Long.MIN_VALUE; long lon = Long.MIN_VALUE; while (parser.hasNext()) { - ProtobufRecord protobufRecord = new ProtobufRecord(baos, parser); + final var protobufRecord = new ProtobufRecord(baos, parser); switch (protobufRecord.getField()) { case 1: id = protobufRecord.asSignedVarInt().intValue(); @@ -518,7 +518,7 @@ private void parseNode(ByteArrayOutputStream baos, byte[] bytes, PrimitiveBlockR if (id == Long.MIN_VALUE || lat == Long.MIN_VALUE || lon == Long.MIN_VALUE) { throw new IllegalDataException("OSM PBF did not provide all the required node information"); } - NodeData node = new NodeData(id); + final var node = new NodeData(id); node.setCoor(calculateLatLon(primitiveBlockRecord, lat, lon)); addTags(node, keys, values); if (info != null) { @@ -546,10 +546,10 @@ private void parseDenseNodes(ByteArrayOutputStream baos, byte[] bytes, Primitive long[] lons = EMPTY_LONG; long[] keyVals = EMPTY_LONG; // technically can be int Info[] denseInfo = null; - try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes); - ProtobufParser parser = new ProtobufParser(bais)) { + try (var bais = new ByteArrayInputStream(bytes); + var parser = new ProtobufParser(bais)) { while (parser.hasNext()) { - ProtobufRecord protobufRecord = new ProtobufRecord(baos, parser); + final var protobufRecord = new ProtobufRecord(baos, parser); switch (protobufRecord.getField()) { case 1: // packed node ids, DELTA encoded long[] tids = decodePackedSInt64(new ProtobufPacked(protobufRecord.getBytes()).getArray()); @@ -575,17 +575,17 @@ private void parseDenseNodes(ByteArrayOutputStream baos, byte[] bytes, Primitive } } - int keyValIndex = 0; // This index must not reset between nodes, and must always increment + var keyValIndex = 0; // This index must not reset between nodes, and must always increment if (ids.length == lats.length && lats.length == lons.length && (denseInfo == null || denseInfo.length == lons.length)) { long id = 0; long lat = 0; long lon = 0; - for (int i = 0; i < ids.length; i++) { + for (var i = 0; i < ids.length; i++) { final NodeData node; id += ids[i]; node = new NodeData(id); if (denseInfo != null) { - Info info = denseInfo[i]; + final var info = denseInfo[i]; setOsmPrimitiveData(primitiveBlockRecord, node, info); } else { ds.setUploadPolicy(UploadPolicy.DISCOURAGED); @@ -637,10 +637,10 @@ private void parseWay(ByteArrayOutputStream baos, byte[] bytes, PrimitiveBlockRe long[] refs = EMPTY_LONG; // DELTA encoded // We don't do live drawing, so we don't care about lats and lons (we essentially throw them away with the current parser) // This is for the optional feature "LocationsOnWays" - try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes); - ProtobufParser parser = new ProtobufParser(bais)) { + try (var bais = new ByteArrayInputStream(bytes); + var parser = new ProtobufParser(bais)) { while (parser.hasNext()) { - ProtobufRecord protobufRecord = new ProtobufRecord(baos, parser); + final var protobufRecord = new ProtobufRecord(baos, parser); switch (protobufRecord.getField()) { case 1: id = protobufRecord.asUnsignedVarInt().longValue(); @@ -671,8 +671,8 @@ private void parseWay(ByteArrayOutputStream baos, byte[] bytes, PrimitiveBlockRe if (refs.length == 0 || id == Long.MIN_VALUE) { throw new IllegalDataException("A way with either no id or no nodes was found"); } - WayData wayData = new WayData(id); - List nodeIds = new ArrayList<>(refs.length); + final var wayData = new WayData(id); + final var nodeIds = new ArrayList(refs.length); long ref = 0; for (long tRef : refs) { ref += tRef; @@ -700,16 +700,16 @@ private void parseWay(ByteArrayOutputStream baos, byte[] bytes, PrimitiveBlockRe private void parseRelation(ByteArrayOutputStream baos, byte[] bytes, PrimitiveBlockRecord primitiveBlockRecord) throws IllegalDataException, IOException { long id = Long.MIN_VALUE; - List keys = new ArrayList<>(); - List values = new ArrayList<>(); + final var keys = new ArrayList(); + final var values = new ArrayList(); Info info = null; long[] rolesStringId = EMPTY_LONG; // Technically int long[] memids = EMPTY_LONG; long[] types = EMPTY_LONG; // Technically an enum - try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes); - ProtobufParser parser = new ProtobufParser(bais)) { + try (var bais = new ByteArrayInputStream(bytes); + var parser = new ProtobufParser(bais)) { while (parser.hasNext()) { - ProtobufRecord protobufRecord = new ProtobufRecord(baos, parser); + final var protobufRecord = new ProtobufRecord(baos, parser); switch (protobufRecord.getField()) { case 1: id = protobufRecord.asUnsignedVarInt().longValue(); @@ -746,7 +746,7 @@ private void parseRelation(ByteArrayOutputStream baos, byte[] bytes, PrimitiveBl if (keys.size() != values.size() || rolesStringId.length != memids.length || memids.length != types.length || id == Long.MIN_VALUE) { throw new IllegalDataException("OSM PBF contains a bad relation definition"); } - RelationData data = new RelationData(id); + final var data = new RelationData(id); if (info != null) { setOsmPrimitiveData(primitiveBlockRecord, data, info); } else { @@ -756,7 +756,7 @@ private void parseRelation(ByteArrayOutputStream baos, byte[] bytes, PrimitiveBl OsmPrimitiveType[] valueTypes = OsmPrimitiveType.values(); List members = new ArrayList<>(rolesStringId.length); long memberId = 0; - for (int i = 0; i < rolesStringId.length; i++) { + for (var i = 0; i < rolesStringId.length; i++) { String role = primitiveBlockRecord.stringTable[(int) rolesStringId[i]]; memberId += memids[i]; OsmPrimitiveType type = valueTypes[(int) types[i]]; @@ -776,16 +776,16 @@ private void parseRelation(ByteArrayOutputStream baos, byte[] bytes, PrimitiveBl */ @Nonnull private static Info parseInfo(ByteArrayOutputStream baos, byte[] bytes) throws IOException { - try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes); - ProtobufParser parser = new ProtobufParser(bais)) { + try (var bais = new ByteArrayInputStream(bytes); + var parser = new ProtobufParser(bais)) { int version = -1; Long timestamp = null; Long changeset = null; Integer uid = null; Integer userSid = null; - boolean visible = true; + var visible = true; while (parser.hasNext()) { - ProtobufRecord protobufRecord = new ProtobufRecord(baos, parser); + final var protobufRecord = new ProtobufRecord(baos, parser); switch (protobufRecord.getField()) { case 1: version = protobufRecord.asUnsignedVarInt().intValue(); @@ -838,7 +838,7 @@ private static void addTags(Tagged primitive, List keys, List va return; } Map tagMap = new HashMap<>(keys.size()); - for (int i = 0; i < keys.size(); i++) { + for (var i = 0; i < keys.size(); i++) { tagMap.put(keys.get(i), values.get(i)); } primitive.putAll(tagMap); @@ -878,7 +878,7 @@ private static void setOsmPrimitiveData(PrimitiveBlockRecord primitiveBlockRecor */ @Nonnull private static long[] decodePackedSInt64(long[] numbers) { - for (int i = 0; i < numbers.length; i++) { + for (var i = 0; i < numbers.length; i++) { numbers[i] = ProtobufParser.decodeZigZag(numbers[i]); } return numbers; @@ -921,10 +921,10 @@ private static Info[] parseDenseInfo(ByteArrayOutputStream baos, byte[] bytes) t long[] uid = EMPTY_LONG; // technically int long[] userSid = EMPTY_LONG; // technically int long[] visible = EMPTY_LONG; // optional, true if not set, technically booleans - try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes); - ProtobufParser parser = new ProtobufParser(bais)) { + try (var bais = new ByteArrayInputStream(bytes); + var parser = new ProtobufParser(bais)) { while (parser.hasNext()) { - ProtobufRecord protobufRecord = new ProtobufRecord(baos, parser); + final var protobufRecord = new ProtobufRecord(baos, parser); switch (protobufRecord.getField()) { case 1: long[] tVersion = new ProtobufPacked(protobufRecord.getBytes()).getArray(); @@ -955,12 +955,12 @@ private static Info[] parseDenseInfo(ByteArrayOutputStream baos, byte[] bytes) t } } if (version.length > 0) { - Info[] infos = new Info[version.length]; + final var infos = new Info[version.length]; long lastTimestamp = 0; // delta encoded long lastChangeset = 0; // delta encoded long lastUid = 0; // delta encoded, long lastUserSid = 0; // delta encoded, string id for username - for (int i = 0; i < version.length; i++) { + for (var i = 0; i < version.length; i++) { if (timestamp.length > i) lastTimestamp += timestamp[i]; if (changeset.length > i) diff --git a/src/org/openstreetmap/josm/tools/ImageResizeMode.java b/src/org/openstreetmap/josm/tools/ImageResizeMode.java index a6eccdcdc96..568b72adaac 100644 --- a/src/org/openstreetmap/josm/tools/ImageResizeMode.java +++ b/src/org/openstreetmap/josm/tools/ImageResizeMode.java @@ -86,8 +86,8 @@ void prepareGraphics(Dimension icon, BufferedImage image, Graphics2D g) { * @throws IllegalArgumentException if renderer or sourceIcon is null */ BufferedImage createBufferedImage(Dimension dim, Dimension icon, Consumer renderer, Image sourceIcon) { - final Dimension real = computeDimension(dim, icon); - final BufferedImage bufferedImage = new BufferedImage(real.width, real.height, BufferedImage.TYPE_INT_ARGB); + final var real = computeDimension(dim, icon); + final var bufferedImage = new BufferedImage(real.width, real.height, BufferedImage.TYPE_INT_ARGB); final Graphics2D g = bufferedImage.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if (renderer != null) { @@ -118,6 +118,7 @@ void prepareGraphics(Dimension icon, BufferedImage image, Graphics2D g) { * @param dim the desired image dimension * @return a cache key */ + @SuppressWarnings("EnumOrdinal") int cacheKey(Dimension dim) { return (ordinal() << 28) | ((dim.width & 0xfff) << 16) | (dim.height & 0xfff); } diff --git a/src/org/openstreetmap/josm/tools/Utils.java b/src/org/openstreetmap/josm/tools/Utils.java index 9d29c970906..fc8efb0a3df 100644 --- a/src/org/openstreetmap/josm/tools/Utils.java +++ b/src/org/openstreetmap/josm/tools/Utils.java @@ -29,7 +29,6 @@ import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; -import java.nio.file.attribute.FileTime; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.Bidi; @@ -152,8 +151,8 @@ public static SubclassFilteredCollection filteredCollecti * @return The index of the first item or -1 if none was found. */ public static int indexOf(Iterable collection, Predicate predicate) { - int i = 0; - for (T item : collection) { + var i = 0; + for (var item : collection) { if (predicate.test(item)) return i; i++; @@ -185,7 +184,7 @@ public static void ensure(boolean condition, String message, Object...data) { public static int mod(int a, int n) { if (n <= 0) throw new IllegalArgumentException("n must be <= 0 but is " + n); - int res = a % n; + var res = a % n; if (res < 0) { res += n; } @@ -303,10 +302,10 @@ public static void copyDirectory(File in, File out) throws IOException { if (!out.exists() && !out.mkdirs()) { Logging.warn("Unable to create directory "+out.getPath()); } - File[] files = in.listFiles(); + var files = in.listFiles(); if (files != null) { - for (File f : files) { - File target = new File(out, f.getName()); + for (var f : files) { + var target = new File(out, f.getName()); if (f.isDirectory()) { copyDirectory(f, target); } else { @@ -324,9 +323,9 @@ public static void copyDirectory(File in, File out) throws IOException { */ public static boolean deleteDirectory(File path) { if (path.exists()) { - File[] files = path.listFiles(); + var files = path.listFiles(); if (files != null) { - for (File file : files) { + for (var file : files) { if (file.isDirectory()) { deleteDirectory(file); } else { @@ -371,7 +370,7 @@ public static boolean deleteFile(File file) { * @since 9296 */ public static boolean deleteFile(File file, String warnMsg) { - boolean result = file.delete(); + var result = file.delete(); if (!result) { Logging.warn(tr(warnMsg, file.getPath())); } @@ -397,7 +396,7 @@ public static boolean mkDirs(File dir) { * @since 9645 */ public static boolean mkDirs(File dir, String warnMsg) { - boolean result = dir.mkdirs(); + var result = dir.mkdirs(); if (!result) { Logging.warn(tr(warnMsg, dir.getPath())); } @@ -497,8 +496,8 @@ public static String md5Hex(String data) { } catch (NoSuchAlgorithmException e) { throw new JosmRuntimeException(e); } - byte[] byteData = data.getBytes(StandardCharsets.UTF_8); - byte[] byteDigest = md.digest(byteData); + var byteData = data.getBytes(StandardCharsets.UTF_8); + var byteDigest = md.digest(byteData); return toHexString(byteDigest); } @@ -517,13 +516,13 @@ public static String toHexString(byte[] bytes) { return ""; } - final int len = bytes.length; + final var len = bytes.length; if (len == 0) { return ""; } - char[] hexChars = new char[len * 2]; - int j = 0; + var hexChars = new char[len * 2]; + var j = 0; for (final int v : bytes) { hexChars[j++] = HEX_ARRAY[(v & 0xf0) >> 4]; hexChars[j++] = HEX_ARRAY[v & 0xf]; @@ -541,25 +540,25 @@ public static String toHexString(byte[] bytes) { * @return the list of sorted objects */ public static List topologicalSort(final MultiMap dependencies) { - MultiMap deps = new MultiMap<>(); - for (T key : dependencies.keySet()) { + var deps = new MultiMap(); + for (var key : dependencies.keySet()) { deps.putVoid(key); - for (T val : dependencies.get(key)) { + for (var val : dependencies.get(key)) { deps.putVoid(val); deps.put(key, val); } } - int size = deps.size(); + var size = deps.size(); List sorted = new ArrayList<>(); - for (int i = 0; i < size; ++i) { - T parentless = deps.keySet().stream() + for (var i = 0; i < size; ++i) { + var parentless = deps.keySet().stream() .filter(key -> deps.get(key).isEmpty()) .findFirst().orElse(null); if (parentless == null) throw new JosmRuntimeException("parentless"); sorted.add(parentless); deps.remove(parentless); - for (T key : deps.keySet()) { + for (var key : deps.keySet()) { deps.remove(key, parentless); } } @@ -679,7 +678,7 @@ public static Map toUnmodifiableMap(Map map) { if (isEmpty(map)) { return Collections.emptyMap(); } else if (map.size() == 1) { - final Map.Entry entry = map.entrySet().iterator().next(); + final var entry = map.entrySet().iterator().next(); return Collections.singletonMap(entry.getKey(), entry.getValue()); } else if (mapOfEntries != null) { try { @@ -795,16 +794,16 @@ public static String strip(final String str, final String skipChars) { return str; } - int start = 0; - int end = str.length(); - boolean leadingSkipChar = true; + var start = 0; + var end = str.length(); + var leadingSkipChar = true; while (leadingSkipChar && start < end) { leadingSkipChar = isStrippedChar(str.charAt(start), skipChars); if (leadingSkipChar) { start++; } } - boolean trailingSkipChar = true; + var trailingSkipChar = true; while (trailingSkipChar && end > start) { trailingSkipChar = isStrippedChar(str.charAt(end - 1), skipChars); if (trailingSkipChar) { @@ -866,9 +865,9 @@ public static String execOutput(List command, long timeout, TimeUnit uni if (Logging.isDebugEnabled()) { Logging.debug(String.join(" ", command)); } - Path out = Files.createTempFile("josm_exec_" + command.get(0) + "_", ".txt"); + var out = Files.createTempFile("josm_exec_" + command.get(0) + "_", ".txt"); try { - Process p = new ProcessBuilder(command).redirectErrorStream(true).redirectOutput(out.toFile()).start(); + var p = new ProcessBuilder(command).redirectErrorStream(true).redirectOutput(out.toFile()).start(); if (!p.waitFor(timeout, unit) || p.exitValue() != 0) { throw new ExecutionException(command.toString(), null); } @@ -888,11 +887,11 @@ public static String execOutput(List command, long timeout, TimeUnit uni * @since 6245 */ public static File getJosmTempDir() { - String tmpDir = getSystemProperty("java.io.tmpdir"); + var tmpDir = getSystemProperty("java.io.tmpdir"); if (tmpDir == null) { return null; } - File josmTmpDir = new File(tmpDir, "JOSM"); + final var josmTmpDir = new File(tmpDir, "JOSM"); if (!josmTmpDir.exists() && !josmTmpDir.mkdirs()) { Logging.warn("Unable to create temp directory " + josmTmpDir); } @@ -920,15 +919,15 @@ public static String getDurationString(long elapsedTime) { } // Is it less than 1 hour ? if (elapsedTime < MILLIS_OF_HOUR) { - final long min = elapsedTime / MILLIS_OF_MINUTE; + final var min = elapsedTime / MILLIS_OF_MINUTE; return String.format("%d %s %d %s", min, tr("min"), (elapsedTime - min * MILLIS_OF_MINUTE) / MILLIS_OF_SECOND, tr("s")); } // Is it less than 1 day ? if (elapsedTime < MILLIS_OF_DAY) { - final long hour = elapsedTime / MILLIS_OF_HOUR; + final var hour = elapsedTime / MILLIS_OF_HOUR; return String.format("%d %s %d %s", hour, tr("h"), (elapsedTime - hour * MILLIS_OF_HOUR) / MILLIS_OF_MINUTE, tr("min")); } - long days = elapsedTime / MILLIS_OF_DAY; + var days = elapsedTime / MILLIS_OF_DAY; return String.format("%d %s %d %s", days, trn("day", "days", days), (elapsedTime - days * MILLIS_OF_DAY) / MILLIS_OF_HOUR, tr("h")); } @@ -943,7 +942,7 @@ public static String getSizeString(long bytes, Locale locale) { if (bytes < 0) { throw new IllegalArgumentException("bytes must be >= 0"); } - int unitIndex = 0; + var unitIndex = 0; double value = bytes; while (value >= 1024 && unitIndex < SIZE_UNITS.length) { value /= 1024; @@ -967,11 +966,11 @@ public static String getSizeString(long bytes, Locale locale) { */ public static String getPositionListString(List positionList) { Collections.sort(positionList); - final StringBuilder sb = new StringBuilder(32); + final var sb = new StringBuilder(32); sb.append(positionList.get(0)); - int cnt = 0; + var cnt = 0; int last = positionList.get(0); - for (int i = 1; i < positionList.size(); ++i) { + for (var i = 1; i < positionList.size(); ++i) { int cur = positionList.get(i); if (cur == last + 1) { ++cnt; @@ -1030,9 +1029,9 @@ public static T cast(Object o, Class klass) { * @since 6639 */ public static Throwable getRootCause(Throwable t) { - Throwable result = t; + var result = t; if (result != null) { - Throwable cause = result.getCause(); + var cause = result.getCause(); while (cause != null && !cause.equals(result)) { result = cause; cause = result.getCause(); @@ -1050,7 +1049,7 @@ public static Throwable getRootCause(Throwable t) { * @since 6717 */ public static T[] addInArrayCopy(T[] array, T item) { - T[] biggerCopy = Arrays.copyOf(array, array.length + 1); + var biggerCopy = Arrays.copyOf(array, array.length + 1); biggerCopy[array.length] = item; return biggerCopy; } @@ -1063,7 +1062,7 @@ public static T[] addInArrayCopy(T[] array, T item) { * @throws IllegalArgumentException if maxLength is less than the length of "..." */ public static String shortenString(String s, int maxLength) { - final String ellipses = "..."; + final var ellipses = "..."; CheckParameterUtil.ensureThat(maxLength >= ellipses.length(), "maxLength is shorter than " + ellipses.length()); if (s != null && s.length() > maxLength) { return s.substring(0, maxLength - ellipses.length()) + ellipses; @@ -1101,7 +1100,7 @@ public static Collection limit(Collection elements, int maxElements, T } else { if (elements.size() > maxElements) { final Collection r = new ArrayList<>(maxElements); - final Iterator it = elements.iterator(); + final var it = elements.iterator(); while (r.size() < maxElements - 1) { r.add(it.next()); } @@ -1126,12 +1125,12 @@ public static String fixURLQuery(String url) { if (url == null || url.indexOf('?') == -1) return url; - String query = url.substring(url.indexOf('?') + 1); + final var query = url.substring(url.indexOf('?') + 1); - StringBuilder sb = new StringBuilder(url.substring(0, url.indexOf('?') + 1)); + final var sb = new StringBuilder(url.substring(0, url.indexOf('?') + 1)); - for (int i = 0; i < query.length(); i++) { - String c = query.substring(i, i + 1); + for (var i = 0; i < query.length(); i++) { + final var c = query.substring(i, i + 1); if (URL_CHARS.contains(c)) { sb.append(c); } else { @@ -1152,7 +1151,7 @@ public static String fixURLQuery(String url) { * @since 8304 */ public static String encodeUrl(String s) { - final String enc = StandardCharsets.UTF_8.name(); + final var enc = StandardCharsets.UTF_8.name(); try { return URLEncoder.encode(s, enc); } catch (UnsupportedEncodingException e) { @@ -1172,7 +1171,7 @@ public static String encodeUrl(String s) { * @since 8304 */ public static String decodeUrl(String s) { - final String enc = StandardCharsets.UTF_8.name(); + final var enc = StandardCharsets.UTF_8.name(); try { return URLDecoder.decode(s, enc); } catch (UnsupportedEncodingException e) { @@ -1220,7 +1219,7 @@ public static ThreadFactory newThreadFactory(final String nameFormat, final int final AtomicLong count = new AtomicLong(0); @Override public Thread newThread(final Runnable runnable) { - final Thread thread = new Thread(runnable, String.format(Locale.ENGLISH, nameFormat, count.getAndIncrement())); + final var thread = new Thread(runnable, String.format(Locale.ENGLISH, nameFormat, count.getAndIncrement())); thread.setPriority(threadPriority); return thread; } @@ -1298,7 +1297,7 @@ public static int getLevenshteinDistance(String s, String t) { */ public static boolean isSimilar(String string1, String string2) { // check plain strings - int distance = getLevenshteinDistance(string1, string2); + var distance = getLevenshteinDistance(string1, string2); // check if only the case differs, so we don't consider large distance as different strings if (distance > 2 && string1.length() == string2.length()) { @@ -1339,7 +1338,7 @@ public static double getStandardDeviation(double[] values, double mean) { mean = Arrays.stream(values).average().orElse(0); } - for (double length : values) { + for (var length : values) { standardDeviation += Math.pow(length - mean, 2); } @@ -1360,9 +1359,9 @@ public static int[][] groupIntegers(int... integers) { return EMPTY_INT_INT_ARRAY; } List groups = new ArrayList<>(); - int[] current = {Integer.MIN_VALUE, Integer.MIN_VALUE}; + var current = new int[]{Integer.MIN_VALUE, Integer.MIN_VALUE}; groups.add(current); - for (int row : integers) { + for (var row : integers) { if (current[0] == Integer.MIN_VALUE) { current[0] = row; current[1] = row; @@ -1397,7 +1396,7 @@ static final class JosmForkJoinWorkerThread extends ForkJoinWorkerThread { */ @SuppressWarnings("ThreadPriorityCheck") public static ForkJoinPool newForkJoinPool(String pref, final String nameFormat, final int threadPriority) { - int noThreads = Config.getPref().getInt(pref, Runtime.getRuntime().availableProcessors()); + final var noThreads = Config.getPref().getInt(pref, Runtime.getRuntime().availableProcessors()); return new ForkJoinPool(noThreads, new ForkJoinPool.ForkJoinWorkerThreadFactory() { final AtomicLong count = new AtomicLong(0); @Override @@ -1467,7 +1466,7 @@ public static String getSystemProperty(String key) { public static String updateSystemProperty(String key, String value) { if (value != null) { try { - String old = System.setProperty(key, value); + var old = System.setProperty(key, value); if (Logging.isDebugEnabled() && !value.equals(old)) { if (!key.toLowerCase(Locale.ENGLISH).contains("password")) { Logging.debug("System property '" + key + "' set to '" + value + "'. Old value was '" + old + '\''); @@ -1493,7 +1492,7 @@ public static String updateSystemProperty(String key, String value) { * @since 8404 */ public static boolean hasExtension(String filename, String... extensions) { - String name = filename.toLowerCase(Locale.ENGLISH).replace("?format=raw", ""); + var name = filename.toLowerCase(Locale.ENGLISH).replace("?format=raw", ""); return Arrays.stream(extensions) .anyMatch(ext -> name.endsWith('.' + ext.toLowerCase(Locale.ENGLISH))); } @@ -1522,11 +1521,11 @@ public static byte[] readBytesFromStream(InputStream stream) throws IOException if (stream == null) { return new byte[0]; } - try (ByteArrayOutputStream bout = new ByteArrayOutputStream(stream.available())) { - byte[] buffer = new byte[8192]; - boolean finished = false; + try (stream; var bout = new ByteArrayOutputStream(stream.available())) { + final var buffer = new byte[8192]; + var finished = false; do { - int read = stream.read(buffer); + var read = stream.read(buffer); if (read >= 0) { bout.write(buffer, 0, read); } else { @@ -1536,8 +1535,6 @@ public static byte[] readBytesFromStream(InputStream stream) throws IOException if (bout.size() == 0) return new byte[0]; return bout.toByteArray(); - } finally { - stream.close(); } } @@ -1602,19 +1599,19 @@ private static class DirectionString { * @return a list of GlyphVectors */ public static List getGlyphVectorsBidi(String string, Font font, FontRenderContext frc) { - List gvs = new ArrayList<>(); - Bidi bidi = new Bidi(string, Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT); - byte[] levels = new byte[bidi.getRunCount()]; - DirectionString[] dirStrings = new DirectionString[levels.length]; - for (int i = 0; i < levels.length; ++i) { + final var gvs = new ArrayList(); + final var bidi = new Bidi(string, Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT); + final var levels = new byte[bidi.getRunCount()]; + final var dirStrings = new DirectionString[levels.length]; + for (var i = 0; i < levels.length; ++i) { levels[i] = (byte) bidi.getRunLevel(i); - String substr = string.substring(bidi.getRunStart(i), bidi.getRunLimit(i)); - int dir = levels[i] % 2 == 0 ? Bidi.DIRECTION_LEFT_TO_RIGHT : Bidi.DIRECTION_RIGHT_TO_LEFT; + final var substr = string.substring(bidi.getRunStart(i), bidi.getRunLimit(i)); + final var dir = levels[i] % 2 == 0 ? Bidi.DIRECTION_LEFT_TO_RIGHT : Bidi.DIRECTION_RIGHT_TO_LEFT; dirStrings[i] = new DirectionString(dir, substr); } Bidi.reorderVisually(levels, 0, dirStrings, 0, levels.length); - for (DirectionString dirString : dirStrings) { - char[] chars = dirString.str.toCharArray(); + for (var dirString : dirStrings) { + var chars = dirString.str.toCharArray(); gvs.add(font.layoutGlyphVector(frc, chars, 0, chars.length, dirString.direction)); } return gvs; @@ -1711,7 +1708,7 @@ public static double toRadians(double angleDeg) { */ public static int getJavaVersion() { // Switch to Runtime.version() once we move past Java 8 - String version = Objects.requireNonNull(getSystemProperty("java.version")); + var version = Objects.requireNonNull(getSystemProperty("java.version")); if (version.startsWith("1.")) { version = version.substring(2); } @@ -1720,8 +1717,8 @@ public static int getJavaVersion() { // 9-ea // 9 // 9.0.1 - int dotPos = version.indexOf('.'); - int dashPos = version.indexOf('-'); + var dotPos = version.indexOf('.'); + var dashPos = version.indexOf('-'); return Integer.parseInt(version.substring(0, dotPos > -1 ? dotPos : dashPos > -1 ? dashPos : version.length())); } @@ -1733,7 +1730,7 @@ public static int getJavaVersion() { */ public static int getJavaUpdate() { // Switch to Runtime.version() once we move past Java 8 - String version = Objects.requireNonNull(getSystemProperty("java.version")); + var version = Objects.requireNonNull(getSystemProperty("java.version")); if (version.startsWith("1.")) { version = version.substring(2); } @@ -1744,14 +1741,14 @@ public static int getJavaUpdate() { // 9.0.1 // 17.0.4.1+1-LTS // $MAJOR.$MINOR.$SECURITY.$PATCH - int undePos = version.indexOf('_'); - int dashPos = version.indexOf('-'); + var undePos = version.indexOf('_'); + var dashPos = version.indexOf('-'); if (undePos > -1) { return Integer.parseInt(version.substring(undePos + 1, dashPos > -1 ? dashPos : version.length())); } - int firstDotPos = version.indexOf('.'); - int secondDotPos = version.indexOf('.', firstDotPos + 1); + var firstDotPos = version.indexOf('.'); + var secondDotPos = version.indexOf('.', firstDotPos + 1); if (firstDotPos == secondDotPos) { return 0; } @@ -1766,9 +1763,9 @@ public static int getJavaUpdate() { */ public static int getJavaBuild() { // Switch to Runtime.version() once we move past Java 8 - String version = Objects.requireNonNull(getSystemProperty("java.runtime.version")); - int bPos = version.indexOf('b'); - int pPos = version.indexOf('+'); + var version = Objects.requireNonNull(getSystemProperty("java.runtime.version")); + var bPos = version.indexOf('b'); + var pPos = version.indexOf('+'); try { return Integer.parseInt(version.substring(bPos > -1 ? bPos + 1 : pPos + 1)); } catch (NumberFormatException e) { @@ -1785,7 +1782,7 @@ public static int getJavaBuild() { public static Date getJavaExpirationDate() { try { Object value; - Class c = Class.forName("com.sun.deploy.config.BuiltInProperties"); + var c = Class.forName("com.sun.deploy.config.BuiltInProperties"); try { value = c.getDeclaredField("JRE_EXPIRATION_DATE").get(null); } catch (NoSuchFieldException e) { @@ -1809,19 +1806,19 @@ public static Date getJavaExpirationDate() { */ public static String getJavaLatestVersion() { try { - String[] versions = HttpClient.create( + var versions = HttpClient.create( new URL(Config.getPref().get( "java.baseline.version.url", Config.getUrls().getJOSMWebsite() + "/remote/oracle-java-update-baseline.version"))) .connect().fetchContent().split("\n", -1); if (getJavaVersion() <= 11 && isRunningWebStart()) { // OpenWebStart currently only has Java 11 - for (String version : versions) { + for (var version : versions) { if (version.startsWith("11")) { return version; } } } else if (getJavaVersion() <= 17) { - for (String version : versions) { + for (var version : versions) { if (version.startsWith("17")) { // Use current Java LTS return version; } @@ -1944,7 +1941,7 @@ public static InputStream openStream(URL url) throws IOException { try { return url.openStream(); } catch (FileNotFoundException | InvalidPathException e) { - URL betterUrl = betterJarUrl(url); + final var betterUrl = betterJarUrl(url); if (betterUrl != null) { try { return betterUrl.openStream(); @@ -1981,15 +1978,15 @@ public static URL betterJarUrl(URL jarUrl) throws IOException { */ public static URL betterJarUrl(URL jarUrl, URL defaultUrl) throws IOException { // Workaround to https://bugs.openjdk.java.net/browse/JDK-4523159 - String urlPath = jarUrl.getPath().replace("%20", " "); + var urlPath = jarUrl.getPath().replace("%20", " "); if (urlPath.startsWith("file:/") && urlPath.split("!", -1).length > 2) { // Locate jar file - int index = urlPath.lastIndexOf("!/"); - Path jarFile = Paths.get(urlPath.substring("file:/".length(), index)); - Path filename = jarFile.getFileName(); - FileTime jarTime = Files.readAttributes(jarFile, BasicFileAttributes.class).lastModifiedTime(); + var index = urlPath.lastIndexOf("!/"); + final var jarFile = Paths.get(urlPath.substring("file:/".length(), index)); + var filename = jarFile.getFileName(); + var jarTime = Files.readAttributes(jarFile, BasicFileAttributes.class).lastModifiedTime(); // Copy it to temp directory (hopefully free of exclamation mark) if needed (missing or older jar) - Path jarCopy = Paths.get(getSystemProperty("java.io.tmpdir")).resolve(filename); + final var jarCopy = Paths.get(getSystemProperty("java.io.tmpdir")).resolve(filename); if (!jarCopy.toFile().exists() || Files.readAttributes(jarCopy, BasicFileAttributes.class).lastModifiedTime().compareTo(jarTime) < 0) { Files.copy(jarFile, jarCopy, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); @@ -2028,7 +2025,7 @@ public static InputStream getResourceAsStream(ClassLoader cl, String path) { Logging.error("Cannot open {0}: {1}", path, e.getMessage()); Logging.trace(e); try { - URL betterUrl = betterJarUrl(cl.getResource(path)); + final var betterUrl = betterJarUrl(cl.getResource(path)); if (betterUrl != null) { return betterUrl.openStream(); } diff --git a/tools/eclipse/JOSM (Java 8).launch b/tools/eclipse/JOSM (Java 8).launch deleted file mode 100644 index aaa75dfae9b..00000000000 --- a/tools/eclipse/JOSM (Java 8).launch +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/tools/ivy.xml b/tools/ivy.xml index 955f0df492d..ad8e6cf12e9 100644 --- a/tools/ivy.xml +++ b/tools/ivy.xml @@ -16,10 +16,11 @@ - + + @@ -27,12 +28,10 @@ - - + + - - - +