Changeset 19048 in josm for trunk/src/org


Ignore:
Timestamp:
2024-04-19T16:21:11+02:00 (8 months ago)
Author:
taylor.smock
Message:

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.

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

Legend:

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

    r18628 r19048  
    77import java.awt.Dimension;
    88import java.awt.GraphicsEnvironment;
     9import java.awt.GridBagConstraints;
    910import java.awt.GridBagLayout;
    1011import java.awt.event.ActionEvent;
     
    1415import java.time.Year;
    1516import java.time.ZoneOffset;
    16 import java.util.Collection;
    1717import java.util.Collections;
    1818import java.util.List;
     
    2626import javax.swing.JScrollPane;
    2727
    28 import org.openstreetmap.josm.data.coor.LatLon;
    29 import org.openstreetmap.josm.data.imagery.DefaultLayer;
    3028import org.openstreetmap.josm.data.imagery.ImageryInfo;
    3129import org.openstreetmap.josm.data.imagery.ImageryInfo.ImageryType;
     
    6260        SelectWmsLayersDialog(WMSLayerTree tree, JComboBox<String> formats) {
    6361            super(MainApplication.getMainFrame(), tr("Select WMS layers"), tr("Add layers"), tr("Cancel"));
    64             final JScrollPane scrollPane = new JScrollPane(tree.getLayerTree());
     62            final var scrollPane = new JScrollPane(tree.getLayerTree());
    6563            scrollPane.setPreferredSize(new Dimension(400, 400));
    66             final JPanel panel = new JPanel(new GridBagLayout());
     64            final var panel = new JPanel(new GridBagLayout());
    6765            panel.add(scrollPane, GBC.eol().fill());
    68             panel.add(formats, GBC.eol().fill(GBC.HORIZONTAL));
     66            panel.add(formats, GBC.eol().fill(GridBagConstraints.HORIZONTAL));
    6967            setContent(panel);
    7068        }
     
    8482
    8583        // change toolbar icon from if specified
    86         String icon = info.getIcon();
     84        var icon = info.getIcon();
    8785        if (icon != null) {
    8886            new ImageProvider(icon).setOptional(true).getResourceAsync(result -> {
     
    103101        try {
    104102            if (info.getUrl() != null && info.getUrl().contains("{time}")) {
    105                 final String instant = Year.now(ZoneOffset.UTC).atDay(1).atStartOfDay(ZoneOffset.UTC).toInstant().toString();
    106                 final String example = String.join("/", instant, instant);
    107                 final String initialSelectionValue = info.getDate() != null ? info.getDate() : example;
    108                 final String userDate = JOptionPane.showInputDialog(MainApplication.getMainFrame(),
     103                final var instant = Year.now(ZoneOffset.UTC).atDay(1).atStartOfDay(ZoneOffset.UTC).toInstant().toString();
     104                final var example = String.join("/", instant, instant);
     105                final var initialSelectionValue = info.getDate() != null ? info.getDate() : example;
     106                final var userDate = JOptionPane.showInputDialog(MainApplication.getMainFrame(),
    109107                        tr("Time filter for \"{0}\" such as \"{1}\"", info.getName(), example),
    110108                        initialSelectionValue);
     
    115113                // TODO persist new {time} value (via ImageryLayerInfo.save?)
    116114            }
    117             switch(info.getImageryType()) {
     115            switch (info.getImageryType()) {
    118116            case WMS_ENDPOINT:
    119117                // convert to WMS type
     
    126124                // specify which layer to use
    127125                if (Utils.isEmpty(info.getDefaultLayers())) {
    128                     WMTSTileSource tileSource = new WMTSTileSource(info);
    129                     DefaultLayer layerId = tileSource.userSelectLayer();
     126                    var tileSource = new WMTSTileSource(info);
     127                    var layerId = tileSource.userSelectLayer();
    130128                    if (layerId != null) {
    131                         ImageryInfo copy = new ImageryInfo(info);
     129                        var copy = new ImageryInfo(info);
    132130                        copy.setDefaultLayers(Collections.singletonList(layerId));
    133                         String layerName = tileSource.getLayers().stream()
     131                        var layerName = tileSource.getLayers().stream()
    134132                                .filter(x -> x.getIdentifier().equals(layerId.getLayerName()))
    135133                                .map(Layer::getUserTitle)
     
    165163        ImageryLayer layer = null;
    166164        try {
    167             final ImageryInfo infoToAdd = convertImagery(info);
     165            final var infoToAdd = convertImagery(info);
    168166            if (infoToAdd != null) {
    169167                layer = ImageryLayer.create(infoToAdd);
     
    207205
    208206    private static LayerSelection askToSelectLayers(WMSImagery wms) {
    209         final WMSLayerTree tree = new WMSLayerTree();
    210 
    211         Collection<String> wmsFormats = wms.getFormats();
    212         final JComboBox<String> formats = new JComboBox<>(wmsFormats.toArray(new String[0]));
     207        final var tree = new WMSLayerTree();
     208
     209        var wmsFormats = wms.getFormats();
     210        final var formats = new JComboBox<String>(wmsFormats.toArray(new String[0]));
    213211        formats.setSelectedItem(wms.getPreferredFormat());
    214212        formats.setToolTipText(tr("Select image format for WMS layer"));
    215213
    216         JCheckBox checkBounds = new JCheckBox(tr("Show only layers for current view"), true);
     214        var checkBounds = new JCheckBox(tr("Show only layers for current view"), true);
    217215        Runnable updateTree = () -> {
    218             LatLon latLon = checkBounds.isSelected() && MainApplication.isDisplayingMapView()
     216            var latLon = checkBounds.isSelected() && MainApplication.isDisplayingMapView()
    219217                    ? MainApplication.getMap().mapView.getProjection().eastNorth2latlon(MainApplication.getMap().mapView.getCenter())
    220218                    : null;
     
    227225
    228226        if (!GraphicsEnvironment.isHeadless()) {
    229             ExtendedDialog dialog = new ExtendedDialog(MainApplication.getMainFrame(),
     227            var dialog = new ExtendedDialog(MainApplication.getMainFrame(),
    230228                    tr("Select WMS layers"), tr("Add layers"), tr("Cancel"));
    231             final JScrollPane scrollPane = new JScrollPane(tree.getLayerTree());
     229            final var scrollPane = new JScrollPane(tree.getLayerTree());
    232230            scrollPane.setPreferredSize(new Dimension(400, 400));
    233             final JPanel panel = new JPanel(new GridBagLayout());
     231            final var panel = new JPanel(new GridBagLayout());
    234232            panel.add(scrollPane, GBC.eol().fill());
    235             panel.add(checkBounds, GBC.eol().fill(GBC.HORIZONTAL));
    236             panel.add(formats, GBC.eol().fill(GBC.HORIZONTAL));
     233            panel.add(checkBounds, GBC.eol().fill(GridBagConstraints.HORIZONTAL));
     234            panel.add(formats, GBC.eol().fill(GridBagConstraints.HORIZONTAL));
    237235            dialog.setContent(panel);
    238236
     
    283281        CheckParameterUtil.ensureThat(ImageryType.WMS_ENDPOINT == info.getImageryType(), "wms_endpoint imagery type expected");
    284282        // We need to get the URL with {apikey} replaced. See #22642.
    285         final TemplatedWMSTileSource tileSource = new TemplatedWMSTileSource(info, ProjectionRegistry.getProjection());
    286         final WMSImagery wms = new WMSImagery(tileSource.getBaseUrl(), info.getCustomHttpHeaders());
    287         LayerSelection selection = choice.apply(wms);
     283        final var tileSource = new TemplatedWMSTileSource(info, ProjectionRegistry.getProjection());
     284        final var wms = new WMSImagery(tileSource.getBaseUrl(), info.getCustomHttpHeaders());
     285        var selection = choice.apply(wms);
    288286        if (selection == null) {
    289287            return null;
    290288        }
    291289
    292         final String url = wms.buildGetMapUrl(
     290        final var url = wms.buildGetMapUrl(
    293291                selection.layers.stream().map(LayerDetails::getName).collect(Collectors.toList()),
    294292                (List<String>) null,
     
    297295                );
    298296
    299         String selectedLayers = selection.layers.stream()
     297        var selectedLayers = selection.layers.stream()
    300298                .map(LayerDetails::getName)
    301299                .collect(Collectors.joining(", "));
    302300        // Use full copy of original Imagery info to copy all attributes. Only overwrite what's different
    303         ImageryInfo ret = new ImageryInfo(info);
     301        var ret = new ImageryInfo(info);
    304302        ret.setUrl(url);
    305303        ret.setImageryType(ImageryType.WMS);
  • trunk/src/org/openstreetmap/josm/actions/AutoScaleAction.java

    r18211 r19048  
    88import java.awt.event.ActionEvent;
    99import java.awt.event.KeyEvent;
    10 import java.awt.geom.Area;
    1110import java.util.ArrayList;
    1211import java.util.Collection;
     
    2322import org.openstreetmap.josm.data.DataSource;
    2423import org.openstreetmap.josm.data.conflict.Conflict;
    25 import org.openstreetmap.josm.data.osm.DataSet;
    2624import org.openstreetmap.josm.data.osm.IPrimitive;
    2725import org.openstreetmap.josm.data.osm.OsmData;
     
    3432import org.openstreetmap.josm.gui.MapView;
    3533import org.openstreetmap.josm.gui.NavigatableComponent.ZoomChangeListener;
    36 import org.openstreetmap.josm.gui.dialogs.ConflictDialog;
    3734import org.openstreetmap.josm.gui.dialogs.LayerListDialog;
    3835import org.openstreetmap.josm.gui.dialogs.ValidatorDialog.ValidatorBoundingXYVisitor;
     
    146143     */
    147144    public static void zoomTo(Collection<? extends IPrimitive> sel) {
    148         BoundingXYVisitor bboxCalculator = new BoundingXYVisitor();
     145        final var bboxCalculator = new BoundingXYVisitor();
    149146        bboxCalculator.computeBoundingBox(sel);
    150147        if (bboxCalculator.getBounds() != null) {
     
    244241    public void autoScale() {
    245242        if (MainApplication.isDisplayingMapView()) {
    246             MapView mapView = MainApplication.getMap().mapView;
     243            final var mapView = MainApplication.getMap().mapView;
    247244            switch (mode) {
    248245            case PREVIOUS:
     
    312309    private void modeLayer(BoundingXYVisitor v) {
    313310        // try to zoom to the first selected layer
    314         Layer l = getFirstSelectedLayer();
     311        final var l = getFirstSelectedLayer();
    315312        if (l == null)
    316313            return;
     
    327324            }
    328325        } else {
    329             ConflictDialog conflictDialog = MainApplication.getMap().conflictDialog;
     326            final var conflictDialog = MainApplication.getMap().conflictDialog;
    330327            Conflict<? extends IPrimitive> c = conflictDialog.getSelectedConflict();
    331328            if (c != null) {
     
    359356        }
    360357        Bounds bbox = null;
    361         final DataSet dataset = getLayerManager().getActiveDataSet();
     358        final var dataset = getLayerManager().getActiveDataSet();
    362359        if (dataset != null) {
    363360            List<DataSource> dataSources = new ArrayList<>(dataset.getDataSources());
     
    372369                } else {
    373370                    lastZoomArea = -1;
    374                     Area sourceArea = getLayerManager().getActiveDataSet().getDataSourceArea();
     371                    final var sourceArea = getLayerManager().getActiveDataSet().getDataSourceArea();
    375372                    if (sourceArea != null) {
    376373                        bbox = new Bounds(sourceArea.getBounds2D());
     
    439436     * Adapter for zoom change events
    440437     */
    441     private class ZoomChangeAdapter implements ZoomChangeListener {
     438    private final class ZoomChangeAdapter implements ZoomChangeListener {
    442439        @Override
    443440        public void zoomChanged() {
  • trunk/src/org/openstreetmap/josm/actions/ChangesetManagerToggleAction.java

    r17188 r19048  
    4949    }
    5050
    51     private class ChangesetCacheManagerClosedHandler extends WindowAdapter {
     51    private final class ChangesetCacheManagerClosedHandler extends WindowAdapter {
    5252        @Override
    5353        public void windowClosed(WindowEvent e) {
  • trunk/src/org/openstreetmap/josm/actions/DownloadOsmInViewAction.java

    r17052 r19048  
    3737    @Override
    3838    public void actionPerformed(ActionEvent e) {
    39         final Bounds bounds = MainApplication.getMap().mapView.getRealBounds();
    40         DownloadOsmInViewTask task = new DownloadOsmInViewTask();
     39        final var bounds = MainApplication.getMap().mapView.getRealBounds();
     40        final var task = new DownloadOsmInViewTask();
    4141        task.setZoomAfterDownload(false);
    4242        Future<?> future = task.download(bounds);
  • trunk/src/org/openstreetmap/josm/actions/JoinAreasAction.java

    r18972 r19048  
    210210
    211211        public List<Node> getNodes() {
    212             List<Node> nodes = new ArrayList<>();
     212            final var nodes = new ArrayList<Node>();
    213213            for (WayInPolygon way : this.ways) {
    214214                //do not add the last node as it will be repeated in the next way
    215215                if (way.insideToTheRight) {
    216                     for (int pos = 0; pos < way.way.getNodesCount() - 1; pos++) {
     216                    for (var pos = 0; pos < way.way.getNodesCount() - 1; pos++) {
    217217                        nodes.add(way.way.getNode(pos));
    218218                    }
     
    343343         */
    344344        private static double getAngle(Node n1, Node n2, Node n3) {
    345             EastNorth en1 = n1.getEastNorth();
    346             EastNorth en2 = n2.getEastNorth();
    347             EastNorth en3 = n3.getEastNorth();
     345            final var en1 = n1.getEastNorth();
     346            final var en2 = n2.getEastNorth();
     347            final var en3 = n3.getEastNorth();
    348348            double angle = Math.atan2(en3.getY() - en1.getY(), en3.getX() - en1.getX()) -
    349349                    Math.atan2(en2.getY() - en1.getY(), en2.getX() - en1.getX());
     
    362362         */
    363363        public WayInPolygon walk() {
    364             Node headNode = getHeadNode();
    365             Node prevNode = getPrevNode();
     364            final var headNode = getHeadNode();
     365            final var prevNode = getPrevNode();
    366366
    367367            double headAngle = Math.atan2(headNode.getEastNorth().east() - prevNode.getEastNorth().east(),
     
    371371            //find best next way
    372372            WayInPolygon bestWay = null;
    373             boolean bestWayReverse = false;
     373            var bestWayReverse = false;
    374374
    375375            for (WayInPolygon way : availableWays) {
     
    418418         */
    419419        public WayInPolygon leftComingWay() {
    420             Node headNode = getHeadNode();
    421             Node prevNode = getPrevNode();
     420            final var headNode = getHeadNode();
     421            final var prevNode = getPrevNode();
    422422
    423423            WayInPolygon mostLeft = null; // most left way connected to head node
    424             boolean comingToHead = false; // true if candidate come to head node
     424            var comingToHead = false; // true if candidate come to head node
    425425            double angle = 2*Math.PI;
    426426
     
    649649        }
    650650
    651         boolean hasChanges = false;
    652 
    653         List<Way> allStartingWays = new ArrayList<>();
    654         List<Way> innerStartingWays = new ArrayList<>();
    655         List<Way> outerStartingWays = new ArrayList<>();
     651        var hasChanges = false;
     652
     653        final var allStartingWays = new ArrayList<Way>();
     654        final var innerStartingWays = new ArrayList<Way>();
     655        final var outerStartingWays = new ArrayList<Way>();
    656656
    657657        for (Multipolygon area : areas) {
     
    721721        if (discardedWays.stream().anyMatch(w -> !w.isNew())) {
    722722            for (AssembledPolygon ring : boundaries) {
    723                 for (int k = 0; k < ring.ways.size(); k++) {
     723                for (var k = 0; k < ring.ways.size(); k++) {
    724724                    WayInPolygon ringWay = ring.ways.get(k);
    725725                    Way older = keepOlder(ringWay.way, oldestWayMap, discardedWays);
    726726
    727727                    if (ringWay.way != older) {
    728                         WayInPolygon repl = new WayInPolygon(older, ringWay.insideToTheRight);
     728                        final var repl = new WayInPolygon(older, ringWay.insideToTheRight);
    729729                        ring.ways.set(k, repl);
    730730                    }
     
    769769        // Delete the discarded inner ways
    770770        if (!discardedWays.isEmpty()) {
    771             Command deleteCmd = DeleteCommand.delete(discardedWays, true);
     771            final var deleteCmd = DeleteCommand.delete(discardedWays, true);
    772772            if (deleteCmd != null) {
    773773                cmds.add(deleteCmd);
     
    796796    private Way keepOlder(Way way, Map<Node, Way> oldestWayMap, List<Way> discardedWays) {
    797797        Way oldest = null;
    798         for (Node n : way.getNodes()) {
    799             Way orig = oldestWayMap .get(n);
     798        for (var n : way.getNodes()) {
     799            final var orig = oldestWayMap .get(n);
    800800            if (orig != null && (oldest == null || oldest.getUniqueId() > orig.getUniqueId())
    801801                    && discardedWays.contains(orig)) {
     
    830830        }
    831831
    832         TagCollection wayTags = TagCollection.unionOfAllPrimitives(ways);
     832        final var wayTags = TagCollection.unionOfAllPrimitives(ways);
    833833        try {
    834834            cmds.addAll(CombinePrimitiveResolverDialog.launchIfNecessary(wayTags, ways, ways));
     
    847847     */
    848848    private boolean removeDuplicateNodes(List<Way> ways) {
    849         Map<Node, Node> nodeMap = new TreeMap<>(new NodePositionComparator());
    850         int totalWaysModified = 0;
     849        final var nodeMap = new TreeMap<Node, Node>(new NodePositionComparator());
     850        var totalWaysModified = 0;
    851851
    852852        for (Way way : ways) {
     
    855855            }
    856856
    857             List<Node> newNodes = new ArrayList<>();
     857            final var newNodes = new ArrayList<Node>();
    858858            Node prevNode = null;
    859             boolean modifyWay = false;
     859            var modifyWay = false;
    860860
    861861            for (Node node : way.getNodes()) {
    862                 Node representator = nodeMap.get(node);
     862                var representator = nodeMap.get(node);
    863863                if (representator == null) {
    864864                    //new node
     
    898898     */
    899899    private void commitCommands(String description) {
    900         switch(cmds.size()) {
     900        switch (cmds.size()) {
    901901        case 0:
    902902            return;
     
    923923        cmds.clear();
    924924        if (addUndoRedo && !executedCmds.isEmpty()) {
    925             UndoRedoHandler ur = UndoRedoHandler.getInstance();
     925            final var ur = UndoRedoHandler.getInstance();
    926926            if (executedCmds.size() == 1) {
    927927                ur.add(executedCmds.getFirst(), false);
     
    945945        Map<Way, Way> nextWayMap = new HashMap<>();
    946946
    947         for (int pos = 0; pos < parts.size(); pos++) {
     947        for (var pos = 0; pos < parts.size(); pos++) {
    948948
    949949            if (!parts.get(pos).lastNode().equals(parts.get((pos + 1) % parts.size()).firstNode()))
     
    956956        Way topWay = null;
    957957        Node topNode = null;
    958         int topIndex = 0;
     958        var topIndex = 0;
    959959        double minY = Double.POSITIVE_INFINITY;
    960960
    961961        for (Way way : parts) {
    962             for (int pos = 0; pos < way.getNodesCount(); pos++) {
    963                 Node node = way.getNode(pos);
     962            for (var pos = 0; pos < way.getNodesCount(); pos++) {
     963                final var node = way.getNode(pos);
    964964
    965965                if (node.getEastNorth().getY() < minY) {
     
    996996            for (Way way : parts) {
    997997                if (way.firstNode().equals(headNode)) {
    998                     Node nextNode = way.getNode(1);
     998                    final var nextNode = way.getNode(1);
    999999
    10001000                    if (topWay == null || !Geometry.isToTheRightSideOfLine(prevNode, headNode, bestWayNextNode, nextNode)) {
     
    10081008                if (way.lastNode().equals(headNode)) {
    10091009                    //end adjacent to headNode
    1010                     Node nextNode = way.getNode(way.getNodesCount() - 2);
     1010                    final var nextNode = way.getNode(way.getNodesCount() - 2);
    10111011
    10121012                    if (topWay == null || !Geometry.isToTheRightSideOfLine(prevNode, headNode, bestWayNextNode, nextNode)) {
     
    10201020        } else {
    10211021            //node is inside way - pick the clockwise going end.
    1022             Node prev = topWay.getNode(topIndex - 1);
    1023             Node next = topWay.getNode(topIndex + 1);
     1022            final var prev = topWay.getNode(topIndex - 1);
     1023            final var next = topWay.getNode(topIndex + 1);
    10241024
    10251025            //there will be no parallel segments in the middle of way, so all fine.
     
    10271027        }
    10281028
    1029         Way curWay = topWay;
     1029        var curWay = topWay;
    10301030        boolean curWayInsideToTheRight = wayClockwise ^ isInner;
    10311031        List<WayInPolygon> result = new ArrayList<>();
     
    10351035
    10361036            //add cur way
    1037             WayInPolygon resultWay = new WayInPolygon(curWay, curWayInsideToTheRight);
     1037            final var resultWay = new WayInPolygon(curWay, curWayInsideToTheRight);
    10381038            result.add(resultWay);
    10391039
    10401040            //process next way
    1041             Way nextWay = nextWayMap.get(curWay);
    1042             Node prevNode = curWay.getNode(curWay.getNodesCount() - 2);
    1043             Node headNode = curWay.lastNode();
    1044             Node nextNode = nextWay.getNode(1);
     1041            final var nextWay = nextWayMap.get(curWay);
     1042            final var prevNode = curWay.getNode(curWay.getNodesCount() - 2);
     1043            final var headNode = curWay.lastNode();
     1044            final var nextNode = nextWay.getNode(1);
    10451045
    10461046            if (nextWay == topWay) {
     
    10681068            //                       |
    10691069
    1070             int intersectionCount = 0;
     1070            var intersectionCount = 0;
    10711071
    10721072            for (Way wayA : parts) {
     
    10781078                if (wayA.lastNode().equals(headNode)) {
    10791079
    1080                     Way wayB = nextWayMap.get(wayA);
     1080                    final var wayB = nextWayMap.get(wayA);
    10811081
    10821082                    //test if wayA is opposite wayB relative to curWay and nextWay
    10831083
    1084                     Node wayANode = wayA.getNode(wayA.getNodesCount() - 2);
    1085                     Node wayBNode = wayB.getNode(1);
     1084                    final var wayANode = wayA.getNode(wayA.getNodesCount() - 2);
     1085                    final var wayBNode = wayB.getNode(1);
    10861086
    10871087                    boolean wayAToTheRight = Geometry.isToTheRightSideOfLine(prevNode, headNode, nextNode, wayANode);
     
    11171117     */
    11181118    private static void revertDuplicateTwoNodeWays(List<WayInPolygon> parts) {
    1119         for (int i = 0; i < parts.size(); i++) {
     1119        for (var i = 0; i < parts.size(); i++) {
    11201120            WayInPolygon w1 = parts.get(i);
    11211121            if (w1.way.getNodesCount() != 2)
     
    11411141    private List<Way> splitWayOnNodes(Way way, Set<Node> nodes, Map<Node, Way> oldestWayMap) {
    11421142
    1143         List<Way> result = new ArrayList<>();
     1143        final var result = new ArrayList<Way>();
    11441144        List<List<Node>> chunks = buildNodeChunks(way, nodes);
    11451145
    11461146        if (chunks.size() > 1) {
    1147             SplitWayCommand split = SplitWayCommand.splitWay(way, chunks,
     1147            final var split = SplitWayCommand.splitWay(way, chunks,
    11481148                    Collections.emptyList(), SplitWayCommand.Strategy.keepFirstChunk());
    11491149
     
    11591159                if (!way.isNew() && result.size() > 1) {
    11601160                    for (Way part : result) {
    1161                         Node n = part.firstNode();
    1162                         Way old = oldestWayMap.get(n);
     1161                        final var n = part.firstNode();
     1162                        final var old = oldestWayMap.get(n);
    11631163                        if (old == null || old.getUniqueId() > way.getUniqueId()) {
    11641164                            oldestWayMap.put(n, way);
     
    12311231
    12321232        //TODO: bad performance for deep nestings...
    1233         List<PolygonLevel> result = new ArrayList<>();
     1233        final var result = new ArrayList<PolygonLevel>();
    12341234
    12351235        for (AssembledPolygon outerWay : boundaryWays) {
    12361236
    1237             boolean outerGood = true;
    1238             List<AssembledPolygon> innerCandidates = new ArrayList<>();
     1237            var outerGood = true;
     1238            final var innerCandidates = new ArrayList<AssembledPolygon>();
    12391239
    12401240            for (AssembledPolygon innerWay : boundaryWays) {
     
    12561256
    12571257            //add new outer polygon
    1258             AssembledMultipolygon pol = new AssembledMultipolygon(outerWay);
    1259             PolygonLevel polLev = new PolygonLevel(pol, level);
     1258            final var pol = new AssembledMultipolygon(outerWay);
     1259            final var polLev = new PolygonLevel(pol, level);
    12601260
    12611261            //process inner ways
     
    12881288        // This seems to appear when is apply over invalid way like #9911 test-case
    12891289        // Remove all of these way to make the next work.
    1290         List<WayInPolygon> cleanMultigonWays = new ArrayList<>();
     1290        final var cleanMultigonWays = new ArrayList<WayInPolygon>();
    12911291        for (WayInPolygon way: multigonWays) {
    12921292            if (way.way.getNodesCount() != 2 || !way.way.isClosed())
    12931293                cleanMultigonWays.add(way);
    12941294        }
    1295         WayTraverser traverser = new WayTraverser(cleanMultigonWays);
    1296         List<AssembledPolygon> result = new ArrayList<>();
     1295        final var traverser = new WayTraverser(cleanMultigonWays);
     1296        final var result = new ArrayList<AssembledPolygon>();
    12971297
    12981298        WayInPolygon startWay;
    12991299        while ((startWay = traverser.startNewWay()) != null) {
    1300             List<WayInPolygon> path = new ArrayList<>();
    1301             List<WayInPolygon> startWays = new ArrayList<>();
     1300            final var path = new ArrayList<WayInPolygon>();
     1301            final var startWays = new ArrayList<WayInPolygon>();
    13021302            path.add(startWay);
    13031303            while (true) {
     
    13181318                if (path.get(0) == nextWay) {
    13191319                    // path is closed -> stop here
    1320                     AssembledPolygon ring = new AssembledPolygon(path);
     1320                    final var ring = new AssembledPolygon(path);
    13211321                    if (ring.getNodes().size() <= 2) {
    13221322                        // Invalid ring (2 nodes) -> remove
     
    13571357     */
    13581358    public static List<AssembledPolygon> fixTouchingPolygons(List<AssembledPolygon> polygons) {
    1359         List<AssembledPolygon> newPolygons = new ArrayList<>();
     1359        final var newPolygons = new ArrayList<AssembledPolygon>();
    13601360
    13611361        for (AssembledPolygon ring : polygons) {
    13621362            ring.reverse();
    1363             WayTraverser traverser = new WayTraverser(ring.ways);
     1363            final var traverser = new WayTraverser(ring.ways);
    13641364            WayInPolygon startWay;
    13651365
    13661366            while ((startWay = traverser.startNewWay()) != null) {
    1367                 List<WayInPolygon> simpleRingWays = new ArrayList<>();
     1367                final var simpleRingWays = new ArrayList<WayInPolygon>();
    13681368                simpleRingWays.add(startWay);
    13691369                WayInPolygon nextWay;
     
    13741374                }
    13751375                traverser.removeWays(simpleRingWays);
    1376                 AssembledPolygon simpleRing = new AssembledPolygon(simpleRingWays);
     1376                final var simpleRing = new AssembledPolygon(simpleRingWays);
    13771377                simpleRing.reverse();
    13781378                newPolygons.add(simpleRing);
     
    14111411     */
    14121412    private Multipolygon joinPolygon(AssembledMultipolygon polygon) throws UserCancelException {
    1413         Multipolygon result = new Multipolygon(joinWays(polygon.outerWay.ways));
     1413        final var result = new Multipolygon(joinWays(polygon.outerWay.ways));
    14141414
    14151415        for (AssembledPolygon pol : polygon.innerWays) {
     
    14291429
    14301430        //leave original orientation, if all paths are reverse.
    1431         boolean allReverse = true;
     1431        var allReverse = true;
    14321432        for (WayInPolygon way : ways) {
    14331433            allReverse &= !way.insideToTheRight;
     
    14401440        }
    14411441
    1442         Way joinedWay = joinOrientedWays(ways);
     1442        final var joinedWay = joinOrientedWays(ways);
    14431443
    14441444        //should not happen
     
    14621462        // the user about this.
    14631463
    1464         List<Way> actionWays = new ArrayList<>(ways.size());
    1465         int oldestPos = 0;
     1464        final var actionWays = new ArrayList<Way>(ways.size());
     1465        var oldestPos = 0;
    14661466        Way oldest = ways.get(0).way;
    14671467        for (WayInPolygon way : ways) {
     
    15111511            }
    15121512
    1513             boolean hasKnownOuter = false;
     1513            var hasKnownOuter = false;
    15141514            outerWays.clear();
    15151515            innerWays.clear();
     
    15381538            }
    15391539
    1540             Way outerWay = outerWays.get(0);
     1540            final var outerWay = outerWays.get(0);
    15411541
    15421542            //retain only selected inner ways
     
    15881588            processedInnerWays.addAll(innerWays);
    15891589
    1590             Multipolygon pol = new Multipolygon(outerWay);
     1590            final var pol = new Multipolygon(outerWay);
    15911591            pol.innerWays.addAll(innerWays);
    15921592
     
    16151615        OsmDataLayer layer = getLayerManager().getEditLayer();
    16161616        // Create new multipolygon relation and add all inner ways to it
    1617         Relation newRel = new Relation();
     1617        final var newRel = new Relation();
    16181618        newRel.put("type", "multipolygon");
    16191619        for (Way w : inner) {
     
    16501650
    16511651                cmds.add(new ChangeMembersCommand(r, members));
    1652                 RelationRole saverel = new RelationRole(r, rm.getRole());
     1652                final var saverel = new RelationRole(r, rm.getRole());
    16531653                if (!result.contains(saverel)) {
    16541654                    result.add(saverel);
     
    17011701        default:
    17021702            // Create a new relation with all previous members and (Way)outer as outer.
    1703             Relation newRel = new Relation();
     1703            final var newRel = new Relation();
    17041704            for (RelationRole r : multiouters) {
    17051705                // Add members
  • trunk/src/org/openstreetmap/josm/actions/SplitWayAction.java

    r18759 r19048  
    77
    88import java.awt.Component;
     9import java.awt.GridBagConstraints;
    910import java.awt.GridBagLayout;
    1011import java.awt.event.ActionEvent;
     
    146147
    147148        // Finally, applicableWays contains only one perfect way
    148         final Way selectedWay = applicableWays.get(0);
    149         final List<OsmPrimitive> sel = new ArrayList<>(ds.getSelectedRelations());
     149        final var selectedWay = applicableWays.get(0);
     150        final var sel = new ArrayList<OsmPrimitive>(ds.getSelectedRelations());
    150151        sel.addAll(selectedWays);
    151152        doSplitWayShowSegmentSelection(selectedWay, selectedNodes, sel);
     
    164165        if (wayChunks != null) {
    165166            final List<Way> newWays = SplitWayCommand.createNewWaysFromChunks(splitWay, wayChunks);
    166             final Way wayToKeep = SplitWayCommand.Strategy.keepLongestChunk().determineWayToKeep(newWays);
     167            final var wayToKeep = SplitWayCommand.Strategy.keepLongestChunk().determineWayToKeep(newWays);
    167168
    168169            if (ExpertToggleAction.isExpert() && !splitWay.isNew()) {
     
    210211
    211212            setButtonIcons("ok", "cancel");
    212             final JPanel pane = new JPanel(new GridBagLayout());
    213             pane.add(new JLabel(getTitle()), GBC.eol().fill(GBC.HORIZONTAL));
    214             pane.add(list, GBC.eop().fill(GBC.HORIZONTAL));
     213            final var pane = new JPanel(new GridBagLayout());
     214            pane.add(new JLabel(getTitle()), GBC.eol().fill(GridBagConstraints.HORIZONTAL));
     215            pane.add(list, GBC.eop().fill(GridBagConstraints.HORIZONTAL));
    215216            setContent(pane);
    216217            setDefaultCloseOperation(HIDE_ON_CLOSE);
     
    224225                    final Collection<WaySegment> segments = new ArrayList<>(selected.getNodesCount() - 1);
    225226                    final Iterator<Node> it = selected.getNodes().iterator();
    226                     Node previousNode = it.next();
     227                    var previousNode = it.next();
    227228                    while (it.hasNext()) {
    228                         final Node node = it.next();
     229                        final var node = it.next();
    229230                        segments.add(WaySegment.forNodePair(selectedWay, previousNode, node));
    230231                        previousNode = node;
     
    237238
    238239        protected void setHighlightedWaySegments(Collection<WaySegment> segments) {
    239             DataSet ds = selectedWay.getDataSet();
     240            final var ds = selectedWay.getDataSet();
    240241            if (ds != null) {
    241242                ds.setHighlightedWaySegments(segments);
     
    247248        public void setVisible(boolean visible) {
    248249            super.setVisible(visible);
    249             DataSet ds = selectedWay.getDataSet();
     250            final var ds = selectedWay.getDataSet();
    250251            if (visible) {
    251252                DISPLAY_COUNT.incrementAndGet();
     
    276277        }
    277278
    278         private class SplitWayDataSetListener implements DataSetListener {
     279        private final class SplitWayDataSetListener implements DataSetListener {
    279280
    280281            @Override
     
    336337        @Override
    337338        public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
    338             final Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
     339            final var c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
    339340            final String name = DefaultNameFormatter.getInstance().format((Way) value);
    340341            // get rid of id from DefaultNameFormatter.decorateNameWithId()
     
    359360        // Special case - one of the selected ways touches (not cross) way that we want to split
    360361        if (selectedNodes.size() == 1) {
    361             Node n = selectedNodes.get(0);
     362            final var n = selectedNodes.get(0);
    362363            List<Way> referredWays = n.getParentWays();
    363364            Way inTheMiddle = null;
  • trunk/src/org/openstreetmap/josm/data/osm/search/SearchCompiler.java

    r18877 r19048  
    2323import java.util.function.Predicate;
    2424import java.util.function.Supplier;
    25 import java.util.regex.Matcher;
    2625import java.util.regex.Pattern;
    2726import java.util.regex.PatternSyntaxException;
     
    160159        @Override
    161160        public Match get(String keyword, boolean caseSensitive, boolean regexSearch, PushbackTokenizer tokenizer) throws SearchParseError {
    162             switch(keyword) {
     161            switch (keyword) {
    163162            case MODIFIED:
    164163                return new Modified();
     
    11401139                    value = Normalizer.normalize(value, Normalizer.Form.NFC);
    11411140
    1142                     Matcher keyMatcher = searchRegex.matcher(key);
    1143                     Matcher valMatcher = searchRegex.matcher(value);
     1141                    final var keyMatcher = searchRegex.matcher(key);
     1142                    final var valMatcher = searchRegex.matcher(value);
    11441143
    11451144                    boolean keyMatchFound = keyMatcher.find();
     
    16231622     * Matches objects that are new (i.e. have not been uploaded to the server)
    16241623     */
    1625     private static class New extends Match {
     1624    private static final class New extends Match {
    16261625        @Override
    16271626        public boolean match(OsmPrimitive osm) {
     
    16381637     * Matches all objects that have been modified, created, or undeleted
    16391638     */
    1640     private static class Modified extends Match {
     1639    private static final class Modified extends Match {
    16411640        @Override
    16421641        public boolean match(OsmPrimitive osm) {
     
    16531652     * Matches all objects that have been deleted
    16541653     */
    1655     private static class Deleted extends Match {
     1654    private static final class Deleted extends Match {
    16561655        @Override
    16571656        public boolean match(OsmPrimitive osm) {
     
    16681667     * Matches all objects currently selected
    16691668     */
    1670     private static class Selected extends Match {
     1669    private static final class Selected extends Match {
    16711670        @Override
    16721671        public boolean match(OsmPrimitive osm) {
     
    16851684     * fetched from the server.
    16861685     */
    1687     private static class Incomplete extends Match {
     1686    private static final class Incomplete extends Match {
    16881687        @Override
    16891688        public boolean match(OsmPrimitive osm) {
     
    17021701     * org.openstreetmap.josm.data.osm.OsmPrimitive.getUninterestingKeys()
    17031702     */
    1704     private static class Untagged extends Match {
     1703    private static final class Untagged extends Match {
    17051704        @Override
    17061705        public boolean match(OsmPrimitive osm) {
     
    17171716     * Matches ways which are closed (i.e. first and last node are the same)
    17181717     */
    1719     private static class Closed extends Match {
     1718    private static final class Closed extends Match {
    17201719        @Override
    17211720        public boolean match(OsmPrimitive osm) {
     
    18181817            if (!(osm instanceof Way))
    18191818                return null;
    1820             Way way = (Way) osm;
     1819            final var way = (Way) osm;
    18211820            return (long) way.getLength();
    18221821        }
     
    19711970
    19721971            try {
    1973                 String groupSuffix = name.substring(0, name.length() - 2); // try to remove '/*'
     1972                final var groupSuffix = name.substring(0, name.length() - 2); // try to remove '/*'
    19741973                TaggingPresetMenu group = preset.group;
    19751974
     
    21792178            } else if (tokenizer.readIfEqual(Token.COLON)) {
    21802179                // see if we have a Match that takes a data parameter
    2181                 SimpleMatchFactory factory = simpleMatchFactoryMap.get(key);
     2180                final var factory = simpleMatchFactoryMap.get(key);
    21822181                if (factory != null)
    21832182                    return factory.get(key, caseSensitive, regexSearch, tokenizer);
    21842183
    2185                 UnaryMatchFactory unaryFactory = unaryMatchFactoryMap.get(key);
     2184                final var unaryFactory = unaryMatchFactoryMap.get(key);
    21862185                if (unaryFactory != null)
    21872186                    return getValidate(unaryFactory, key, tokenizer);
     
    21962195                return new BooleanMatch(key, false);
    21972196            else {
    2198                 SimpleMatchFactory factory = simpleMatchFactoryMap.get(key);
     2197                final var factory = simpleMatchFactoryMap.get(key);
    21992198                if (factory != null)
    22002199                    return factory.get(key, caseSensitive, regexSearch, null).validate();
    22012200
    2202                 UnaryMatchFactory unaryFactory = unaryMatchFactoryMap.get(key);
     2201                final var unaryFactory = unaryMatchFactoryMap.get(key);
    22032202                if (unaryFactory != null)
    22042203                    return getValidate(unaryFactory, key, null);
     
    22222221
    22232222    private static int regexFlags(boolean caseSensitive) {
    2224         int searchFlags = 0;
     2223        var searchFlags = 0;
    22252224
    22262225        // Enables canonical Unicode equivalence so that e.g. the two
  • trunk/src/org/openstreetmap/josm/data/validation/ValidatorCLI.java

    r18950 r19048  
    1111import java.nio.charset.StandardCharsets;
    1212import java.nio.file.Files;
    13 import java.nio.file.Path;
    1413import java.nio.file.Paths;
    1514import java.util.ArrayList;
     
    2726import java.util.stream.Collectors;
    2827
    29 import org.apache.commons.compress.utils.FileNameUtils;
     28import org.apache.commons.io.FilenameUtils;
    3029import org.openstreetmap.josm.actions.ExtensionFileFilter;
    3130import org.openstreetmap.josm.cli.CLIModule;
    3231import org.openstreetmap.josm.data.Preferences;
    33 import org.openstreetmap.josm.data.osm.DataSet;
    3432import org.openstreetmap.josm.data.preferences.JosmBaseDirectories;
    3533import org.openstreetmap.josm.data.preferences.JosmUrls;
     
    176174            }
    177175            this.initialize();
    178             final ProgressMonitor fileMonitor = progressMonitorFactory.get();
     176            final var fileMonitor = progressMonitorFactory.get();
    179177            fileMonitor.beginTask(tr("Processing files..."), this.input.size());
    180178            for (String inputFile : this.input) {
     
    202200     */
    203201    private static void processMapcssFile(final String inputFile) throws ParseException {
    204         final MapCSSStyleSource styleSource = new MapCSSStyleSource(new File(inputFile).toURI().getPath(), inputFile, inputFile);
     202        final var styleSource = new MapCSSStyleSource(new File(inputFile).toURI().getPath(), inputFile, inputFile);
    205203        styleSource.loadStyleSource();
    206204        if (!styleSource.getErrors().isEmpty()) {
     
    221219        // Check asserts
    222220        Config.getPref().putBoolean("validator.check_assert_local_rules", true);
    223         final MapCSSTagChecker mapCSSTagChecker = new MapCSSTagChecker();
    224         final Collection<String> assertionErrors = new ArrayList<>();
     221        final var mapCSSTagChecker = new MapCSSTagChecker();
     222        final var assertionErrors = new ArrayList<String>();
    225223        final MapCSSTagChecker.ParseResult result = mapCSSTagChecker.addMapCSS(new File(inputFile).toURI().getPath(),
    226224                assertionErrors::add);
     
    247245     */
    248246    private void processFile(final String inputFile) throws IllegalDataException, IOException {
    249         final File inputFileFile = new File(inputFile);
     247        final var inputFileFile = new File(inputFile);
    250248        final List<FileImporter> inputFileImporters = ExtensionFileFilter.getImporters().stream()
    251249                .filter(importer -> importer.acceptFile(inputFileFile)).collect(Collectors.toList());
    252         final Stopwatch stopwatch = Stopwatch.createStarted();
     250        final var stopwatch = Stopwatch.createStarted();
    253251        if (inputFileImporters.stream().noneMatch(fileImporter ->
    254252                fileImporter.importDataHandleExceptions(inputFileFile, progressMonitorFactory.get()))) {
     
    263261                    .stream().filter(layer -> inputFileFile.equals(layer.getAssociatedFile()))
    264262                    .findFirst().orElseThrow(() -> new JosmRuntimeException(tr("Could not find a layer for {0}", inputFile)));
    265             final DataSet dataSet = dataLayer.getDataSet();
     263            final var dataSet = dataLayer.getDataSet();
    266264            if (this.changeFiles.containsKey(inputFile)) {
    267                 ProgressMonitor changeFilesMonitor = progressMonitorFactory.get();
     265                final var changeFilesMonitor = progressMonitorFactory.get();
    268266                for (String changeFile : this.changeFiles.getOrDefault(inputFile, Collections.emptyList())) {
    269                     try (InputStream changeStream = Compression.getUncompressedFileInputStream(Paths.get(changeFile))) {
     267                    try (var changeStream = Compression.getUncompressedFileInputStream(Paths.get(changeFile))) {
    270268                        dataSet.mergeFrom(OsmChangeReader.parseDataSet(changeStream, changeFilesMonitor));
    271269                    }
    272270                }
    273271            }
    274             Path path = Paths.get(outputFile);
     272            final var path = Paths.get(outputFile);
    275273            if (path.toFile().isFile() && !Files.deleteIfExists(path)) {
    276274                Logging.error("Could not delete {0}, attempting to append", outputFile);
    277275            }
    278             GeoJSONMapRouletteWriter geoJSONMapRouletteWriter = new GeoJSONMapRouletteWriter(dataSet);
     276            final var geoJSONMapRouletteWriter = new GeoJSONMapRouletteWriter(dataSet);
    279277            OsmValidator.initializeTests();
    280278
    281             try (OutputStream fileOutputStream = Files.newOutputStream(path)) {
     279            try (var fileOutputStream = Files.newOutputStream(path)) {
    282280                // The first writeErrors catches anything that was written, for whatever reason. This is probably never
    283281                // going to be called.
    284                 ValidationTask validationTask = new ValidationTask(errors -> writeErrors(geoJSONMapRouletteWriter, fileOutputStream, errors),
     282                final var validationTask = new ValidationTask(errors -> writeErrors(geoJSONMapRouletteWriter, fileOutputStream, errors),
    285283                        progressMonitorFactory.get(), OsmValidator.getEnabledTests(false),
    286284                        dataSet.allPrimitives(), Collections.emptyList(), false);
     
    320318     */
    321319    private static String getDefaultOutputName(final String inputString) {
    322         final String extension = FileNameUtils.getExtension(inputString);
     320        final String extension = FilenameUtils.getExtension(inputString);
    323321        if (!Arrays.asList("zip", "bz", "xz", "geojson").contains(extension)) {
    324             return FileNameUtils.getBaseName(inputString) + ".geojson";
     322            return FilenameUtils.getBaseName(inputString) + ".geojson";
    325323        } else if ("geojson".equals(extension)) {
    326324            // Account for geojson input files
    327             return FileNameUtils.getBaseName(inputString) + ".validated.geojson";
    328         }
    329         return FileNameUtils.getBaseName(FileNameUtils.getBaseName(inputString)) + ".geojson";
     325            return FilenameUtils.getBaseName(inputString) + ".validated.geojson";
     326        }
     327        return FilenameUtils.getBaseName(FilenameUtils.getBaseName(inputString)) + ".geojson";
    330328    }
    331329
     
    348346    /**
    349347     * Initialize everything that might be needed
    350      *
     348     * <p>
    351349     * Arguments may need to be parsed first.
    352350     */
     
    369367        Logging.setLogLevel(Level.INFO);
    370368
    371         OptionParser parser = new OptionParser("JOSM validate");
    372         final AtomicReference<String> currentInput = new AtomicReference<>(null);
     369        final var parser = new OptionParser("JOSM validate");
     370        final var currentInput = new AtomicReference<String>(null);
    373371        for (Option o : Option.values()) {
    374372            if (o.requiresArgument()) {
     
    425423            break;
    426424        case LOAD_PREFERENCES:
    427             final Preferences tempPreferences = new Preferences();
     425            final var tempPreferences = new Preferences();
    428426            tempPreferences.enableSaveOnPut(false);
    429             CustomConfigurator.XMLCommandProcessor config = new CustomConfigurator.XMLCommandProcessor(tempPreferences);
     427            final var config = new CustomConfigurator.XMLCommandProcessor(tempPreferences);
    430428            try (InputStream is = Utils.openStream(new File(argument).toURI().toURL())) {
    431429                config.openAndReadXML(is);
     
    435433            final IPreferences pref = Config.getPref();
    436434            if (pref instanceof MemoryPreferences) {
    437                 final MemoryPreferences memoryPreferences = (MemoryPreferences) pref;
     435                final var memoryPreferences = (MemoryPreferences) pref;
    438436                tempPreferences.getAllSettings().forEach(memoryPreferences::putSetting);
    439437            } else {
     
    454452
    455453    private static String getHelp() {
    456         final String helpPadding = "\t                          ";
     454        final var helpPadding = "\t                          ";
    457455        // CHECKSTYLE.OFF: SingleSpaceSeparator
    458456        return tr("JOSM Validation command line interface") + "\n\n" +
  • trunk/src/org/openstreetmap/josm/gui/dialogs/relation/sort/RelationSorter.java

    r17867 r19048  
    4848     * {@code type=associatedStreet} and {@code type=street} relations.
    4949     */
    50     private static class AssociatedStreetRoleStreetSorter implements AdditionalSorter {
     50    private static final class AssociatedStreetRoleStreetSorter implements AdditionalSorter {
    5151
    5252        @Override
     
    6565     * {@code type=associatedStreet} and {@code type=street} relations.
    6666     */
    67     private static class AssociatedStreetRoleAddressHouseSorter implements AdditionalSorter {
     67    private static final class AssociatedStreetRoleAddressHouseSorter implements AdditionalSorter {
    6868
    6969        @Override
     
    9393     * {@code type=public_transport} relations.
    9494     */
    95     private static class PublicTransportRoleStopPlatformSorter implements AdditionalSorter {
     95    private static final class PublicTransportRoleStopPlatformSorter implements AdditionalSorter {
    9696
    9797        @Override
     
    140140     * {@code type=restriction} relations.
    141141     */
    142     private static class FromViaToSorter implements AdditionalSorter {
     142    private static final class FromViaToSorter implements AdditionalSorter {
    143143
    144144        private static final List<String> ROLES = Arrays.asList("from", "via", "to");
     
    173173        // Dispatch members to the first adequate sorter
    174174        for (RelationMember m : relationMembers) {
    175             boolean wasAdded = false;
     175            var wasAdded = false;
    176176            for (AdditionalSorter sorter : ADDITIONAL_SORTERS) {
    177177                if (sorter.acceptsMember(relationMembers, m)) {
  • trunk/src/org/openstreetmap/josm/gui/io/UploadPrimitivesTask.java

    r18283 r19048  
    141141                ht("/Action/Upload#ChangesetFull")
    142142        );
    143         switch(ret) {
     143        switch (ret) {
    144144        case 0: return MaxChangesetSizeExceededPolicy.AUTOMATICALLY_OPEN_NEW_CHANGESETS;
    145145        case 1: return MaxChangesetSizeExceededPolicy.FILL_ONE_CHANGESET_AND_RETURN_TO_UPLOAD_DIALOG;
     
    168168            strategy.setPolicy(promptUserForPolicy());
    169169        }
    170         switch(strategy.getPolicy()) {
     170        switch (strategy.getPolicy()) {
    171171        case AUTOMATICALLY_OPEN_NEW_CHANGESETS:
    172             Changeset newChangeSet = new Changeset();
     172            final var newChangeSet = new Changeset();
    173173            newChangeSet.setKeys(changeset.getKeys());
    174174            closeChangeset();
     
    280280                        processedPrimitives.addAll(writer.getProcessedPrimitives()); // OsmPrimitive in => OsmPrimitive out
    281281                    }
    282                     switch(e.getSource()) {
     282                    switch (e.getSource()) {
    283283                    case UPLOAD_DATA:
    284284                        // Most likely the changeset is full. Try to recover and continue
     
    319319            }
    320320        } finally {
    321             if (MessageNotifier.PROP_NOTIFIER_ENABLED.get()) {
     321            if (Boolean.TRUE.equals(MessageNotifier.PROP_NOTIFIER_ENABLED.get())) {
    322322                MessageNotifier.start();
    323323            }
     
    372372            if (uploadCanceled) return;
    373373            if (lastException == null) {
    374                 HtmlPanel panel = new HtmlPanel(
     374                final var panel = new HtmlPanel(
    375375                        "<h3><a href=\"" + Config.getUrls().getBaseBrowseUrl() + "/changeset/" + changeset.getId() + "\">"
    376376                                + tr("Upload successful!") + "</a></h3>");
     
    393393                    return;
    394394                if (e.getSource() == ChangesetClosedException.Source.UPLOAD_DATA) {
    395                     switch(strategy.getPolicy()) {
     395                    switch (strategy.getPolicy()) {
    396396                    case ABORT:
    397397                        break; /* do nothing - we return to map editing */
  • trunk/src/org/openstreetmap/josm/gui/layer/geoimage/CorrelateGpxWithImages.java

    r18221 r19048  
    6767import org.openstreetmap.josm.gui.layer.LayerManager.LayerRemoveEvent;
    6868import org.openstreetmap.josm.gui.layer.geoimage.AdjustTimezoneAndOffsetDialog.AdjustListener;
    69 import org.openstreetmap.josm.gui.layer.geoimage.SynchronizeTimeFromPhotoDialog.TimeZoneItem;
    7069import org.openstreetmap.josm.gui.layer.gpx.GpxDataHelper;
    7170import org.openstreetmap.josm.gui.widgets.JosmComboBox;
     
    173172                // Search whether an other layer has yet defined some bounding box.
    174173                // If none, we'll zoom to the bounding box of the layer with the photos.
    175                 boolean boundingBoxedLayerFound = false;
     174                var boundingBoxedLayerFound = false;
    176175                for (Layer l: MainApplication.getLayerManager().getLayers()) {
    177176                    if (l != yLayer) {
    178                         BoundingXYVisitor bbox = new BoundingXYVisitor();
     177                        final var bbox = new BoundingXYVisitor();
    179178                        l.visitBoundingBox(bbox);
    180179                        if (bbox.getBounds() != null) {
     
    185184                }
    186185                if (!boundingBoxedLayerFound) {
    187                     BoundingXYVisitor bbox = new BoundingXYVisitor();
     186                    final var bbox = new BoundingXYVisitor();
    188187                    yLayer.visitBoundingBox(bbox);
    189188                    MainApplication.getMap().mapView.zoomTo(bbox);
     
    261260     * been loaded yet. It displays a FileChooser dialog to select the GPX file to be loaded.
    262261     */
    263     private class LoadGpxDataActionListener implements ActionListener {
     262    private final class LoadGpxDataActionListener implements ActionListener {
    264263
    265264        @Override
    266265        public void actionPerformed(ActionEvent e) {
    267             File sel = GpxDataHelper.chooseGpxDataFile();
     266            final var sel = GpxDataHelper.chooseGpxDataFile();
    268267            if (sel != null) {
    269268                try {
    270269                    outerPanel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    271270                    removeDuplicates(sel);
    272                     GpxData data = GpxDataHelper.loadGpxData(sel);
     271                    final var data = GpxDataHelper.loadGpxData(sel);
    273272                    if (data != null) {
    274                         GpxDataWrapper elem = new GpxDataWrapper(sel.getName(), data, sel);
     273                        final var elem = new GpxDataWrapper(sel.getName(), data, sel);
    275274                        gpxModel.addElement(elem);
    276275                        gpxModel.setSelectedItem(elem);
     
    284283    }
    285284
    286     private class UseSupportLayerActionListener implements ActionListener {
     285    private final class UseSupportLayerActionListener implements ActionListener {
    287286
    288287        @Override
     
    296295    }
    297296
    298     private class AdvancedSettingsActionListener implements ActionListener {
     297    private final class AdvancedSettingsActionListener implements ActionListener {
    299298
    300299        @Override
    301300        public void actionPerformed(ActionEvent e) {
    302             AdvancedCorrelationSettingsDialog ed = new AdvancedCorrelationSettingsDialog(MainApplication.getMainFrame(), forceTags);
     301            final var ed = new AdvancedCorrelationSettingsDialog(MainApplication.getMainFrame(), forceTags);
    303302            if (ed.showDialog().getValue() == 1) {
    304303                forceTags = ed.isForceTaggingSelected(); // This setting is not supposed to be saved permanently
     
    317316     * @author chris
    318317     */
    319     private class SetOffsetActionListener implements ActionListener {
     318    private final class SetOffsetActionListener implements ActionListener {
    320319
    321320        @Override
    322321        public void actionPerformed(ActionEvent e) {
    323             boolean isOk = false;
     322            var isOk = false;
    324323            while (!isOk) {
    325                 SynchronizeTimeFromPhotoDialog ed = new SynchronizeTimeFromPhotoDialog(
    326                         MainApplication.getMainFrame(), yLayer.getImageData().getImages());
     324                final var ed = new SynchronizeTimeFromPhotoDialog(MainApplication.getMainFrame(), yLayer.getImageData().getImages());
    327325                int answer = ed.showDialog().getValue();
    328326                if (answer != 1)
     
    340338                }
    341339
    342                 TimeZoneItem selectedTz = ed.getTimeZoneItem();
     340                final var selectedTz = ed.getTimeZoneItem();
    343341
    344342                Config.getPref().put("geoimage.timezoneid", selectedTz.getID());
     
    354352    }
    355353
    356     private static class GpxLayerAddedListener implements LayerChangeListener {
     354    private static final class GpxLayerAddedListener implements LayerChangeListener {
    357355        @Override
    358356        public void layerAdded(LayerAddEvent e) {
    359             Layer layer = e.getAddedLayer();
     357            final var layer = e.getAddedLayer();
    360358            if (layer instanceof GpxDataContainer) {
    361                 GpxData gpx = ((GpxDataContainer) layer).getGpxData();
    362                 File file = gpx.storageFile;
     359                final var gpx = ((GpxDataContainer) layer).getGpxData();
     360                final var file = gpx.storageFile;
    363361                removeDuplicates(file);
    364                 GpxDataWrapper gdw = new GpxDataWrapper(layer.getName(), gpx, file);
     362                final var gdw = new GpxDataWrapper(layer.getName(), gpx, file);
    365363                layer.addPropertyChangeListener(new GpxLayerRenamedListener(gdw));
    366364                gpxModel.addElement(gdw);
     
    376374        @Override
    377375        public void layerRemoving(LayerRemoveEvent e) {
    378             Layer layer = e.getRemovedLayer();
     376            final var layer = e.getRemovedLayer();
    379377            if (layer instanceof GpxDataContainer) {
    380                 GpxData removedGpxData = ((GpxDataContainer) layer).getGpxData();
     378                final var removedGpxData = ((GpxDataContainer) layer).getGpxData();
    381379                for (int i = gpxModel.getSize() - 1; i >= 0; i--) {
    382380                    GpxData data = gpxModel.getElementAt(i).data;
     
    428426        for (AbstractModifiableLayer cur : MainApplication.getLayerManager().getLayersOfType(AbstractModifiableLayer.class)) {
    429427            if (cur instanceof GpxDataContainer) {
    430                 GpxData data = ((GpxDataContainer) cur).getGpxData();
    431                 GpxDataWrapper gdw = new GpxDataWrapper(cur.getName(), data, data.storageFile);
     428                final var data = ((GpxDataContainer) cur).getGpxData();
     429                final var gdw = new GpxDataWrapper(cur.getName(), data, data.storageFile);
    432430                cur.addPropertyChangeListener(new GpxLayerRenamedListener(gdw));
    433431                gpxModel.addElement(gdw);
     
    471469    @Override
    472470    public void actionPerformed(ActionEvent ae) {
    473         NoGpxDataWrapper nogdw = new NoGpxDataWrapper();
     471        final var nogdw = new NoGpxDataWrapper();
    474472        if (gpxModel == null) {
    475473            constructGpxModel(nogdw);
    476474        }
    477475
    478         JPanel panelCb = new JPanel();
     476        final var panelCb = new JPanel();
    479477
    480478        panelCb.add(new JLabel(tr("GPX track: ")));
     
    485483        panelCb.add(cbGpx);
    486484
    487         JButton buttonOpen = new JButton(tr("Open another GPX trace"));
     485        final var buttonOpen = new JButton(tr("Open another GPX trace"));
    488486        buttonOpen.addActionListener(new LoadGpxDataActionListener());
    489487        panelCb.add(buttonOpen);
     
    493491        panelCb.add(buttonSupport);
    494492
    495         JPanel panelTf = new JPanel(new GridBagLayout());
     493        final var panelTf = new JPanel(new GridBagLayout());
    496494
    497495        timezone = loadTimezone();
     
    505503        tfOffset.setText(delta.formatOffset());
    506504
    507         JButton buttonViewGpsPhoto = new JButton(tr("<html>Use photo of an accurate clock,<br>e.g. GPS receiver display</html>"));
     505        final var buttonViewGpsPhoto = new JButton(tr("<html>Use photo of an accurate clock,<br>e.g. GPS receiver display</html>"));
    508506        buttonViewGpsPhoto.setIcon(ImageProvider.get("clock"));
    509507        buttonViewGpsPhoto.addActionListener(new SetOffsetActionListener());
    510508
    511         JButton buttonAutoGuess = new JButton(tr("Auto-Guess"));
     509        final var buttonAutoGuess = new JButton(tr("Auto-Guess"));
    512510        buttonAutoGuess.setToolTipText(tr("Matches first photo with first gpx point"));
    513511        buttonAutoGuess.addActionListener(new AutoGuessActionListener());
    514512
    515         JButton buttonAdjust = new JButton(tr("Manual adjust"));
     513        final var buttonAdjust = new JButton(tr("Manual adjust"));
    516514        buttonAdjust.addActionListener(new AdjustActionListener());
    517515
    518         JButton buttonAdvanced = new JButton(tr("Advanced settings..."));
     516        final var buttonAdvanced = new JButton(tr("Advanced settings..."));
    519517        buttonAdvanced.addActionListener(new AdvancedSettingsActionListener());
    520518
    521         JLabel labelPosition = new JLabel(tr("Override position for: "));
     519        final var labelPosition = new JLabel(tr("Override position for: "));
    522520
    523521        int numAll = yLayer.getSortedImgList(true, true).size();
     
    537535        cbShowThumbs.setEnabled(!yLayer.thumbsLoaded);
    538536
    539         int y = 0;
    540         GBC gbc = GBC.eol();
     537        var y = 0;
     538        var gbc = GBC.eol();
    541539        gbc.gridx = 0;
    542540        gbc.gridy = y++;
    543541        panelTf.add(panelCb, gbc);
    544542
    545         gbc = GBC.eol().fill(GBC.HORIZONTAL).insets(0, 0, 0, 12);
     543        gbc = GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(0, 0, 0, 12);
    546544        gbc.gridx = 0;
    547545        gbc.gridy = y++;
     
    553551        panelTf.add(new JLabel(tr("Timezone: ")), gbc);
    554552
    555         gbc = GBC.std().fill(GBC.HORIZONTAL);
     553        gbc = GBC.std().fill(GridBagConstraints.HORIZONTAL);
    556554        gbc.gridx = 1;
    557555        gbc.gridy = y++;
     
    564562        panelTf.add(new JLabel(tr("Offset:")), gbc);
    565563
    566         gbc = GBC.std().fill(GBC.HORIZONTAL);
     564        gbc = GBC.std().fill(GridBagConstraints.HORIZONTAL);
    567565        gbc.gridx = 1;
    568566        gbc.gridy = y++;
     
    579577        panelTf.add(buttonViewGpsPhoto, gbc);
    580578
    581         gbc = GBC.std().fill(GBC.BOTH).insets(5, 5, 5, 5);
     579        gbc = GBC.std().fill(GridBagConstraints.BOTH).insets(5, 5, 5, 5);
    582580        gbc.gridx = 1;
    583581        gbc.gridy = y++;
     
    591589        panelTf.add(buttonAdjust, gbc);
    592590
    593         gbc = GBC.eol().fill(GBC.HORIZONTAL).insets(0, 12, 0, 0);
     591        gbc = GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(0, 12, 0, 0);
    594592        gbc.gridx = 0;
    595593        gbc.gridy = y++;
     
    616614        panelTf.add(cbShowThumbs, gbc);
    617615
    618         gbc = GBC.eol().fill(GBC.HORIZONTAL).insets(0, 12, 0, 0);
     616        gbc = GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(0, 12, 0, 0);
    619617        sepDirectionPosition = new JSeparator(SwingConstants.HORIZONTAL);
    620618        panelTf.add(sepDirectionPosition, gbc);
     
    627625        expertChanged(ExpertToggleAction.isExpert());
    628626
    629         final JPanel statusBar = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
     627        final var statusBar = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
    630628        statusBar.setBorder(BorderFactory.createLoweredBevelBorder());
    631629        statusBarText = new JLabel(" ");
     
    633631        statusBar.add(statusBarText);
    634632
    635         RepaintTheMapListener repaintTheMap = new RepaintTheMapListener(yLayer);
     633        final var repaintTheMap = new RepaintTheMapListener(yLayer);
    636634        pDirectionPosition.addFocusListenerOnComponent(repaintTheMap);
    637635        tfTimezone.addFocusListener(repaintTheMap);
     
    808806     * Presents dialog with sliders for manual adjust.
    809807     */
    810     private class AdjustActionListener implements ActionListener {
     808    private final class AdjustActionListener implements ActionListener {
    811809
    812810        @Override
    813811        public void actionPerformed(ActionEvent e) {
    814812
    815             final GpxTimeOffset offset = GpxTimeOffset.milliseconds(
     813            final var offset = GpxTimeOffset.milliseconds(
    816814                    delta.getMilliseconds() + Math.round(timezone.getHours() * TimeUnit.HOURS.toMillis(1)));
    817815            final int dayOffset = offset.getDayOffset();
     
    895893    }
    896894
    897     private class AutoGuessActionListener implements ActionListener {
     895    private final class AutoGuessActionListener implements ActionListener {
    898896
    899897        @Override
     
    943941    }
    944942
    945     private GpxDataWrapper selectedGPX(boolean complain) {
     943    private static GpxDataWrapper selectedGPX(boolean complain) {
    946944        Object item = gpxModel.getSelectedItem();
    947945
     
    961959        if (cbGpx != null) {
    962960            // Force the JCombobox to remove its eventListener from the static GpxDataWrapper
    963             cbGpx.setModel(new DefaultComboBoxModel<GpxDataWrapper>());
     961            cbGpx.setModel(new DefaultComboBoxModel<>());
    964962            cbGpx = null;
    965963        }
  • trunk/src/org/openstreetmap/josm/gui/layer/geoimage/RemoteEntry.java

    r18806 r19048  
    296296    @Override
    297297    public InputStream getInputStream() throws IOException {
    298         URI u = getImageURI();
     298        final var u = getImageURI();
    299299        if (u.getScheme().contains("file")) {
    300300            return Files.newInputStream(Paths.get(u));
    301301        }
    302         HttpClient client = HttpClient.create(u.toURL());
     302        final var client = HttpClient.create(u.toURL());
    303303        InputStream actual = client.connect().getContent();
    304304        return new BufferedInputStream(actual) {
     
    343343    @Override
    344344    public boolean equals(Object obj) {
    345         if (super.equals(obj)) {
     345        if (this == obj) {
    346346            return true;
    347347        }
  • trunk/src/org/openstreetmap/josm/gui/mappaint/styleelement/LabelCompositionStrategy.java

    r19045 r19048  
    167167        /* Is joining an array really that complicated in Java? */
    168168        private static String[] getDefaultNameTags() {
    169             ArrayList<String> tags = new ArrayList<String>(Arrays.asList(LanguageInfo.getOSMLocaleCodes("name:")));
    170             tags.addAll(Arrays.asList(new String[]{
    171                 "name",
    172                 "int_name",
    173                 "distance",
    174                 "railway:position",
    175                 "ref",
    176                 "operator",
    177                 "brand",
    178                 "addr:unit",
    179                 "addr:flats",
    180                 "addr:housenumber"
    181             }));
     169            final var tags = new ArrayList<String>(Arrays.asList(LanguageInfo.getOSMLocaleCodes("name:")));
     170            tags.addAll(Arrays.asList("name",
     171                    "int_name",
     172                    "distance",
     173                    "railway:position",
     174                    "ref",
     175                    "operator",
     176                    "brand",
     177                    "addr:unit",
     178                    "addr:flats",
     179                    "addr:housenumber"));
    182180            return tags.toArray(String[]::new);
    183181        }
     
    251249
    252250        private String getPrimitiveName(IPrimitive n) {
    253             StringBuilder name = new StringBuilder();
     251            final var name = new StringBuilder();
    254252            if (!n.hasKeys()) return null;
    255253            nameTags.stream().map(n::get).filter(Objects::nonNull).findFirst()
  • trunk/src/org/openstreetmap/josm/gui/widgets/JosmTextField.java

    r18538 r19048  
    55import java.awt.ComponentOrientation;
    66import java.awt.Font;
    7 import java.awt.FontMetrics;
    87import java.awt.Graphics;
    98import java.awt.Graphics2D;
     
    1918
    2019import javax.swing.Icon;
     20import javax.swing.JMenuItem;
     21import javax.swing.JPopupMenu;
    2122import javax.swing.JTextField;
    2223import javax.swing.RepaintManager;
    23 import javax.swing.JMenuItem;
    24 import javax.swing.JPopupMenu;
    2524import javax.swing.UIManager;
    2625import javax.swing.text.BadLocationException;
     
    3029import org.openstreetmap.josm.gui.MapFrame;
    3130import org.openstreetmap.josm.tools.Destroyable;
     31import org.openstreetmap.josm.tools.Logging;
    3232import org.openstreetmap.josm.tools.Utils;
    3333
     
    254254     */
    255255    public static Color getHintTextColor() {
    256         Color color = UIManager.getColor("TextField[Disabled].textForeground"); // Nimbus?
     256        var color = UIManager.getColor("TextField[Disabled].textForeground"); // Nimbus?
    257257        if (color == null)
    258258            color = UIManager.getColor("TextField.inactiveForeground");
     
    290290        int x;
    291291        try {
    292             x = modelToView(0).x;
     292            x = (int) Math.round(modelToView2D(0).getX());
    293293        } catch (BadLocationException exc) {
     294            Logging.trace(exc);
    294295            return; // can't happen
    295296        }
     
    304305            g.drawString(getHint(), x, getBaseline(getWidth(), getHeight()));
    305306        } else {
    306             FontMetrics metrics = g.getFontMetrics(g.getFont());
     307            final var metrics = g.getFontMetrics(g.getFont());
    307308            int dx = metrics.stringWidth(getHint());
    308309            g.drawString(getHint(), x - dx, getBaseline(getWidth(), getHeight()));
  • trunk/src/org/openstreetmap/josm/io/NoteReader.java

    r17712 r19048  
    5252     * Reads both API style and planet dump style formats.
    5353     */
    54     private class Parser extends DefaultHandler {
     54    private final class Parser extends DefaultHandler {
    5555
    5656        private NoteParseMode parseMode;
     
    7373        public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
    7474            buffer.setLength(0);
    75             switch(qName) {
     75            switch (qName) {
    7676            case "osm":
    7777                parseMode = NoteParseMode.API;
     
    9292
    9393            //The rest only applies for dump mode
    94             switch(qName) {
     94            switch (qName) {
    9595            case "note":
    9696                thisNote = parseNoteFull(attrs);
     
    113113            }
    114114            if ("comment".equals(qName)) {
    115                 User commentUser = User.createOsmUser(commentUid, commentUsername);
     115                final User commentUser;
    116116                if (commentUid == 0) {
    117117                    commentUser = User.getAnonymous();
     118                } else {
     119                    commentUser = User.createOsmUser(commentUid, commentUsername);
    118120                }
    119121                if (parseMode == NoteParseMode.API) {
     
    177179
    178180    static LatLon parseLatLon(UnaryOperator<String> attrs) {
    179         double lat = Double.parseDouble(attrs.apply("lat"));
    180         double lon = Double.parseDouble(attrs.apply("lon"));
     181        final var lat = Double.parseDouble(attrs.apply("lat"));
     182        final var lon = Double.parseDouble(attrs.apply("lon"));
    181183        return new LatLon(lat, lon);
    182184    }
     
    195197
    196198    static Note parseNoteFull(UnaryOperator<String> attrs) {
    197         Note note = parseNoteBasic(attrs);
     199        final var note = parseNoteBasic(attrs);
    198200        String id = attrs.apply("id");
    199201        if (id != null) {
  • trunk/src/org/openstreetmap/josm/io/OsmPbfReader.java

    r19038 r19048  
    1616import java.util.Set;
    1717
    18 import org.apache.commons.compress.utils.CountingInputStream;
     18import org.apache.commons.io.input.BoundedInputStream;
    1919import org.openstreetmap.josm.data.Bounds;
    2020import org.openstreetmap.josm.data.DataSource;
     
    8888
    8989    private void parse(InputStream source) throws IllegalDataException, IOException {
    90         final CountingInputStream inputStream;
     90        final BoundedInputStream inputStream;
    9191        if (source.markSupported()) {
    92             inputStream = new CountingInputStream(source);
     92            inputStream = new BoundedInputStream(source);
    9393        } else {
    94             inputStream = new CountingInputStream(new BufferedInputStream(source));
    95         }
    96         try (ProtobufParser parser = new ProtobufParser(inputStream)) {
    97             final ByteArrayOutputStream baos = new ByteArrayOutputStream();
     94            inputStream = new BoundedInputStream(new BufferedInputStream(source));
     95        }
     96        try (var parser = new ProtobufParser(inputStream)) {
     97            final var baos = new ByteArrayOutputStream();
    9898            HeaderBlock headerBlock = null;
    9999            BlobHeader blobHeader = null;
     
    106106                    }
    107107                    // OSM PBF is fun -- it has *nested* pbf data
    108                     Blob blob = parseBlob(blobHeader, inputStream, parser, baos);
     108                    final var blob = parseBlob(blobHeader, inputStream, parser, baos);
    109109                    headerBlock = parseHeaderBlock(blob, baos);
    110110                    checkRequiredFeatures(headerBlock);
     
    114114                        throw new IllegalStateException("A header block must occur before the first data block");
    115115                    }
    116                     Blob blob = parseBlob(blobHeader, inputStream, parser, baos);
     116                    final var blob = parseBlob(blobHeader, inputStream, parser, baos);
    117117                    parseDataBlock(baos, headerBlock, blob);
    118118                    blobHeader = null;
     
    133133     */
    134134    @Nonnull
    135     private static BlobHeader parseBlobHeader(CountingInputStream cis, ByteArrayOutputStream baos, ProtobufParser parser)
     135    private static BlobHeader parseBlobHeader(BoundedInputStream cis, ByteArrayOutputStream baos, ProtobufParser parser)
    136136            throws IOException, IllegalDataException {
    137137        String type = null;
    138138        byte[] indexData = null;
    139139        int datasize = Integer.MIN_VALUE;
    140         int length = 0;
    141         long start = cis.getBytesRead();
    142         while (parser.hasNext() && (length == 0 || cis.getBytesRead() - start < length)) {
    143             final ProtobufRecord current = new ProtobufRecord(baos, parser);
     140        var length = 0;
     141        long start = cis.getCount();
     142        while (parser.hasNext() && (length == 0 || cis.getCount() - start < length)) {
     143            final var current = new ProtobufRecord(baos, parser);
    144144            switch (current.getField()) {
    145145                case 1:
     
    153153                    break;
    154154                default:
    155                     start = cis.getBytesRead();
     155                    start = cis.getCount();
    156156                    length += current.asUnsignedVarInt().intValue();
    157157                    if (length > MAX_BLOBHEADER_SIZE) { // There is a hard limit of 64 KiB for the BlobHeader. It *should* be less than 32 KiB.
     
    181181     */
    182182    @Nonnull
    183     private static Blob parseBlob(BlobHeader header, CountingInputStream cis, ProtobufParser parser, ByteArrayOutputStream baos)
     183    private static Blob parseBlob(BlobHeader header, BoundedInputStream cis, ProtobufParser parser, ByteArrayOutputStream baos)
    184184            throws IOException {
    185         long start = cis.getBytesRead();
     185        long start = cis.getCount();
    186186        int size = Integer.MIN_VALUE;
    187187        Blob.CompressionType type = null;
     
    189189        // Needed since size and compression type + compression data may be in a different order
    190190        byte[] bytes = null;
    191         while (parser.hasNext() && cis.getBytesRead() - start < header.dataSize()) {
     191        while (parser.hasNext() && cis.getCount() - start < header.dataSize()) {
    192192            current = new ProtobufRecord(baos, parser);
    193193            switch (current.getField()) {
     
    239239    @Nonnull
    240240    private static HeaderBlock parseHeaderBlock(Blob blob, ByteArrayOutputStream baos) throws IOException {
    241         try (InputStream blobInput = blob.inputStream();
    242              ProtobufParser parser = new ProtobufParser(blobInput)) {
     241        try (var blobInput = blob.inputStream();
     242             var parser = new ProtobufParser(blobInput)) {
    243243            BBox bbox = null;
    244             List<String> required = new ArrayList<>();
    245             List<String> optional = new ArrayList<>();
     244            final var required = new ArrayList<String>();
     245            final var optional = new ArrayList<String>();
    246246            String program = null;
    247247            String source = null;
     
    250250            String osmosisReplicationBaseUrl = null;
    251251            while (parser.hasNext()) {
    252                 final ProtobufRecord current = new ProtobufRecord(baos, parser);
     252                final var current = new ProtobufRecord(baos, parser);
    253253                switch (current.getField()) {
    254254                    case 1: // bbox
     
    311311        String[] stringTable = null; // field 1, note that stringTable[0] is a delimiter, so it is always blank and unused
    312312        // field 2 -- we cannot parse these live just in case the following fields come later
    313         List<ProtobufRecord> primitiveGroups = new ArrayList<>();
    314         int granularity = 100; // field 17
     313        final var primitiveGroups = new ArrayList<ProtobufRecord>();
     314        var granularity = 100; // field 17
    315315        long latOffset = 0; // field 19
    316316        long lonOffset = 0; // field 20
    317         int dateGranularity = 1000; // field 18, default is milliseconds since the 1970 epoch
    318         try (InputStream inputStream = blob.inputStream();
    319              ProtobufParser parser = new ProtobufParser(inputStream)) {
     317        var dateGranularity = 1000; // field 18, default is milliseconds since the 1970 epoch
     318        try (var inputStream = blob.inputStream();
     319             var parser = new ProtobufParser(inputStream)) {
    320320            while (parser.hasNext()) {
    321                 ProtobufRecord protobufRecord = new ProtobufRecord(baos, parser);
     321                final var protobufRecord = new ProtobufRecord(baos, parser);
    322322                switch (protobufRecord.getField()) {
    323323                    case 1:
     
    343343            }
    344344        }
    345         final PrimitiveBlockRecord primitiveBlockRecord = new PrimitiveBlockRecord(stringTable, granularity, latOffset, lonOffset,
     345        final var primitiveBlockRecord = new PrimitiveBlockRecord(stringTable, granularity, latOffset, lonOffset,
    346346                dateGranularity);
    347         final DataSet ds = getDataSet();
     347        final var ds = getDataSet();
    348348        if (!primitiveGroups.isEmpty() && headerBlock.bbox() != null) {
    349349            try {
     
    375375    @Nullable
    376376    private static BBox parseBBox(ByteArrayOutputStream baos, ProtobufRecord current) throws IOException {
    377         try (ByteArrayInputStream bboxInputStream = new ByteArrayInputStream(current.getBytes());
    378              ProtobufParser bboxParser = new ProtobufParser(bboxInputStream)) {
     377        try (var bboxInputStream = new ByteArrayInputStream(current.getBytes());
     378             var bboxParser = new ProtobufParser(bboxInputStream)) {
    379379            double left = Double.NaN;
    380380            double right = Double.NaN;
     
    382382            double bottom = Double.NaN;
    383383            while (bboxParser.hasNext()) {
    384                 ProtobufRecord protobufRecord = new ProtobufRecord(baos, bboxParser);
     384                final var protobufRecord = new ProtobufRecord(baos, bboxParser);
    385385                if (protobufRecord.getType() == WireType.VARINT) {
    386386                    double value = protobufRecord.asSignedVarInt().longValue() * NANO_DEGREES;
     
    419419    @Nonnull
    420420    private static String[] parseStringTable(ByteArrayOutputStream baos, byte[] bytes) throws IOException {
    421         try (ByteArrayInputStream is = new ByteArrayInputStream(bytes);
    422              ProtobufParser parser = new ProtobufParser(is)) {
    423             List<String> list = new ArrayList<>();
     421        try (var is = new ByteArrayInputStream(bytes);
     422             var parser = new ProtobufParser(is)) {
     423            final var list = new ArrayList<String>();
    424424            while (parser.hasNext()) {
    425                 ProtobufRecord protobufRecord = new ProtobufRecord(baos, parser);
     425                final var protobufRecord = new ProtobufRecord(baos, parser);
    426426                if (protobufRecord.getField() == 1) {
    427427                    list.add(protobufRecord.asString().intern()); // field is technically repeated bytes
     
    444444    private void parsePrimitiveGroup(ByteArrayOutputStream baos, byte[] bytes, PrimitiveBlockRecord primitiveBlockRecord)
    445445            throws IllegalDataException, IOException {
    446         try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    447              ProtobufParser parser = new ProtobufParser(bais)) {
     446        try (var bais = new ByteArrayInputStream(bytes);
     447             var parser = new ProtobufParser(bais)) {
    448448            while (parser.hasNext()) {
    449                 ProtobufRecord protobufRecord = new ProtobufRecord(baos, parser);
     449                final var protobufRecord = new ProtobufRecord(baos, parser);
    450450                switch (protobufRecord.getField()) {
    451451                    case 1: // Nodes, repeated
     
    480480    private void parseNode(ByteArrayOutputStream baos, byte[] bytes, PrimitiveBlockRecord primitiveBlockRecord)
    481481            throws IllegalDataException, IOException {
    482         try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    483              ProtobufParser parser = new ProtobufParser(bais)) {
     482        try (var bais = new ByteArrayInputStream(bytes);
     483             var parser = new ProtobufParser(bais)) {
    484484            long id = Long.MIN_VALUE;
    485             List<String> keys = new ArrayList<>();
    486             List<String> values = new ArrayList<>();
     485            final var keys = new ArrayList<String>();
     486            final var values = new ArrayList<String>();
    487487            Info info = null;
    488488            long lat = Long.MIN_VALUE;
    489489            long lon = Long.MIN_VALUE;
    490490            while (parser.hasNext()) {
    491                 ProtobufRecord protobufRecord = new ProtobufRecord(baos, parser);
     491                final var protobufRecord = new ProtobufRecord(baos, parser);
    492492                switch (protobufRecord.getField()) {
    493493                    case 1:
     
    519519                throw new IllegalDataException("OSM PBF did not provide all the required node information");
    520520            }
    521             NodeData node = new NodeData(id);
     521            final var node = new NodeData(id);
    522522            node.setCoor(calculateLatLon(primitiveBlockRecord, lat, lon));
    523523            addTags(node, keys, values);
     
    547547        long[] keyVals = EMPTY_LONG; // technically can be int
    548548        Info[] denseInfo = null;
    549         try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    550              ProtobufParser parser = new ProtobufParser(bais)) {
     549        try (var bais = new ByteArrayInputStream(bytes);
     550             var parser = new ProtobufParser(bais)) {
    551551            while (parser.hasNext()) {
    552                 ProtobufRecord protobufRecord = new ProtobufRecord(baos, parser);
     552                final var protobufRecord = new ProtobufRecord(baos, parser);
    553553                switch (protobufRecord.getField()) {
    554554                    case 1: // packed node ids, DELTA encoded
     
    576576        }
    577577
    578         int keyValIndex = 0; // This index must not reset between nodes, and must always increment
     578        var keyValIndex = 0; // This index must not reset between nodes, and must always increment
    579579        if (ids.length == lats.length && lats.length == lons.length && (denseInfo == null || denseInfo.length == lons.length)) {
    580580            long id = 0;
    581581            long lat = 0;
    582582            long lon = 0;
    583             for (int i = 0; i < ids.length; i++) {
     583            for (var i = 0; i < ids.length; i++) {
    584584                final NodeData node;
    585585                id += ids[i];
    586586                node = new NodeData(id);
    587587                if (denseInfo != null) {
    588                     Info info = denseInfo[i];
     588                    final var info = denseInfo[i];
    589589                    setOsmPrimitiveData(primitiveBlockRecord, node, info);
    590590                } else {
     
    638638        // We don't do live drawing, so we don't care about lats and lons (we essentially throw them away with the current parser)
    639639        // This is for the optional feature "LocationsOnWays"
    640         try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    641              ProtobufParser parser = new ProtobufParser(bais)) {
     640        try (var bais = new ByteArrayInputStream(bytes);
     641             var parser = new ProtobufParser(bais)) {
    642642            while (parser.hasNext()) {
    643                 ProtobufRecord protobufRecord = new ProtobufRecord(baos, parser);
     643                final var protobufRecord = new ProtobufRecord(baos, parser);
    644644                switch (protobufRecord.getField()) {
    645645                    case 1:
     
    672672            throw new IllegalDataException("A way with either no id or no nodes was found");
    673673        }
    674         WayData wayData = new WayData(id);
    675         List<Long> nodeIds = new ArrayList<>(refs.length);
     674        final var wayData = new WayData(id);
     675        final var nodeIds = new ArrayList<Long>(refs.length);
    676676        long ref = 0;
    677677        for (long tRef : refs) {
     
    701701            throws IllegalDataException, IOException {
    702702        long id = Long.MIN_VALUE;
    703         List<String> keys = new ArrayList<>();
    704         List<String> values = new ArrayList<>();
     703        final var keys = new ArrayList<String>();
     704        final var values = new ArrayList<String>();
    705705        Info info = null;
    706706        long[] rolesStringId = EMPTY_LONG; // Technically int
    707707        long[] memids = EMPTY_LONG;
    708708        long[] types = EMPTY_LONG; // Technically an enum
    709         try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    710              ProtobufParser parser = new ProtobufParser(bais)) {
     709        try (var bais = new ByteArrayInputStream(bytes);
     710             var parser = new ProtobufParser(bais)) {
    711711            while (parser.hasNext()) {
    712                 ProtobufRecord protobufRecord = new ProtobufRecord(baos, parser);
     712                final var protobufRecord = new ProtobufRecord(baos, parser);
    713713                switch (protobufRecord.getField()) {
    714714                    case 1:
     
    747747            throw new IllegalDataException("OSM PBF contains a bad relation definition");
    748748        }
    749         RelationData data = new RelationData(id);
     749        final var data = new RelationData(id);
    750750        if (info != null) {
    751751            setOsmPrimitiveData(primitiveBlockRecord, data, info);
     
    757757        List<RelationMemberData> members = new ArrayList<>(rolesStringId.length);
    758758        long memberId = 0;
    759         for (int i = 0; i < rolesStringId.length; i++) {
     759        for (var i = 0; i < rolesStringId.length; i++) {
    760760            String role = primitiveBlockRecord.stringTable[(int) rolesStringId[i]];
    761761            memberId += memids[i];
     
    777777    @Nonnull
    778778    private static Info parseInfo(ByteArrayOutputStream baos, byte[] bytes) throws IOException {
    779         try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    780              ProtobufParser parser = new ProtobufParser(bais)) {
     779        try (var bais = new ByteArrayInputStream(bytes);
     780             var parser = new ProtobufParser(bais)) {
    781781            int version = -1;
    782782            Long timestamp = null;
     
    784784            Integer uid = null;
    785785            Integer userSid = null;
    786             boolean visible = true;
     786            var visible = true;
    787787            while (parser.hasNext()) {
    788                 ProtobufRecord protobufRecord = new ProtobufRecord(baos, parser);
     788                final var protobufRecord = new ProtobufRecord(baos, parser);
    789789                switch (protobufRecord.getField()) {
    790790                    case 1:
     
    839839        }
    840840        Map<String, String> tagMap = new HashMap<>(keys.size());
    841         for (int i = 0; i < keys.size(); i++) {
     841        for (var i = 0; i < keys.size(); i++) {
    842842            tagMap.put(keys.get(i), values.get(i));
    843843        }
     
    879879    @Nonnull
    880880    private static long[] decodePackedSInt64(long[] numbers) {
    881         for (int i = 0; i < numbers.length; i++) {
     881        for (var i = 0; i < numbers.length; i++) {
    882882            numbers[i] = ProtobufParser.decodeZigZag(numbers[i]);
    883883        }
     
    922922        long[] userSid = EMPTY_LONG; // technically int
    923923        long[] visible = EMPTY_LONG; // optional, true if not set, technically booleans
    924         try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    925              ProtobufParser parser = new ProtobufParser(bais)) {
     924        try (var bais = new ByteArrayInputStream(bytes);
     925             var parser = new ProtobufParser(bais)) {
    926926            while (parser.hasNext()) {
    927                 ProtobufRecord protobufRecord = new ProtobufRecord(baos, parser);
     927                final var protobufRecord = new ProtobufRecord(baos, parser);
    928928                switch (protobufRecord.getField()) {
    929929                    case 1:
     
    956956        }
    957957        if (version.length > 0) {
    958             Info[] infos = new Info[version.length];
     958            final var infos = new Info[version.length];
    959959            long lastTimestamp = 0; // delta encoded
    960960            long lastChangeset = 0; // delta encoded
    961961            long lastUid = 0; // delta encoded,
    962962            long lastUserSid = 0; // delta encoded, string id for username
    963             for (int i = 0; i < version.length; i++) {
     963            for (var i = 0; i < version.length; i++) {
    964964                if (timestamp.length > i)
    965965                    lastTimestamp += timestamp[i];
  • trunk/src/org/openstreetmap/josm/tools/ImageResizeMode.java

    r17144 r19048  
    8787     */
    8888    BufferedImage createBufferedImage(Dimension dim, Dimension icon, Consumer<Graphics2D> renderer, Image sourceIcon) {
    89         final Dimension real = computeDimension(dim, icon);
    90         final BufferedImage bufferedImage = new BufferedImage(real.width, real.height, BufferedImage.TYPE_INT_ARGB);
     89        final var real = computeDimension(dim, icon);
     90        final var bufferedImage = new BufferedImage(real.width, real.height, BufferedImage.TYPE_INT_ARGB);
    9191        final Graphics2D g = bufferedImage.createGraphics();
    9292        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
     
    119119     * @return a cache key
    120120     */
     121    @SuppressWarnings("EnumOrdinal")
    121122    int cacheKey(Dimension dim) {
    122123        return (ordinal() << 28) | ((dim.width & 0xfff) << 16) | (dim.height & 0xfff);
  • trunk/src/org/openstreetmap/josm/tools/Utils.java

    r18811 r19048  
    3030import java.nio.file.StandardCopyOption;
    3131import java.nio.file.attribute.BasicFileAttributes;
    32 import java.nio.file.attribute.FileTime;
    3332import java.security.MessageDigest;
    3433import java.security.NoSuchAlgorithmException;
     
    153152     */
    154153    public static <T> int indexOf(Iterable<? extends T> collection, Predicate<? super T> predicate) {
    155         int i = 0;
    156         for (T item : collection) {
     154        var i = 0;
     155        for (var item : collection) {
    157156            if (predicate.test(item))
    158157                return i;
     
    186185        if (n <= 0)
    187186            throw new IllegalArgumentException("n must be <= 0 but is " + n);
    188         int res = a % n;
     187        var res = a % n;
    189188        if (res < 0) {
    190189            res += n;
     
    304303            Logging.warn("Unable to create directory "+out.getPath());
    305304        }
    306         File[] files = in.listFiles();
     305        var files = in.listFiles();
    307306        if (files != null) {
    308             for (File f : files) {
    309                 File target = new File(out, f.getName());
     307            for (var f : files) {
     308                var target = new File(out, f.getName());
    310309                if (f.isDirectory()) {
    311310                    copyDirectory(f, target);
     
    325324    public static boolean deleteDirectory(File path) {
    326325        if (path.exists()) {
    327             File[] files = path.listFiles();
     326            var files = path.listFiles();
    328327            if (files != null) {
    329                 for (File file : files) {
     328                for (var file : files) {
    330329                    if (file.isDirectory()) {
    331330                        deleteDirectory(file);
     
    372371     */
    373372    public static boolean deleteFile(File file, String warnMsg) {
    374         boolean result = file.delete();
     373        var result = file.delete();
    375374        if (!result) {
    376375            Logging.warn(tr(warnMsg, file.getPath()));
     
    398397     */
    399398    public static boolean mkDirs(File dir, String warnMsg) {
    400         boolean result = dir.mkdirs();
     399        var result = dir.mkdirs();
    401400        if (!result) {
    402401            Logging.warn(tr(warnMsg, dir.getPath()));
     
    498497            throw new JosmRuntimeException(e);
    499498        }
    500         byte[] byteData = data.getBytes(StandardCharsets.UTF_8);
    501         byte[] byteDigest = md.digest(byteData);
     499        var byteData = data.getBytes(StandardCharsets.UTF_8);
     500        var byteDigest = md.digest(byteData);
    502501        return toHexString(byteDigest);
    503502    }
     
    518517        }
    519518
    520         final int len = bytes.length;
     519        final var len = bytes.length;
    521520        if (len == 0) {
    522521            return "";
    523522        }
    524523
    525         char[] hexChars = new char[len * 2];
    526         int j = 0;
     524        var hexChars = new char[len * 2];
     525        var j = 0;
    527526        for (final int v : bytes) {
    528527            hexChars[j++] = HEX_ARRAY[(v & 0xf0) >> 4];
     
    542541     */
    543542    public static <T> List<T> topologicalSort(final MultiMap<T, T> dependencies) {
    544         MultiMap<T, T> deps = new MultiMap<>();
    545         for (T key : dependencies.keySet()) {
     543        var deps = new MultiMap<T, T>();
     544        for (var key : dependencies.keySet()) {
    546545            deps.putVoid(key);
    547             for (T val : dependencies.get(key)) {
     546            for (var val : dependencies.get(key)) {
    548547                deps.putVoid(val);
    549548                deps.put(key, val);
     
    551550        }
    552551
    553         int size = deps.size();
     552        var size = deps.size();
    554553        List<T> sorted = new ArrayList<>();
    555         for (int i = 0; i < size; ++i) {
    556             T parentless = deps.keySet().stream()
     554        for (var i = 0; i < size; ++i) {
     555            var parentless = deps.keySet().stream()
    557556                    .filter(key -> deps.get(key).isEmpty())
    558557                    .findFirst().orElse(null);
     
    560559            sorted.add(parentless);
    561560            deps.remove(parentless);
    562             for (T key : deps.keySet()) {
     561            for (var key : deps.keySet()) {
    563562                deps.remove(key, parentless);
    564563            }
     
    680679            return Collections.emptyMap();
    681680        } else if (map.size() == 1) {
    682             final Map.Entry<K, V> entry = map.entrySet().iterator().next();
     681            final var entry = map.entrySet().iterator().next();
    683682            return Collections.singletonMap(entry.getKey(), entry.getValue());
    684683        } else if (mapOfEntries != null) {
     
    796795        }
    797796
    798         int start = 0;
    799         int end = str.length();
    800         boolean leadingSkipChar = true;
     797        var start = 0;
     798        var end = str.length();
     799        var leadingSkipChar = true;
    801800        while (leadingSkipChar && start < end) {
    802801            leadingSkipChar = isStrippedChar(str.charAt(start), skipChars);
     
    805804            }
    806805        }
    807         boolean trailingSkipChar = true;
     806        var trailingSkipChar = true;
    808807        while (trailingSkipChar && end > start) {
    809808            trailingSkipChar = isStrippedChar(str.charAt(end - 1), skipChars);
     
    867866            Logging.debug(String.join(" ", command));
    868867        }
    869         Path out = Files.createTempFile("josm_exec_" + command.get(0) + "_", ".txt");
     868        var out = Files.createTempFile("josm_exec_" + command.get(0) + "_", ".txt");
    870869        try {
    871             Process p = new ProcessBuilder(command).redirectErrorStream(true).redirectOutput(out.toFile()).start();
     870            var p = new ProcessBuilder(command).redirectErrorStream(true).redirectOutput(out.toFile()).start();
    872871            if (!p.waitFor(timeout, unit) || p.exitValue() != 0) {
    873872                throw new ExecutionException(command.toString(), null);
     
    889888     */
    890889    public static File getJosmTempDir() {
    891         String tmpDir = getSystemProperty("java.io.tmpdir");
     890        var tmpDir = getSystemProperty("java.io.tmpdir");
    892891        if (tmpDir == null) {
    893892            return null;
    894893        }
    895         File josmTmpDir = new File(tmpDir, "JOSM");
     894        final var josmTmpDir = new File(tmpDir, "JOSM");
    896895        if (!josmTmpDir.exists() && !josmTmpDir.mkdirs()) {
    897896            Logging.warn("Unable to create temp directory " + josmTmpDir);
     
    921920        // Is it less than 1 hour ?
    922921        if (elapsedTime < MILLIS_OF_HOUR) {
    923             final long min = elapsedTime / MILLIS_OF_MINUTE;
     922            final var min = elapsedTime / MILLIS_OF_MINUTE;
    924923            return String.format("%d %s %d %s", min, tr("min"), (elapsedTime - min * MILLIS_OF_MINUTE) / MILLIS_OF_SECOND, tr("s"));
    925924        }
    926925        // Is it less than 1 day ?
    927926        if (elapsedTime < MILLIS_OF_DAY) {
    928             final long hour = elapsedTime / MILLIS_OF_HOUR;
     927            final var hour = elapsedTime / MILLIS_OF_HOUR;
    929928            return String.format("%d %s %d %s", hour, tr("h"), (elapsedTime - hour * MILLIS_OF_HOUR) / MILLIS_OF_MINUTE, tr("min"));
    930929        }
    931         long days = elapsedTime / MILLIS_OF_DAY;
     930        var days = elapsedTime / MILLIS_OF_DAY;
    932931        return String.format("%d %s %d %s", days, trn("day", "days", days), (elapsedTime - days * MILLIS_OF_DAY) / MILLIS_OF_HOUR, tr("h"));
    933932    }
     
    944943            throw new IllegalArgumentException("bytes must be >= 0");
    945944        }
    946         int unitIndex = 0;
     945        var unitIndex = 0;
    947946        double value = bytes;
    948947        while (value >= 1024 && unitIndex < SIZE_UNITS.length) {
     
    968967    public static String getPositionListString(List<Integer> positionList) {
    969968        Collections.sort(positionList);
    970         final StringBuilder sb = new StringBuilder(32);
     969        final var sb = new StringBuilder(32);
    971970        sb.append(positionList.get(0));
    972         int cnt = 0;
     971        var cnt = 0;
    973972        int last = positionList.get(0);
    974         for (int i = 1; i < positionList.size(); ++i) {
     973        for (var i = 1; i < positionList.size(); ++i) {
    975974            int cur = positionList.get(i);
    976975            if (cur == last + 1) {
     
    10311030     */
    10321031    public static Throwable getRootCause(Throwable t) {
    1033         Throwable result = t;
     1032        var result = t;
    10341033        if (result != null) {
    1035             Throwable cause = result.getCause();
     1034            var cause = result.getCause();
    10361035            while (cause != null && !cause.equals(result)) {
    10371036                result = cause;
     
    10511050     */
    10521051    public static <T> T[] addInArrayCopy(T[] array, T item) {
    1053         T[] biggerCopy = Arrays.copyOf(array, array.length + 1);
     1052        var biggerCopy = Arrays.copyOf(array, array.length + 1);
    10541053        biggerCopy[array.length] = item;
    10551054        return biggerCopy;
     
    10641063     */
    10651064    public static String shortenString(String s, int maxLength) {
    1066         final String ellipses = "...";
     1065        final var ellipses = "...";
    10671066        CheckParameterUtil.ensureThat(maxLength >= ellipses.length(), "maxLength is shorter than " + ellipses.length());
    10681067        if (s != null && s.length() > maxLength) {
     
    11021101            if (elements.size() > maxElements) {
    11031102                final Collection<T> r = new ArrayList<>(maxElements);
    1104                 final Iterator<T> it = elements.iterator();
     1103                final var it = elements.iterator();
    11051104                while (r.size() < maxElements - 1) {
    11061105                    r.add(it.next());
     
    11271126            return url;
    11281127
    1129         String query = url.substring(url.indexOf('?') + 1);
    1130 
    1131         StringBuilder sb = new StringBuilder(url.substring(0, url.indexOf('?') + 1));
    1132 
    1133         for (int i = 0; i < query.length(); i++) {
    1134             String c = query.substring(i, i + 1);
     1128        final var query = url.substring(url.indexOf('?') + 1);
     1129
     1130        final var sb = new StringBuilder(url.substring(0, url.indexOf('?') + 1));
     1131
     1132        for (var i = 0; i < query.length(); i++) {
     1133            final var c = query.substring(i, i + 1);
    11351134            if (URL_CHARS.contains(c)) {
    11361135                sb.append(c);
     
    11531152     */
    11541153    public static String encodeUrl(String s) {
    1155         final String enc = StandardCharsets.UTF_8.name();
     1154        final var enc = StandardCharsets.UTF_8.name();
    11561155        try {
    11571156            return URLEncoder.encode(s, enc);
     
    11731172     */
    11741173    public static String decodeUrl(String s) {
    1175         final String enc = StandardCharsets.UTF_8.name();
     1174        final var enc = StandardCharsets.UTF_8.name();
    11761175        try {
    11771176            return URLDecoder.decode(s, enc);
     
    12211220            @Override
    12221221            public Thread newThread(final Runnable runnable) {
    1223                 final Thread thread = new Thread(runnable, String.format(Locale.ENGLISH, nameFormat, count.getAndIncrement()));
     1222                final var thread = new Thread(runnable, String.format(Locale.ENGLISH, nameFormat, count.getAndIncrement()));
    12241223                thread.setPriority(threadPriority);
    12251224                return thread;
     
    12991298    public static boolean isSimilar(String string1, String string2) {
    13001299        // check plain strings
    1301         int distance = getLevenshteinDistance(string1, string2);
     1300        var distance = getLevenshteinDistance(string1, string2);
    13021301
    13031302        // check if only the case differs, so we don't consider large distance as different strings
     
    13401339        }
    13411340
    1342         for (double length : values) {
     1341        for (var length : values) {
    13431342            standardDeviation += Math.pow(length - mean, 2);
    13441343        }
     
    13611360        }
    13621361        List<int[]> groups = new ArrayList<>();
    1363         int[] current = {Integer.MIN_VALUE, Integer.MIN_VALUE};
     1362        var current = new int[]{Integer.MIN_VALUE, Integer.MIN_VALUE};
    13641363        groups.add(current);
    1365         for (int row : integers) {
     1364        for (var row : integers) {
    13661365            if (current[0] == Integer.MIN_VALUE) {
    13671366                current[0] = row;
     
    13981397    @SuppressWarnings("ThreadPriorityCheck")
    13991398    public static ForkJoinPool newForkJoinPool(String pref, final String nameFormat, final int threadPriority) {
    1400         int noThreads = Config.getPref().getInt(pref, Runtime.getRuntime().availableProcessors());
     1399        final var noThreads = Config.getPref().getInt(pref, Runtime.getRuntime().availableProcessors());
    14011400        return new ForkJoinPool(noThreads, new ForkJoinPool.ForkJoinWorkerThreadFactory() {
    14021401            final AtomicLong count = new AtomicLong(0);
     
    14681467        if (value != null) {
    14691468            try {
    1470                 String old = System.setProperty(key, value);
     1469                var old = System.setProperty(key, value);
    14711470                if (Logging.isDebugEnabled() && !value.equals(old)) {
    14721471                    if (!key.toLowerCase(Locale.ENGLISH).contains("password")) {
     
    14941493     */
    14951494    public static boolean hasExtension(String filename, String... extensions) {
    1496         String name = filename.toLowerCase(Locale.ENGLISH).replace("?format=raw", "");
     1495        var name = filename.toLowerCase(Locale.ENGLISH).replace("?format=raw", "");
    14971496        return Arrays.stream(extensions)
    14981497                .anyMatch(ext -> name.endsWith('.' + ext.toLowerCase(Locale.ENGLISH)));
     
    15231522            return new byte[0];
    15241523        }
    1525         try (ByteArrayOutputStream bout = new ByteArrayOutputStream(stream.available())) {
    1526             byte[] buffer = new byte[8192];
    1527             boolean finished = false;
     1524        try (stream; var bout = new ByteArrayOutputStream(stream.available())) {
     1525            final var buffer = new byte[8192];
     1526            var finished = false;
    15281527            do {
    1529                 int read = stream.read(buffer);
     1528                var read = stream.read(buffer);
    15301529                if (read >= 0) {
    15311530                    bout.write(buffer, 0, read);
     
    15371536                return new byte[0];
    15381537            return bout.toByteArray();
    1539         } finally {
    1540             stream.close();
    15411538        }
    15421539    }
     
    16031600     */
    16041601    public static List<GlyphVector> getGlyphVectorsBidi(String string, Font font, FontRenderContext frc) {
    1605         List<GlyphVector> gvs = new ArrayList<>();
    1606         Bidi bidi = new Bidi(string, Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
    1607         byte[] levels = new byte[bidi.getRunCount()];
    1608         DirectionString[] dirStrings = new DirectionString[levels.length];
    1609         for (int i = 0; i < levels.length; ++i) {
     1602        final var gvs = new ArrayList<GlyphVector>();
     1603        final var bidi = new Bidi(string, Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
     1604        final var levels = new byte[bidi.getRunCount()];
     1605        final var dirStrings = new DirectionString[levels.length];
     1606        for (var i = 0; i < levels.length; ++i) {
    16101607            levels[i] = (byte) bidi.getRunLevel(i);
    1611             String substr = string.substring(bidi.getRunStart(i), bidi.getRunLimit(i));
    1612             int dir = levels[i] % 2 == 0 ? Bidi.DIRECTION_LEFT_TO_RIGHT : Bidi.DIRECTION_RIGHT_TO_LEFT;
     1608            final var substr = string.substring(bidi.getRunStart(i), bidi.getRunLimit(i));
     1609            final var dir = levels[i] % 2 == 0 ? Bidi.DIRECTION_LEFT_TO_RIGHT : Bidi.DIRECTION_RIGHT_TO_LEFT;
    16131610            dirStrings[i] = new DirectionString(dir, substr);
    16141611        }
    16151612        Bidi.reorderVisually(levels, 0, dirStrings, 0, levels.length);
    1616         for (DirectionString dirString : dirStrings) {
    1617             char[] chars = dirString.str.toCharArray();
     1613        for (var dirString : dirStrings) {
     1614            var chars = dirString.str.toCharArray();
    16181615            gvs.add(font.layoutGlyphVector(frc, chars, 0, chars.length, dirString.direction));
    16191616        }
     
    17121709    public static int getJavaVersion() {
    17131710        // Switch to Runtime.version() once we move past Java 8
    1714         String version = Objects.requireNonNull(getSystemProperty("java.version"));
     1711        var version = Objects.requireNonNull(getSystemProperty("java.version"));
    17151712        if (version.startsWith("1.")) {
    17161713            version = version.substring(2);
     
    17211718        // 9
    17221719        // 9.0.1
    1723         int dotPos = version.indexOf('.');
    1724         int dashPos = version.indexOf('-');
     1720        var dotPos = version.indexOf('.');
     1721        var dashPos = version.indexOf('-');
    17251722        return Integer.parseInt(version.substring(0,
    17261723                dotPos > -1 ? dotPos : dashPos > -1 ? dashPos : version.length()));
     
    17341731    public static int getJavaUpdate() {
    17351732        // Switch to Runtime.version() once we move past Java 8
    1736         String version = Objects.requireNonNull(getSystemProperty("java.version"));
     1733        var version = Objects.requireNonNull(getSystemProperty("java.version"));
    17371734        if (version.startsWith("1.")) {
    17381735            version = version.substring(2);
     
    17451742        // 17.0.4.1+1-LTS
    17461743        // $MAJOR.$MINOR.$SECURITY.$PATCH
    1747         int undePos = version.indexOf('_');
    1748         int dashPos = version.indexOf('-');
     1744        var undePos = version.indexOf('_');
     1745        var dashPos = version.indexOf('-');
    17491746        if (undePos > -1) {
    17501747            return Integer.parseInt(version.substring(undePos + 1,
    17511748                    dashPos > -1 ? dashPos : version.length()));
    17521749        }
    1753         int firstDotPos = version.indexOf('.');
    1754         int secondDotPos = version.indexOf('.', firstDotPos + 1);
     1750        var firstDotPos = version.indexOf('.');
     1751        var secondDotPos = version.indexOf('.', firstDotPos + 1);
    17551752        if (firstDotPos == secondDotPos) {
    17561753            return 0;
     
    17671764    public static int getJavaBuild() {
    17681765        // Switch to Runtime.version() once we move past Java 8
    1769         String version = Objects.requireNonNull(getSystemProperty("java.runtime.version"));
    1770         int bPos = version.indexOf('b');
    1771         int pPos = version.indexOf('+');
     1766        var version = Objects.requireNonNull(getSystemProperty("java.runtime.version"));
     1767        var bPos = version.indexOf('b');
     1768        var pPos = version.indexOf('+');
    17721769        try {
    17731770            return Integer.parseInt(version.substring(bPos > -1 ? bPos + 1 : pPos + 1));
     
    17861783        try {
    17871784            Object value;
    1788             Class<?> c = Class.forName("com.sun.deploy.config.BuiltInProperties");
     1785            var c = Class.forName("com.sun.deploy.config.BuiltInProperties");
    17891786            try {
    17901787                value = c.getDeclaredField("JRE_EXPIRATION_DATE").get(null);
     
    18101807    public static String getJavaLatestVersion() {
    18111808        try {
    1812             String[] versions = HttpClient.create(
     1809            var versions = HttpClient.create(
    18131810                    new URL(Config.getPref().get(
    18141811                            "java.baseline.version.url",
     
    18161813                    .connect().fetchContent().split("\n", -1);
    18171814            if (getJavaVersion() <= 11 && isRunningWebStart()) { // OpenWebStart currently only has Java 11
    1818                 for (String version : versions) {
     1815                for (var version : versions) {
    18191816                    if (version.startsWith("11")) {
    18201817                        return version;
     
    18221819                }
    18231820            } else if (getJavaVersion() <= 17) {
    1824                 for (String version : versions) {
     1821                for (var version : versions) {
    18251822                    if (version.startsWith("17")) { // Use current Java LTS
    18261823                        return version;
     
    19451942                    return url.openStream();
    19461943                } catch (FileNotFoundException | InvalidPathException e) {
    1947                     URL betterUrl = betterJarUrl(url);
     1944                    final var betterUrl = betterJarUrl(url);
    19481945                    if (betterUrl != null) {
    19491946                        try {
     
    19821979    public static URL betterJarUrl(URL jarUrl, URL defaultUrl) throws IOException {
    19831980        // Workaround to https://bugs.openjdk.java.net/browse/JDK-4523159
    1984         String urlPath = jarUrl.getPath().replace("%20", " ");
     1981        var urlPath = jarUrl.getPath().replace("%20", " ");
    19851982        if (urlPath.startsWith("file:/") && urlPath.split("!", -1).length > 2) {
    19861983            // Locate jar file
    1987             int index = urlPath.lastIndexOf("!/");
    1988             Path jarFile = Paths.get(urlPath.substring("file:/".length(), index));
    1989             Path filename = jarFile.getFileName();
    1990             FileTime jarTime = Files.readAttributes(jarFile, BasicFileAttributes.class).lastModifiedTime();
     1984            var index = urlPath.lastIndexOf("!/");
     1985            final var jarFile = Paths.get(urlPath.substring("file:/".length(), index));
     1986            var filename = jarFile.getFileName();
     1987            var jarTime = Files.readAttributes(jarFile, BasicFileAttributes.class).lastModifiedTime();
    19911988            // Copy it to temp directory (hopefully free of exclamation mark) if needed (missing or older jar)
    1992             Path jarCopy = Paths.get(getSystemProperty("java.io.tmpdir")).resolve(filename);
     1989            final var jarCopy = Paths.get(getSystemProperty("java.io.tmpdir")).resolve(filename);
    19931990            if (!jarCopy.toFile().exists() ||
    19941991                    Files.readAttributes(jarCopy, BasicFileAttributes.class).lastModifiedTime().compareTo(jarTime) < 0) {
     
    20292026            Logging.trace(e);
    20302027            try {
    2031                 URL betterUrl = betterJarUrl(cl.getResource(path));
     2028                final var betterUrl = betterJarUrl(cl.getResource(path));
    20322029                if (betterUrl != null) {
    20332030                    return betterUrl.openStream();
Note: See TracChangeset for help on using the changeset viewer.