Changeset 19048 in josm for trunk/src/org
- Timestamp:
- 2024-04-19T16:21:11+02:00 (8 months ago)
- Location:
- trunk/src/org/openstreetmap/josm
- Files:
-
- 18 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/src/org/openstreetmap/josm/actions/AddImageryLayerAction.java
r18628 r19048 7 7 import java.awt.Dimension; 8 8 import java.awt.GraphicsEnvironment; 9 import java.awt.GridBagConstraints; 9 10 import java.awt.GridBagLayout; 10 11 import java.awt.event.ActionEvent; … … 14 15 import java.time.Year; 15 16 import java.time.ZoneOffset; 16 import java.util.Collection;17 17 import java.util.Collections; 18 18 import java.util.List; … … 26 26 import javax.swing.JScrollPane; 27 27 28 import org.openstreetmap.josm.data.coor.LatLon;29 import org.openstreetmap.josm.data.imagery.DefaultLayer;30 28 import org.openstreetmap.josm.data.imagery.ImageryInfo; 31 29 import org.openstreetmap.josm.data.imagery.ImageryInfo.ImageryType; … … 62 60 SelectWmsLayersDialog(WMSLayerTree tree, JComboBox<String> formats) { 63 61 super(MainApplication.getMainFrame(), tr("Select WMS layers"), tr("Add layers"), tr("Cancel")); 64 final JScrollPanescrollPane = new JScrollPane(tree.getLayerTree());62 final var scrollPane = new JScrollPane(tree.getLayerTree()); 65 63 scrollPane.setPreferredSize(new Dimension(400, 400)); 66 final JPanelpanel = new JPanel(new GridBagLayout());64 final var panel = new JPanel(new GridBagLayout()); 67 65 panel.add(scrollPane, GBC.eol().fill()); 68 panel.add(formats, GBC.eol().fill(G BC.HORIZONTAL));66 panel.add(formats, GBC.eol().fill(GridBagConstraints.HORIZONTAL)); 69 67 setContent(panel); 70 68 } … … 84 82 85 83 // change toolbar icon from if specified 86 Stringicon = info.getIcon();84 var icon = info.getIcon(); 87 85 if (icon != null) { 88 86 new ImageProvider(icon).setOptional(true).getResourceAsync(result -> { … … 103 101 try { 104 102 if (info.getUrl() != null && info.getUrl().contains("{time}")) { 105 final Stringinstant = Year.now(ZoneOffset.UTC).atDay(1).atStartOfDay(ZoneOffset.UTC).toInstant().toString();106 final Stringexample = String.join("/", instant, instant);107 final StringinitialSelectionValue = info.getDate() != null ? info.getDate() : example;108 final StringuserDate = 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(), 109 107 tr("Time filter for \"{0}\" such as \"{1}\"", info.getName(), example), 110 108 initialSelectionValue); … … 115 113 // TODO persist new {time} value (via ImageryLayerInfo.save?) 116 114 } 117 switch (info.getImageryType()) {115 switch (info.getImageryType()) { 118 116 case WMS_ENDPOINT: 119 117 // convert to WMS type … … 126 124 // specify which layer to use 127 125 if (Utils.isEmpty(info.getDefaultLayers())) { 128 WMTSTileSourcetileSource = new WMTSTileSource(info);129 DefaultLayer layerId = tileSource.userSelectLayer();126 var tileSource = new WMTSTileSource(info); 127 var layerId = tileSource.userSelectLayer(); 130 128 if (layerId != null) { 131 ImageryInfocopy = new ImageryInfo(info);129 var copy = new ImageryInfo(info); 132 130 copy.setDefaultLayers(Collections.singletonList(layerId)); 133 StringlayerName = tileSource.getLayers().stream()131 var layerName = tileSource.getLayers().stream() 134 132 .filter(x -> x.getIdentifier().equals(layerId.getLayerName())) 135 133 .map(Layer::getUserTitle) … … 165 163 ImageryLayer layer = null; 166 164 try { 167 final ImageryInfoinfoToAdd = convertImagery(info);165 final var infoToAdd = convertImagery(info); 168 166 if (infoToAdd != null) { 169 167 layer = ImageryLayer.create(infoToAdd); … … 207 205 208 206 private static LayerSelection askToSelectLayers(WMSImagery wms) { 209 final WMSLayerTreetree = 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])); 213 211 formats.setSelectedItem(wms.getPreferredFormat()); 214 212 formats.setToolTipText(tr("Select image format for WMS layer")); 215 213 216 JCheckBoxcheckBounds = new JCheckBox(tr("Show only layers for current view"), true);214 var checkBounds = new JCheckBox(tr("Show only layers for current view"), true); 217 215 Runnable updateTree = () -> { 218 LatLonlatLon = checkBounds.isSelected() && MainApplication.isDisplayingMapView()216 var latLon = checkBounds.isSelected() && MainApplication.isDisplayingMapView() 219 217 ? MainApplication.getMap().mapView.getProjection().eastNorth2latlon(MainApplication.getMap().mapView.getCenter()) 220 218 : null; … … 227 225 228 226 if (!GraphicsEnvironment.isHeadless()) { 229 ExtendedDialogdialog = new ExtendedDialog(MainApplication.getMainFrame(),227 var dialog = new ExtendedDialog(MainApplication.getMainFrame(), 230 228 tr("Select WMS layers"), tr("Add layers"), tr("Cancel")); 231 final JScrollPanescrollPane = new JScrollPane(tree.getLayerTree());229 final var scrollPane = new JScrollPane(tree.getLayerTree()); 232 230 scrollPane.setPreferredSize(new Dimension(400, 400)); 233 final JPanelpanel = new JPanel(new GridBagLayout());231 final var panel = new JPanel(new GridBagLayout()); 234 232 panel.add(scrollPane, GBC.eol().fill()); 235 panel.add(checkBounds, GBC.eol().fill(G BC.HORIZONTAL));236 panel.add(formats, GBC.eol().fill(G BC.HORIZONTAL));233 panel.add(checkBounds, GBC.eol().fill(GridBagConstraints.HORIZONTAL)); 234 panel.add(formats, GBC.eol().fill(GridBagConstraints.HORIZONTAL)); 237 235 dialog.setContent(panel); 238 236 … … 283 281 CheckParameterUtil.ensureThat(ImageryType.WMS_ENDPOINT == info.getImageryType(), "wms_endpoint imagery type expected"); 284 282 // We need to get the URL with {apikey} replaced. See #22642. 285 final TemplatedWMSTileSourcetileSource = new TemplatedWMSTileSource(info, ProjectionRegistry.getProjection());286 final WMSImagerywms = new WMSImagery(tileSource.getBaseUrl(), info.getCustomHttpHeaders());287 LayerSelectionselection = 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); 288 286 if (selection == null) { 289 287 return null; 290 288 } 291 289 292 final Stringurl = wms.buildGetMapUrl(290 final var url = wms.buildGetMapUrl( 293 291 selection.layers.stream().map(LayerDetails::getName).collect(Collectors.toList()), 294 292 (List<String>) null, … … 297 295 ); 298 296 299 StringselectedLayers = selection.layers.stream()297 var selectedLayers = selection.layers.stream() 300 298 .map(LayerDetails::getName) 301 299 .collect(Collectors.joining(", ")); 302 300 // Use full copy of original Imagery info to copy all attributes. Only overwrite what's different 303 ImageryInforet = new ImageryInfo(info);301 var ret = new ImageryInfo(info); 304 302 ret.setUrl(url); 305 303 ret.setImageryType(ImageryType.WMS); -
trunk/src/org/openstreetmap/josm/actions/AutoScaleAction.java
r18211 r19048 8 8 import java.awt.event.ActionEvent; 9 9 import java.awt.event.KeyEvent; 10 import java.awt.geom.Area;11 10 import java.util.ArrayList; 12 11 import java.util.Collection; … … 23 22 import org.openstreetmap.josm.data.DataSource; 24 23 import org.openstreetmap.josm.data.conflict.Conflict; 25 import org.openstreetmap.josm.data.osm.DataSet;26 24 import org.openstreetmap.josm.data.osm.IPrimitive; 27 25 import org.openstreetmap.josm.data.osm.OsmData; … … 34 32 import org.openstreetmap.josm.gui.MapView; 35 33 import org.openstreetmap.josm.gui.NavigatableComponent.ZoomChangeListener; 36 import org.openstreetmap.josm.gui.dialogs.ConflictDialog;37 34 import org.openstreetmap.josm.gui.dialogs.LayerListDialog; 38 35 import org.openstreetmap.josm.gui.dialogs.ValidatorDialog.ValidatorBoundingXYVisitor; … … 146 143 */ 147 144 public static void zoomTo(Collection<? extends IPrimitive> sel) { 148 BoundingXYVisitor bboxCalculator = new BoundingXYVisitor();145 final var bboxCalculator = new BoundingXYVisitor(); 149 146 bboxCalculator.computeBoundingBox(sel); 150 147 if (bboxCalculator.getBounds() != null) { … … 244 241 public void autoScale() { 245 242 if (MainApplication.isDisplayingMapView()) { 246 MapViewmapView = MainApplication.getMap().mapView;243 final var mapView = MainApplication.getMap().mapView; 247 244 switch (mode) { 248 245 case PREVIOUS: … … 312 309 private void modeLayer(BoundingXYVisitor v) { 313 310 // try to zoom to the first selected layer 314 Layer l = getFirstSelectedLayer();311 final var l = getFirstSelectedLayer(); 315 312 if (l == null) 316 313 return; … … 327 324 } 328 325 } else { 329 ConflictDialogconflictDialog = MainApplication.getMap().conflictDialog;326 final var conflictDialog = MainApplication.getMap().conflictDialog; 330 327 Conflict<? extends IPrimitive> c = conflictDialog.getSelectedConflict(); 331 328 if (c != null) { … … 359 356 } 360 357 Bounds bbox = null; 361 final DataSetdataset = getLayerManager().getActiveDataSet();358 final var dataset = getLayerManager().getActiveDataSet(); 362 359 if (dataset != null) { 363 360 List<DataSource> dataSources = new ArrayList<>(dataset.getDataSources()); … … 372 369 } else { 373 370 lastZoomArea = -1; 374 AreasourceArea = getLayerManager().getActiveDataSet().getDataSourceArea();371 final var sourceArea = getLayerManager().getActiveDataSet().getDataSourceArea(); 375 372 if (sourceArea != null) { 376 373 bbox = new Bounds(sourceArea.getBounds2D()); … … 439 436 * Adapter for zoom change events 440 437 */ 441 private class ZoomChangeAdapter implements ZoomChangeListener {438 private final class ZoomChangeAdapter implements ZoomChangeListener { 442 439 @Override 443 440 public void zoomChanged() { -
trunk/src/org/openstreetmap/josm/actions/ChangesetManagerToggleAction.java
r17188 r19048 49 49 } 50 50 51 private class ChangesetCacheManagerClosedHandler extends WindowAdapter {51 private final class ChangesetCacheManagerClosedHandler extends WindowAdapter { 52 52 @Override 53 53 public void windowClosed(WindowEvent e) { -
trunk/src/org/openstreetmap/josm/actions/DownloadOsmInViewAction.java
r17052 r19048 37 37 @Override 38 38 public void actionPerformed(ActionEvent e) { 39 final Boundsbounds = MainApplication.getMap().mapView.getRealBounds();40 DownloadOsmInViewTasktask = new DownloadOsmInViewTask();39 final var bounds = MainApplication.getMap().mapView.getRealBounds(); 40 final var task = new DownloadOsmInViewTask(); 41 41 task.setZoomAfterDownload(false); 42 42 Future<?> future = task.download(bounds); -
trunk/src/org/openstreetmap/josm/actions/JoinAreasAction.java
r18972 r19048 210 210 211 211 public List<Node> getNodes() { 212 List<Node> nodes = new ArrayList<>();212 final var nodes = new ArrayList<Node>(); 213 213 for (WayInPolygon way : this.ways) { 214 214 //do not add the last node as it will be repeated in the next way 215 215 if (way.insideToTheRight) { 216 for ( intpos = 0; pos < way.way.getNodesCount() - 1; pos++) {216 for (var pos = 0; pos < way.way.getNodesCount() - 1; pos++) { 217 217 nodes.add(way.way.getNode(pos)); 218 218 } … … 343 343 */ 344 344 private static double getAngle(Node n1, Node n2, Node n3) { 345 EastNorthen1 = n1.getEastNorth();346 EastNorthen2 = n2.getEastNorth();347 EastNorthen3 = n3.getEastNorth();345 final var en1 = n1.getEastNorth(); 346 final var en2 = n2.getEastNorth(); 347 final var en3 = n3.getEastNorth(); 348 348 double angle = Math.atan2(en3.getY() - en1.getY(), en3.getX() - en1.getX()) - 349 349 Math.atan2(en2.getY() - en1.getY(), en2.getX() - en1.getX()); … … 362 362 */ 363 363 public WayInPolygon walk() { 364 NodeheadNode = getHeadNode();365 NodeprevNode = getPrevNode();364 final var headNode = getHeadNode(); 365 final var prevNode = getPrevNode(); 366 366 367 367 double headAngle = Math.atan2(headNode.getEastNorth().east() - prevNode.getEastNorth().east(), … … 371 371 //find best next way 372 372 WayInPolygon bestWay = null; 373 booleanbestWayReverse = false;373 var bestWayReverse = false; 374 374 375 375 for (WayInPolygon way : availableWays) { … … 418 418 */ 419 419 public WayInPolygon leftComingWay() { 420 NodeheadNode = getHeadNode();421 NodeprevNode = getPrevNode();420 final var headNode = getHeadNode(); 421 final var prevNode = getPrevNode(); 422 422 423 423 WayInPolygon mostLeft = null; // most left way connected to head node 424 booleancomingToHead = false; // true if candidate come to head node424 var comingToHead = false; // true if candidate come to head node 425 425 double angle = 2*Math.PI; 426 426 … … 649 649 } 650 650 651 booleanhasChanges = 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>(); 656 656 657 657 for (Multipolygon area : areas) { … … 721 721 if (discardedWays.stream().anyMatch(w -> !w.isNew())) { 722 722 for (AssembledPolygon ring : boundaries) { 723 for ( intk = 0; k < ring.ways.size(); k++) {723 for (var k = 0; k < ring.ways.size(); k++) { 724 724 WayInPolygon ringWay = ring.ways.get(k); 725 725 Way older = keepOlder(ringWay.way, oldestWayMap, discardedWays); 726 726 727 727 if (ringWay.way != older) { 728 WayInPolygonrepl = new WayInPolygon(older, ringWay.insideToTheRight);728 final var repl = new WayInPolygon(older, ringWay.insideToTheRight); 729 729 ring.ways.set(k, repl); 730 730 } … … 769 769 // Delete the discarded inner ways 770 770 if (!discardedWays.isEmpty()) { 771 CommanddeleteCmd = DeleteCommand.delete(discardedWays, true);771 final var deleteCmd = DeleteCommand.delete(discardedWays, true); 772 772 if (deleteCmd != null) { 773 773 cmds.add(deleteCmd); … … 796 796 private Way keepOlder(Way way, Map<Node, Way> oldestWayMap, List<Way> discardedWays) { 797 797 Way oldest = null; 798 for ( Noden : way.getNodes()) {799 Wayorig = oldestWayMap .get(n);798 for (var n : way.getNodes()) { 799 final var orig = oldestWayMap .get(n); 800 800 if (orig != null && (oldest == null || oldest.getUniqueId() > orig.getUniqueId()) 801 801 && discardedWays.contains(orig)) { … … 830 830 } 831 831 832 TagCollectionwayTags = TagCollection.unionOfAllPrimitives(ways);832 final var wayTags = TagCollection.unionOfAllPrimitives(ways); 833 833 try { 834 834 cmds.addAll(CombinePrimitiveResolverDialog.launchIfNecessary(wayTags, ways, ways)); … … 847 847 */ 848 848 private boolean removeDuplicateNodes(List<Way> ways) { 849 Map<Node, Node> nodeMap = new TreeMap<>(new NodePositionComparator());850 inttotalWaysModified = 0;849 final var nodeMap = new TreeMap<Node, Node>(new NodePositionComparator()); 850 var totalWaysModified = 0; 851 851 852 852 for (Way way : ways) { … … 855 855 } 856 856 857 List<Node> newNodes = new ArrayList<>();857 final var newNodes = new ArrayList<Node>(); 858 858 Node prevNode = null; 859 booleanmodifyWay = false;859 var modifyWay = false; 860 860 861 861 for (Node node : way.getNodes()) { 862 Noderepresentator = nodeMap.get(node);862 var representator = nodeMap.get(node); 863 863 if (representator == null) { 864 864 //new node … … 898 898 */ 899 899 private void commitCommands(String description) { 900 switch (cmds.size()) {900 switch (cmds.size()) { 901 901 case 0: 902 902 return; … … 923 923 cmds.clear(); 924 924 if (addUndoRedo && !executedCmds.isEmpty()) { 925 UndoRedoHandler ur = UndoRedoHandler.getInstance();925 final var ur = UndoRedoHandler.getInstance(); 926 926 if (executedCmds.size() == 1) { 927 927 ur.add(executedCmds.getFirst(), false); … … 945 945 Map<Way, Way> nextWayMap = new HashMap<>(); 946 946 947 for ( intpos = 0; pos < parts.size(); pos++) {947 for (var pos = 0; pos < parts.size(); pos++) { 948 948 949 949 if (!parts.get(pos).lastNode().equals(parts.get((pos + 1) % parts.size()).firstNode())) … … 956 956 Way topWay = null; 957 957 Node topNode = null; 958 inttopIndex = 0;958 var topIndex = 0; 959 959 double minY = Double.POSITIVE_INFINITY; 960 960 961 961 for (Way way : parts) { 962 for ( intpos = 0; pos < way.getNodesCount(); pos++) {963 Nodenode = way.getNode(pos);962 for (var pos = 0; pos < way.getNodesCount(); pos++) { 963 final var node = way.getNode(pos); 964 964 965 965 if (node.getEastNorth().getY() < minY) { … … 996 996 for (Way way : parts) { 997 997 if (way.firstNode().equals(headNode)) { 998 NodenextNode = way.getNode(1);998 final var nextNode = way.getNode(1); 999 999 1000 1000 if (topWay == null || !Geometry.isToTheRightSideOfLine(prevNode, headNode, bestWayNextNode, nextNode)) { … … 1008 1008 if (way.lastNode().equals(headNode)) { 1009 1009 //end adjacent to headNode 1010 NodenextNode = way.getNode(way.getNodesCount() - 2);1010 final var nextNode = way.getNode(way.getNodesCount() - 2); 1011 1011 1012 1012 if (topWay == null || !Geometry.isToTheRightSideOfLine(prevNode, headNode, bestWayNextNode, nextNode)) { … … 1020 1020 } else { 1021 1021 //node is inside way - pick the clockwise going end. 1022 Nodeprev = topWay.getNode(topIndex - 1);1023 Nodenext = topWay.getNode(topIndex + 1);1022 final var prev = topWay.getNode(topIndex - 1); 1023 final var next = topWay.getNode(topIndex + 1); 1024 1024 1025 1025 //there will be no parallel segments in the middle of way, so all fine. … … 1027 1027 } 1028 1028 1029 WaycurWay = topWay;1029 var curWay = topWay; 1030 1030 boolean curWayInsideToTheRight = wayClockwise ^ isInner; 1031 1031 List<WayInPolygon> result = new ArrayList<>(); … … 1035 1035 1036 1036 //add cur way 1037 WayInPolygonresultWay = new WayInPolygon(curWay, curWayInsideToTheRight);1037 final var resultWay = new WayInPolygon(curWay, curWayInsideToTheRight); 1038 1038 result.add(resultWay); 1039 1039 1040 1040 //process next way 1041 WaynextWay = nextWayMap.get(curWay);1042 NodeprevNode = curWay.getNode(curWay.getNodesCount() - 2);1043 NodeheadNode = curWay.lastNode();1044 NodenextNode = 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); 1045 1045 1046 1046 if (nextWay == topWay) { … … 1068 1068 // | 1069 1069 1070 intintersectionCount = 0;1070 var intersectionCount = 0; 1071 1071 1072 1072 for (Way wayA : parts) { … … 1078 1078 if (wayA.lastNode().equals(headNode)) { 1079 1079 1080 WaywayB = nextWayMap.get(wayA);1080 final var wayB = nextWayMap.get(wayA); 1081 1081 1082 1082 //test if wayA is opposite wayB relative to curWay and nextWay 1083 1083 1084 NodewayANode = wayA.getNode(wayA.getNodesCount() - 2);1085 NodewayBNode = wayB.getNode(1);1084 final var wayANode = wayA.getNode(wayA.getNodesCount() - 2); 1085 final var wayBNode = wayB.getNode(1); 1086 1086 1087 1087 boolean wayAToTheRight = Geometry.isToTheRightSideOfLine(prevNode, headNode, nextNode, wayANode); … … 1117 1117 */ 1118 1118 private static void revertDuplicateTwoNodeWays(List<WayInPolygon> parts) { 1119 for ( inti = 0; i < parts.size(); i++) {1119 for (var i = 0; i < parts.size(); i++) { 1120 1120 WayInPolygon w1 = parts.get(i); 1121 1121 if (w1.way.getNodesCount() != 2) … … 1141 1141 private List<Way> splitWayOnNodes(Way way, Set<Node> nodes, Map<Node, Way> oldestWayMap) { 1142 1142 1143 List<Way> result = new ArrayList<>();1143 final var result = new ArrayList<Way>(); 1144 1144 List<List<Node>> chunks = buildNodeChunks(way, nodes); 1145 1145 1146 1146 if (chunks.size() > 1) { 1147 SplitWayCommandsplit = SplitWayCommand.splitWay(way, chunks,1147 final var split = SplitWayCommand.splitWay(way, chunks, 1148 1148 Collections.emptyList(), SplitWayCommand.Strategy.keepFirstChunk()); 1149 1149 … … 1159 1159 if (!way.isNew() && result.size() > 1) { 1160 1160 for (Way part : result) { 1161 Noden = part.firstNode();1162 Wayold = oldestWayMap.get(n);1161 final var n = part.firstNode(); 1162 final var old = oldestWayMap.get(n); 1163 1163 if (old == null || old.getUniqueId() > way.getUniqueId()) { 1164 1164 oldestWayMap.put(n, way); … … 1231 1231 1232 1232 //TODO: bad performance for deep nestings... 1233 List<PolygonLevel> result = new ArrayList<>();1233 final var result = new ArrayList<PolygonLevel>(); 1234 1234 1235 1235 for (AssembledPolygon outerWay : boundaryWays) { 1236 1236 1237 booleanouterGood = true;1238 List<AssembledPolygon> innerCandidates = new ArrayList<>();1237 var outerGood = true; 1238 final var innerCandidates = new ArrayList<AssembledPolygon>(); 1239 1239 1240 1240 for (AssembledPolygon innerWay : boundaryWays) { … … 1256 1256 1257 1257 //add new outer polygon 1258 AssembledMultipolygonpol = new AssembledMultipolygon(outerWay);1259 PolygonLevelpolLev = new PolygonLevel(pol, level);1258 final var pol = new AssembledMultipolygon(outerWay); 1259 final var polLev = new PolygonLevel(pol, level); 1260 1260 1261 1261 //process inner ways … … 1288 1288 // This seems to appear when is apply over invalid way like #9911 test-case 1289 1289 // Remove all of these way to make the next work. 1290 List<WayInPolygon> cleanMultigonWays = new ArrayList<>();1290 final var cleanMultigonWays = new ArrayList<WayInPolygon>(); 1291 1291 for (WayInPolygon way: multigonWays) { 1292 1292 if (way.way.getNodesCount() != 2 || !way.way.isClosed()) 1293 1293 cleanMultigonWays.add(way); 1294 1294 } 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>(); 1297 1297 1298 1298 WayInPolygon startWay; 1299 1299 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>(); 1302 1302 path.add(startWay); 1303 1303 while (true) { … … 1318 1318 if (path.get(0) == nextWay) { 1319 1319 // path is closed -> stop here 1320 AssembledPolygonring = new AssembledPolygon(path);1320 final var ring = new AssembledPolygon(path); 1321 1321 if (ring.getNodes().size() <= 2) { 1322 1322 // Invalid ring (2 nodes) -> remove … … 1357 1357 */ 1358 1358 public static List<AssembledPolygon> fixTouchingPolygons(List<AssembledPolygon> polygons) { 1359 List<AssembledPolygon> newPolygons = new ArrayList<>();1359 final var newPolygons = new ArrayList<AssembledPolygon>(); 1360 1360 1361 1361 for (AssembledPolygon ring : polygons) { 1362 1362 ring.reverse(); 1363 WayTraverser traverser = new WayTraverser(ring.ways);1363 final var traverser = new WayTraverser(ring.ways); 1364 1364 WayInPolygon startWay; 1365 1365 1366 1366 while ((startWay = traverser.startNewWay()) != null) { 1367 List<WayInPolygon> simpleRingWays = new ArrayList<>();1367 final var simpleRingWays = new ArrayList<WayInPolygon>(); 1368 1368 simpleRingWays.add(startWay); 1369 1369 WayInPolygon nextWay; … … 1374 1374 } 1375 1375 traverser.removeWays(simpleRingWays); 1376 AssembledPolygonsimpleRing = new AssembledPolygon(simpleRingWays);1376 final var simpleRing = new AssembledPolygon(simpleRingWays); 1377 1377 simpleRing.reverse(); 1378 1378 newPolygons.add(simpleRing); … … 1411 1411 */ 1412 1412 private Multipolygon joinPolygon(AssembledMultipolygon polygon) throws UserCancelException { 1413 Multipolygonresult = new Multipolygon(joinWays(polygon.outerWay.ways));1413 final var result = new Multipolygon(joinWays(polygon.outerWay.ways)); 1414 1414 1415 1415 for (AssembledPolygon pol : polygon.innerWays) { … … 1429 1429 1430 1430 //leave original orientation, if all paths are reverse. 1431 booleanallReverse = true;1431 var allReverse = true; 1432 1432 for (WayInPolygon way : ways) { 1433 1433 allReverse &= !way.insideToTheRight; … … 1440 1440 } 1441 1441 1442 WayjoinedWay = joinOrientedWays(ways);1442 final var joinedWay = joinOrientedWays(ways); 1443 1443 1444 1444 //should not happen … … 1462 1462 // the user about this. 1463 1463 1464 List<Way> actionWays = new ArrayList<>(ways.size());1465 intoldestPos = 0;1464 final var actionWays = new ArrayList<Way>(ways.size()); 1465 var oldestPos = 0; 1466 1466 Way oldest = ways.get(0).way; 1467 1467 for (WayInPolygon way : ways) { … … 1511 1511 } 1512 1512 1513 booleanhasKnownOuter = false;1513 var hasKnownOuter = false; 1514 1514 outerWays.clear(); 1515 1515 innerWays.clear(); … … 1538 1538 } 1539 1539 1540 WayouterWay = outerWays.get(0);1540 final var outerWay = outerWays.get(0); 1541 1541 1542 1542 //retain only selected inner ways … … 1588 1588 processedInnerWays.addAll(innerWays); 1589 1589 1590 Multipolygonpol = new Multipolygon(outerWay);1590 final var pol = new Multipolygon(outerWay); 1591 1591 pol.innerWays.addAll(innerWays); 1592 1592 … … 1615 1615 OsmDataLayer layer = getLayerManager().getEditLayer(); 1616 1616 // Create new multipolygon relation and add all inner ways to it 1617 RelationnewRel = new Relation();1617 final var newRel = new Relation(); 1618 1618 newRel.put("type", "multipolygon"); 1619 1619 for (Way w : inner) { … … 1650 1650 1651 1651 cmds.add(new ChangeMembersCommand(r, members)); 1652 RelationRolesaverel = new RelationRole(r, rm.getRole());1652 final var saverel = new RelationRole(r, rm.getRole()); 1653 1653 if (!result.contains(saverel)) { 1654 1654 result.add(saverel); … … 1701 1701 default: 1702 1702 // Create a new relation with all previous members and (Way)outer as outer. 1703 RelationnewRel = new Relation();1703 final var newRel = new Relation(); 1704 1704 for (RelationRole r : multiouters) { 1705 1705 // Add members -
trunk/src/org/openstreetmap/josm/actions/SplitWayAction.java
r18759 r19048 7 7 8 8 import java.awt.Component; 9 import java.awt.GridBagConstraints; 9 10 import java.awt.GridBagLayout; 10 11 import java.awt.event.ActionEvent; … … 146 147 147 148 // Finally, applicableWays contains only one perfect way 148 final WayselectedWay = 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()); 150 151 sel.addAll(selectedWays); 151 152 doSplitWayShowSegmentSelection(selectedWay, selectedNodes, sel); … … 164 165 if (wayChunks != null) { 165 166 final List<Way> newWays = SplitWayCommand.createNewWaysFromChunks(splitWay, wayChunks); 166 final WaywayToKeep = SplitWayCommand.Strategy.keepLongestChunk().determineWayToKeep(newWays);167 final var wayToKeep = SplitWayCommand.Strategy.keepLongestChunk().determineWayToKeep(newWays); 167 168 168 169 if (ExpertToggleAction.isExpert() && !splitWay.isNew()) { … … 210 211 211 212 setButtonIcons("ok", "cancel"); 212 final JPanelpane = new JPanel(new GridBagLayout());213 pane.add(new JLabel(getTitle()), GBC.eol().fill(G BC.HORIZONTAL));214 pane.add(list, GBC.eop().fill(G BC.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)); 215 216 setContent(pane); 216 217 setDefaultCloseOperation(HIDE_ON_CLOSE); … … 224 225 final Collection<WaySegment> segments = new ArrayList<>(selected.getNodesCount() - 1); 225 226 final Iterator<Node> it = selected.getNodes().iterator(); 226 NodepreviousNode = it.next();227 var previousNode = it.next(); 227 228 while (it.hasNext()) { 228 final Nodenode = it.next();229 final var node = it.next(); 229 230 segments.add(WaySegment.forNodePair(selectedWay, previousNode, node)); 230 231 previousNode = node; … … 237 238 238 239 protected void setHighlightedWaySegments(Collection<WaySegment> segments) { 239 DataSetds = selectedWay.getDataSet();240 final var ds = selectedWay.getDataSet(); 240 241 if (ds != null) { 241 242 ds.setHighlightedWaySegments(segments); … … 247 248 public void setVisible(boolean visible) { 248 249 super.setVisible(visible); 249 DataSetds = selectedWay.getDataSet();250 final var ds = selectedWay.getDataSet(); 250 251 if (visible) { 251 252 DISPLAY_COUNT.incrementAndGet(); … … 276 277 } 277 278 278 private class SplitWayDataSetListener implements DataSetListener {279 private final class SplitWayDataSetListener implements DataSetListener { 279 280 280 281 @Override … … 336 337 @Override 337 338 public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { 338 final Componentc = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);339 final var c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); 339 340 final String name = DefaultNameFormatter.getInstance().format((Way) value); 340 341 // get rid of id from DefaultNameFormatter.decorateNameWithId() … … 359 360 // Special case - one of the selected ways touches (not cross) way that we want to split 360 361 if (selectedNodes.size() == 1) { 361 Noden = selectedNodes.get(0);362 final var n = selectedNodes.get(0); 362 363 List<Way> referredWays = n.getParentWays(); 363 364 Way inTheMiddle = null; -
trunk/src/org/openstreetmap/josm/data/osm/search/SearchCompiler.java
r18877 r19048 23 23 import java.util.function.Predicate; 24 24 import java.util.function.Supplier; 25 import java.util.regex.Matcher;26 25 import java.util.regex.Pattern; 27 26 import java.util.regex.PatternSyntaxException; … … 160 159 @Override 161 160 public Match get(String keyword, boolean caseSensitive, boolean regexSearch, PushbackTokenizer tokenizer) throws SearchParseError { 162 switch (keyword) {161 switch (keyword) { 163 162 case MODIFIED: 164 163 return new Modified(); … … 1140 1139 value = Normalizer.normalize(value, Normalizer.Form.NFC); 1141 1140 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); 1144 1143 1145 1144 boolean keyMatchFound = keyMatcher.find(); … … 1623 1622 * Matches objects that are new (i.e. have not been uploaded to the server) 1624 1623 */ 1625 private static class New extends Match {1624 private static final class New extends Match { 1626 1625 @Override 1627 1626 public boolean match(OsmPrimitive osm) { … … 1638 1637 * Matches all objects that have been modified, created, or undeleted 1639 1638 */ 1640 private static class Modified extends Match {1639 private static final class Modified extends Match { 1641 1640 @Override 1642 1641 public boolean match(OsmPrimitive osm) { … … 1653 1652 * Matches all objects that have been deleted 1654 1653 */ 1655 private static class Deleted extends Match {1654 private static final class Deleted extends Match { 1656 1655 @Override 1657 1656 public boolean match(OsmPrimitive osm) { … … 1668 1667 * Matches all objects currently selected 1669 1668 */ 1670 private static class Selected extends Match {1669 private static final class Selected extends Match { 1671 1670 @Override 1672 1671 public boolean match(OsmPrimitive osm) { … … 1685 1684 * fetched from the server. 1686 1685 */ 1687 private static class Incomplete extends Match {1686 private static final class Incomplete extends Match { 1688 1687 @Override 1689 1688 public boolean match(OsmPrimitive osm) { … … 1702 1701 * org.openstreetmap.josm.data.osm.OsmPrimitive.getUninterestingKeys() 1703 1702 */ 1704 private static class Untagged extends Match {1703 private static final class Untagged extends Match { 1705 1704 @Override 1706 1705 public boolean match(OsmPrimitive osm) { … … 1717 1716 * Matches ways which are closed (i.e. first and last node are the same) 1718 1717 */ 1719 private static class Closed extends Match {1718 private static final class Closed extends Match { 1720 1719 @Override 1721 1720 public boolean match(OsmPrimitive osm) { … … 1818 1817 if (!(osm instanceof Way)) 1819 1818 return null; 1820 Wayway = (Way) osm;1819 final var way = (Way) osm; 1821 1820 return (long) way.getLength(); 1822 1821 } … … 1971 1970 1972 1971 try { 1973 StringgroupSuffix = name.substring(0, name.length() - 2); // try to remove '/*'1972 final var groupSuffix = name.substring(0, name.length() - 2); // try to remove '/*' 1974 1973 TaggingPresetMenu group = preset.group; 1975 1974 … … 2179 2178 } else if (tokenizer.readIfEqual(Token.COLON)) { 2180 2179 // see if we have a Match that takes a data parameter 2181 SimpleMatchFactoryfactory = simpleMatchFactoryMap.get(key);2180 final var factory = simpleMatchFactoryMap.get(key); 2182 2181 if (factory != null) 2183 2182 return factory.get(key, caseSensitive, regexSearch, tokenizer); 2184 2183 2185 UnaryMatchFactoryunaryFactory = unaryMatchFactoryMap.get(key);2184 final var unaryFactory = unaryMatchFactoryMap.get(key); 2186 2185 if (unaryFactory != null) 2187 2186 return getValidate(unaryFactory, key, tokenizer); … … 2196 2195 return new BooleanMatch(key, false); 2197 2196 else { 2198 SimpleMatchFactoryfactory = simpleMatchFactoryMap.get(key);2197 final var factory = simpleMatchFactoryMap.get(key); 2199 2198 if (factory != null) 2200 2199 return factory.get(key, caseSensitive, regexSearch, null).validate(); 2201 2200 2202 UnaryMatchFactoryunaryFactory = unaryMatchFactoryMap.get(key);2201 final var unaryFactory = unaryMatchFactoryMap.get(key); 2203 2202 if (unaryFactory != null) 2204 2203 return getValidate(unaryFactory, key, null); … … 2222 2221 2223 2222 private static int regexFlags(boolean caseSensitive) { 2224 intsearchFlags = 0;2223 var searchFlags = 0; 2225 2224 2226 2225 // Enables canonical Unicode equivalence so that e.g. the two -
trunk/src/org/openstreetmap/josm/data/validation/ValidatorCLI.java
r18950 r19048 11 11 import java.nio.charset.StandardCharsets; 12 12 import java.nio.file.Files; 13 import java.nio.file.Path;14 13 import java.nio.file.Paths; 15 14 import java.util.ArrayList; … … 27 26 import java.util.stream.Collectors; 28 27 29 import org.apache.commons. compress.utils.FileNameUtils;28 import org.apache.commons.io.FilenameUtils; 30 29 import org.openstreetmap.josm.actions.ExtensionFileFilter; 31 30 import org.openstreetmap.josm.cli.CLIModule; 32 31 import org.openstreetmap.josm.data.Preferences; 33 import org.openstreetmap.josm.data.osm.DataSet;34 32 import org.openstreetmap.josm.data.preferences.JosmBaseDirectories; 35 33 import org.openstreetmap.josm.data.preferences.JosmUrls; … … 176 174 } 177 175 this.initialize(); 178 final ProgressMonitor fileMonitor = progressMonitorFactory.get();176 final var fileMonitor = progressMonitorFactory.get(); 179 177 fileMonitor.beginTask(tr("Processing files..."), this.input.size()); 180 178 for (String inputFile : this.input) { … … 202 200 */ 203 201 private static void processMapcssFile(final String inputFile) throws ParseException { 204 final MapCSSStyleSourcestyleSource = new MapCSSStyleSource(new File(inputFile).toURI().getPath(), inputFile, inputFile);202 final var styleSource = new MapCSSStyleSource(new File(inputFile).toURI().getPath(), inputFile, inputFile); 205 203 styleSource.loadStyleSource(); 206 204 if (!styleSource.getErrors().isEmpty()) { … … 221 219 // Check asserts 222 220 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>(); 225 223 final MapCSSTagChecker.ParseResult result = mapCSSTagChecker.addMapCSS(new File(inputFile).toURI().getPath(), 226 224 assertionErrors::add); … … 247 245 */ 248 246 private void processFile(final String inputFile) throws IllegalDataException, IOException { 249 final FileinputFileFile = new File(inputFile);247 final var inputFileFile = new File(inputFile); 250 248 final List<FileImporter> inputFileImporters = ExtensionFileFilter.getImporters().stream() 251 249 .filter(importer -> importer.acceptFile(inputFileFile)).collect(Collectors.toList()); 252 final Stopwatchstopwatch = Stopwatch.createStarted();250 final var stopwatch = Stopwatch.createStarted(); 253 251 if (inputFileImporters.stream().noneMatch(fileImporter -> 254 252 fileImporter.importDataHandleExceptions(inputFileFile, progressMonitorFactory.get()))) { … … 263 261 .stream().filter(layer -> inputFileFile.equals(layer.getAssociatedFile())) 264 262 .findFirst().orElseThrow(() -> new JosmRuntimeException(tr("Could not find a layer for {0}", inputFile))); 265 final DataSetdataSet = dataLayer.getDataSet();263 final var dataSet = dataLayer.getDataSet(); 266 264 if (this.changeFiles.containsKey(inputFile)) { 267 ProgressMonitor changeFilesMonitor = progressMonitorFactory.get();265 final var changeFilesMonitor = progressMonitorFactory.get(); 268 266 for (String changeFile : this.changeFiles.getOrDefault(inputFile, Collections.emptyList())) { 269 try ( InputStreamchangeStream = Compression.getUncompressedFileInputStream(Paths.get(changeFile))) {267 try (var changeStream = Compression.getUncompressedFileInputStream(Paths.get(changeFile))) { 270 268 dataSet.mergeFrom(OsmChangeReader.parseDataSet(changeStream, changeFilesMonitor)); 271 269 } 272 270 } 273 271 } 274 Pathpath = Paths.get(outputFile);272 final var path = Paths.get(outputFile); 275 273 if (path.toFile().isFile() && !Files.deleteIfExists(path)) { 276 274 Logging.error("Could not delete {0}, attempting to append", outputFile); 277 275 } 278 GeoJSONMapRouletteWriter geoJSONMapRouletteWriter = new GeoJSONMapRouletteWriter(dataSet);276 final var geoJSONMapRouletteWriter = new GeoJSONMapRouletteWriter(dataSet); 279 277 OsmValidator.initializeTests(); 280 278 281 try ( OutputStreamfileOutputStream = Files.newOutputStream(path)) {279 try (var fileOutputStream = Files.newOutputStream(path)) { 282 280 // The first writeErrors catches anything that was written, for whatever reason. This is probably never 283 281 // going to be called. 284 ValidationTaskvalidationTask = new ValidationTask(errors -> writeErrors(geoJSONMapRouletteWriter, fileOutputStream, errors),282 final var validationTask = new ValidationTask(errors -> writeErrors(geoJSONMapRouletteWriter, fileOutputStream, errors), 285 283 progressMonitorFactory.get(), OsmValidator.getEnabledTests(false), 286 284 dataSet.allPrimitives(), Collections.emptyList(), false); … … 320 318 */ 321 319 private static String getDefaultOutputName(final String inputString) { 322 final String extension = File NameUtils.getExtension(inputString);320 final String extension = FilenameUtils.getExtension(inputString); 323 321 if (!Arrays.asList("zip", "bz", "xz", "geojson").contains(extension)) { 324 return File NameUtils.getBaseName(inputString) + ".geojson";322 return FilenameUtils.getBaseName(inputString) + ".geojson"; 325 323 } else if ("geojson".equals(extension)) { 326 324 // Account for geojson input files 327 return File NameUtils.getBaseName(inputString) + ".validated.geojson";328 } 329 return File NameUtils.getBaseName(FileNameUtils.getBaseName(inputString)) + ".geojson";325 return FilenameUtils.getBaseName(inputString) + ".validated.geojson"; 326 } 327 return FilenameUtils.getBaseName(FilenameUtils.getBaseName(inputString)) + ".geojson"; 330 328 } 331 329 … … 348 346 /** 349 347 * Initialize everything that might be needed 350 * 348 * <p> 351 349 * Arguments may need to be parsed first. 352 350 */ … … 369 367 Logging.setLogLevel(Level.INFO); 370 368 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); 373 371 for (Option o : Option.values()) { 374 372 if (o.requiresArgument()) { … … 425 423 break; 426 424 case LOAD_PREFERENCES: 427 final PreferencestempPreferences = new Preferences();425 final var tempPreferences = new Preferences(); 428 426 tempPreferences.enableSaveOnPut(false); 429 CustomConfigurator.XMLCommandProcessor config = new CustomConfigurator.XMLCommandProcessor(tempPreferences);427 final var config = new CustomConfigurator.XMLCommandProcessor(tempPreferences); 430 428 try (InputStream is = Utils.openStream(new File(argument).toURI().toURL())) { 431 429 config.openAndReadXML(is); … … 435 433 final IPreferences pref = Config.getPref(); 436 434 if (pref instanceof MemoryPreferences) { 437 final MemoryPreferencesmemoryPreferences = (MemoryPreferences) pref;435 final var memoryPreferences = (MemoryPreferences) pref; 438 436 tempPreferences.getAllSettings().forEach(memoryPreferences::putSetting); 439 437 } else { … … 454 452 455 453 private static String getHelp() { 456 final StringhelpPadding = "\t ";454 final var helpPadding = "\t "; 457 455 // CHECKSTYLE.OFF: SingleSpaceSeparator 458 456 return tr("JOSM Validation command line interface") + "\n\n" + -
trunk/src/org/openstreetmap/josm/gui/dialogs/relation/sort/RelationSorter.java
r17867 r19048 48 48 * {@code type=associatedStreet} and {@code type=street} relations. 49 49 */ 50 private static class AssociatedStreetRoleStreetSorter implements AdditionalSorter {50 private static final class AssociatedStreetRoleStreetSorter implements AdditionalSorter { 51 51 52 52 @Override … … 65 65 * {@code type=associatedStreet} and {@code type=street} relations. 66 66 */ 67 private static class AssociatedStreetRoleAddressHouseSorter implements AdditionalSorter {67 private static final class AssociatedStreetRoleAddressHouseSorter implements AdditionalSorter { 68 68 69 69 @Override … … 93 93 * {@code type=public_transport} relations. 94 94 */ 95 private static class PublicTransportRoleStopPlatformSorter implements AdditionalSorter {95 private static final class PublicTransportRoleStopPlatformSorter implements AdditionalSorter { 96 96 97 97 @Override … … 140 140 * {@code type=restriction} relations. 141 141 */ 142 private static class FromViaToSorter implements AdditionalSorter {142 private static final class FromViaToSorter implements AdditionalSorter { 143 143 144 144 private static final List<String> ROLES = Arrays.asList("from", "via", "to"); … … 173 173 // Dispatch members to the first adequate sorter 174 174 for (RelationMember m : relationMembers) { 175 booleanwasAdded = false;175 var wasAdded = false; 176 176 for (AdditionalSorter sorter : ADDITIONAL_SORTERS) { 177 177 if (sorter.acceptsMember(relationMembers, m)) { -
trunk/src/org/openstreetmap/josm/gui/io/UploadPrimitivesTask.java
r18283 r19048 141 141 ht("/Action/Upload#ChangesetFull") 142 142 ); 143 switch (ret) {143 switch (ret) { 144 144 case 0: return MaxChangesetSizeExceededPolicy.AUTOMATICALLY_OPEN_NEW_CHANGESETS; 145 145 case 1: return MaxChangesetSizeExceededPolicy.FILL_ONE_CHANGESET_AND_RETURN_TO_UPLOAD_DIALOG; … … 168 168 strategy.setPolicy(promptUserForPolicy()); 169 169 } 170 switch (strategy.getPolicy()) {170 switch (strategy.getPolicy()) { 171 171 case AUTOMATICALLY_OPEN_NEW_CHANGESETS: 172 ChangesetnewChangeSet = new Changeset();172 final var newChangeSet = new Changeset(); 173 173 newChangeSet.setKeys(changeset.getKeys()); 174 174 closeChangeset(); … … 280 280 processedPrimitives.addAll(writer.getProcessedPrimitives()); // OsmPrimitive in => OsmPrimitive out 281 281 } 282 switch (e.getSource()) {282 switch (e.getSource()) { 283 283 case UPLOAD_DATA: 284 284 // Most likely the changeset is full. Try to recover and continue … … 319 319 } 320 320 } finally { 321 if ( MessageNotifier.PROP_NOTIFIER_ENABLED.get()) {321 if (Boolean.TRUE.equals(MessageNotifier.PROP_NOTIFIER_ENABLED.get())) { 322 322 MessageNotifier.start(); 323 323 } … … 372 372 if (uploadCanceled) return; 373 373 if (lastException == null) { 374 HtmlPanelpanel = new HtmlPanel(374 final var panel = new HtmlPanel( 375 375 "<h3><a href=\"" + Config.getUrls().getBaseBrowseUrl() + "/changeset/" + changeset.getId() + "\">" 376 376 + tr("Upload successful!") + "</a></h3>"); … … 393 393 return; 394 394 if (e.getSource() == ChangesetClosedException.Source.UPLOAD_DATA) { 395 switch (strategy.getPolicy()) {395 switch (strategy.getPolicy()) { 396 396 case ABORT: 397 397 break; /* do nothing - we return to map editing */ -
trunk/src/org/openstreetmap/josm/gui/layer/geoimage/CorrelateGpxWithImages.java
r18221 r19048 67 67 import org.openstreetmap.josm.gui.layer.LayerManager.LayerRemoveEvent; 68 68 import org.openstreetmap.josm.gui.layer.geoimage.AdjustTimezoneAndOffsetDialog.AdjustListener; 69 import org.openstreetmap.josm.gui.layer.geoimage.SynchronizeTimeFromPhotoDialog.TimeZoneItem;70 69 import org.openstreetmap.josm.gui.layer.gpx.GpxDataHelper; 71 70 import org.openstreetmap.josm.gui.widgets.JosmComboBox; … … 173 172 // Search whether an other layer has yet defined some bounding box. 174 173 // If none, we'll zoom to the bounding box of the layer with the photos. 175 booleanboundingBoxedLayerFound = false;174 var boundingBoxedLayerFound = false; 176 175 for (Layer l: MainApplication.getLayerManager().getLayers()) { 177 176 if (l != yLayer) { 178 BoundingXYVisitor bbox = new BoundingXYVisitor();177 final var bbox = new BoundingXYVisitor(); 179 178 l.visitBoundingBox(bbox); 180 179 if (bbox.getBounds() != null) { … … 185 184 } 186 185 if (!boundingBoxedLayerFound) { 187 BoundingXYVisitor bbox = new BoundingXYVisitor();186 final var bbox = new BoundingXYVisitor(); 188 187 yLayer.visitBoundingBox(bbox); 189 188 MainApplication.getMap().mapView.zoomTo(bbox); … … 261 260 * been loaded yet. It displays a FileChooser dialog to select the GPX file to be loaded. 262 261 */ 263 private class LoadGpxDataActionListener implements ActionListener {262 private final class LoadGpxDataActionListener implements ActionListener { 264 263 265 264 @Override 266 265 public void actionPerformed(ActionEvent e) { 267 Filesel = GpxDataHelper.chooseGpxDataFile();266 final var sel = GpxDataHelper.chooseGpxDataFile(); 268 267 if (sel != null) { 269 268 try { 270 269 outerPanel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); 271 270 removeDuplicates(sel); 272 GpxDatadata = GpxDataHelper.loadGpxData(sel);271 final var data = GpxDataHelper.loadGpxData(sel); 273 272 if (data != null) { 274 GpxDataWrapper elem = new GpxDataWrapper(sel.getName(), data, sel);273 final var elem = new GpxDataWrapper(sel.getName(), data, sel); 275 274 gpxModel.addElement(elem); 276 275 gpxModel.setSelectedItem(elem); … … 284 283 } 285 284 286 private class UseSupportLayerActionListener implements ActionListener {285 private final class UseSupportLayerActionListener implements ActionListener { 287 286 288 287 @Override … … 296 295 } 297 296 298 private class AdvancedSettingsActionListener implements ActionListener {297 private final class AdvancedSettingsActionListener implements ActionListener { 299 298 300 299 @Override 301 300 public void actionPerformed(ActionEvent e) { 302 AdvancedCorrelationSettingsDialoged = new AdvancedCorrelationSettingsDialog(MainApplication.getMainFrame(), forceTags);301 final var ed = new AdvancedCorrelationSettingsDialog(MainApplication.getMainFrame(), forceTags); 303 302 if (ed.showDialog().getValue() == 1) { 304 303 forceTags = ed.isForceTaggingSelected(); // This setting is not supposed to be saved permanently … … 317 316 * @author chris 318 317 */ 319 private class SetOffsetActionListener implements ActionListener {318 private final class SetOffsetActionListener implements ActionListener { 320 319 321 320 @Override 322 321 public void actionPerformed(ActionEvent e) { 323 booleanisOk = false;322 var isOk = false; 324 323 while (!isOk) { 325 SynchronizeTimeFromPhotoDialog ed = new SynchronizeTimeFromPhotoDialog( 326 MainApplication.getMainFrame(), yLayer.getImageData().getImages()); 324 final var ed = new SynchronizeTimeFromPhotoDialog(MainApplication.getMainFrame(), yLayer.getImageData().getImages()); 327 325 int answer = ed.showDialog().getValue(); 328 326 if (answer != 1) … … 340 338 } 341 339 342 TimeZoneItemselectedTz = ed.getTimeZoneItem();340 final var selectedTz = ed.getTimeZoneItem(); 343 341 344 342 Config.getPref().put("geoimage.timezoneid", selectedTz.getID()); … … 354 352 } 355 353 356 private static class GpxLayerAddedListener implements LayerChangeListener {354 private static final class GpxLayerAddedListener implements LayerChangeListener { 357 355 @Override 358 356 public void layerAdded(LayerAddEvent e) { 359 Layer layer = e.getAddedLayer();357 final var layer = e.getAddedLayer(); 360 358 if (layer instanceof GpxDataContainer) { 361 GpxDatagpx = ((GpxDataContainer) layer).getGpxData();362 Filefile = gpx.storageFile;359 final var gpx = ((GpxDataContainer) layer).getGpxData(); 360 final var file = gpx.storageFile; 363 361 removeDuplicates(file); 364 GpxDataWrapper gdw = new GpxDataWrapper(layer.getName(), gpx, file);362 final var gdw = new GpxDataWrapper(layer.getName(), gpx, file); 365 363 layer.addPropertyChangeListener(new GpxLayerRenamedListener(gdw)); 366 364 gpxModel.addElement(gdw); … … 376 374 @Override 377 375 public void layerRemoving(LayerRemoveEvent e) { 378 Layer layer = e.getRemovedLayer();376 final var layer = e.getRemovedLayer(); 379 377 if (layer instanceof GpxDataContainer) { 380 GpxDataremovedGpxData = ((GpxDataContainer) layer).getGpxData();378 final var removedGpxData = ((GpxDataContainer) layer).getGpxData(); 381 379 for (int i = gpxModel.getSize() - 1; i >= 0; i--) { 382 380 GpxData data = gpxModel.getElementAt(i).data; … … 428 426 for (AbstractModifiableLayer cur : MainApplication.getLayerManager().getLayersOfType(AbstractModifiableLayer.class)) { 429 427 if (cur instanceof GpxDataContainer) { 430 GpxDatadata = ((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); 432 430 cur.addPropertyChangeListener(new GpxLayerRenamedListener(gdw)); 433 431 gpxModel.addElement(gdw); … … 471 469 @Override 472 470 public void actionPerformed(ActionEvent ae) { 473 NoGpxDataWrapper nogdw = new NoGpxDataWrapper();471 final var nogdw = new NoGpxDataWrapper(); 474 472 if (gpxModel == null) { 475 473 constructGpxModel(nogdw); 476 474 } 477 475 478 JPanelpanelCb = new JPanel();476 final var panelCb = new JPanel(); 479 477 480 478 panelCb.add(new JLabel(tr("GPX track: "))); … … 485 483 panelCb.add(cbGpx); 486 484 487 JButtonbuttonOpen = new JButton(tr("Open another GPX trace"));485 final var buttonOpen = new JButton(tr("Open another GPX trace")); 488 486 buttonOpen.addActionListener(new LoadGpxDataActionListener()); 489 487 panelCb.add(buttonOpen); … … 493 491 panelCb.add(buttonSupport); 494 492 495 JPanelpanelTf = new JPanel(new GridBagLayout());493 final var panelTf = new JPanel(new GridBagLayout()); 496 494 497 495 timezone = loadTimezone(); … … 505 503 tfOffset.setText(delta.formatOffset()); 506 504 507 JButtonbuttonViewGpsPhoto = 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>")); 508 506 buttonViewGpsPhoto.setIcon(ImageProvider.get("clock")); 509 507 buttonViewGpsPhoto.addActionListener(new SetOffsetActionListener()); 510 508 511 JButtonbuttonAutoGuess = new JButton(tr("Auto-Guess"));509 final var buttonAutoGuess = new JButton(tr("Auto-Guess")); 512 510 buttonAutoGuess.setToolTipText(tr("Matches first photo with first gpx point")); 513 511 buttonAutoGuess.addActionListener(new AutoGuessActionListener()); 514 512 515 JButtonbuttonAdjust = new JButton(tr("Manual adjust"));513 final var buttonAdjust = new JButton(tr("Manual adjust")); 516 514 buttonAdjust.addActionListener(new AdjustActionListener()); 517 515 518 JButtonbuttonAdvanced = new JButton(tr("Advanced settings..."));516 final var buttonAdvanced = new JButton(tr("Advanced settings...")); 519 517 buttonAdvanced.addActionListener(new AdvancedSettingsActionListener()); 520 518 521 JLabellabelPosition = new JLabel(tr("Override position for: "));519 final var labelPosition = new JLabel(tr("Override position for: ")); 522 520 523 521 int numAll = yLayer.getSortedImgList(true, true).size(); … … 537 535 cbShowThumbs.setEnabled(!yLayer.thumbsLoaded); 538 536 539 inty = 0;540 GBCgbc = GBC.eol();537 var y = 0; 538 var gbc = GBC.eol(); 541 539 gbc.gridx = 0; 542 540 gbc.gridy = y++; 543 541 panelTf.add(panelCb, gbc); 544 542 545 gbc = GBC.eol().fill(G BC.HORIZONTAL).insets(0, 0, 0, 12);543 gbc = GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(0, 0, 0, 12); 546 544 gbc.gridx = 0; 547 545 gbc.gridy = y++; … … 553 551 panelTf.add(new JLabel(tr("Timezone: ")), gbc); 554 552 555 gbc = GBC.std().fill(G BC.HORIZONTAL);553 gbc = GBC.std().fill(GridBagConstraints.HORIZONTAL); 556 554 gbc.gridx = 1; 557 555 gbc.gridy = y++; … … 564 562 panelTf.add(new JLabel(tr("Offset:")), gbc); 565 563 566 gbc = GBC.std().fill(G BC.HORIZONTAL);564 gbc = GBC.std().fill(GridBagConstraints.HORIZONTAL); 567 565 gbc.gridx = 1; 568 566 gbc.gridy = y++; … … 579 577 panelTf.add(buttonViewGpsPhoto, gbc); 580 578 581 gbc = GBC.std().fill(G BC.BOTH).insets(5, 5, 5, 5);579 gbc = GBC.std().fill(GridBagConstraints.BOTH).insets(5, 5, 5, 5); 582 580 gbc.gridx = 1; 583 581 gbc.gridy = y++; … … 591 589 panelTf.add(buttonAdjust, gbc); 592 590 593 gbc = GBC.eol().fill(G BC.HORIZONTAL).insets(0, 12, 0, 0);591 gbc = GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(0, 12, 0, 0); 594 592 gbc.gridx = 0; 595 593 gbc.gridy = y++; … … 616 614 panelTf.add(cbShowThumbs, gbc); 617 615 618 gbc = GBC.eol().fill(G BC.HORIZONTAL).insets(0, 12, 0, 0);616 gbc = GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(0, 12, 0, 0); 619 617 sepDirectionPosition = new JSeparator(SwingConstants.HORIZONTAL); 620 618 panelTf.add(sepDirectionPosition, gbc); … … 627 625 expertChanged(ExpertToggleAction.isExpert()); 628 626 629 final JPanelstatusBar = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));627 final var statusBar = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); 630 628 statusBar.setBorder(BorderFactory.createLoweredBevelBorder()); 631 629 statusBarText = new JLabel(" "); … … 633 631 statusBar.add(statusBarText); 634 632 635 RepaintTheMapListener repaintTheMap = new RepaintTheMapListener(yLayer);633 final var repaintTheMap = new RepaintTheMapListener(yLayer); 636 634 pDirectionPosition.addFocusListenerOnComponent(repaintTheMap); 637 635 tfTimezone.addFocusListener(repaintTheMap); … … 808 806 * Presents dialog with sliders for manual adjust. 809 807 */ 810 private class AdjustActionListener implements ActionListener {808 private final class AdjustActionListener implements ActionListener { 811 809 812 810 @Override 813 811 public void actionPerformed(ActionEvent e) { 814 812 815 final GpxTimeOffsetoffset = GpxTimeOffset.milliseconds(813 final var offset = GpxTimeOffset.milliseconds( 816 814 delta.getMilliseconds() + Math.round(timezone.getHours() * TimeUnit.HOURS.toMillis(1))); 817 815 final int dayOffset = offset.getDayOffset(); … … 895 893 } 896 894 897 private class AutoGuessActionListener implements ActionListener {895 private final class AutoGuessActionListener implements ActionListener { 898 896 899 897 @Override … … 943 941 } 944 942 945 private GpxDataWrapper selectedGPX(boolean complain) {943 private static GpxDataWrapper selectedGPX(boolean complain) { 946 944 Object item = gpxModel.getSelectedItem(); 947 945 … … 961 959 if (cbGpx != null) { 962 960 // Force the JCombobox to remove its eventListener from the static GpxDataWrapper 963 cbGpx.setModel(new DefaultComboBoxModel< GpxDataWrapper>());961 cbGpx.setModel(new DefaultComboBoxModel<>()); 964 962 cbGpx = null; 965 963 } -
trunk/src/org/openstreetmap/josm/gui/layer/geoimage/RemoteEntry.java
r18806 r19048 296 296 @Override 297 297 public InputStream getInputStream() throws IOException { 298 URIu = getImageURI();298 final var u = getImageURI(); 299 299 if (u.getScheme().contains("file")) { 300 300 return Files.newInputStream(Paths.get(u)); 301 301 } 302 HttpClientclient = HttpClient.create(u.toURL());302 final var client = HttpClient.create(u.toURL()); 303 303 InputStream actual = client.connect().getContent(); 304 304 return new BufferedInputStream(actual) { … … 343 343 @Override 344 344 public boolean equals(Object obj) { 345 if ( super.equals(obj)) {345 if (this == obj) { 346 346 return true; 347 347 } -
trunk/src/org/openstreetmap/josm/gui/mappaint/styleelement/LabelCompositionStrategy.java
r19045 r19048 167 167 /* Is joining an array really that complicated in Java? */ 168 168 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")); 182 180 return tags.toArray(String[]::new); 183 181 } … … 251 249 252 250 private String getPrimitiveName(IPrimitive n) { 253 StringBuilder name = new StringBuilder();251 final var name = new StringBuilder(); 254 252 if (!n.hasKeys()) return null; 255 253 nameTags.stream().map(n::get).filter(Objects::nonNull).findFirst() -
trunk/src/org/openstreetmap/josm/gui/widgets/JosmTextField.java
r18538 r19048 5 5 import java.awt.ComponentOrientation; 6 6 import java.awt.Font; 7 import java.awt.FontMetrics;8 7 import java.awt.Graphics; 9 8 import java.awt.Graphics2D; … … 19 18 20 19 import javax.swing.Icon; 20 import javax.swing.JMenuItem; 21 import javax.swing.JPopupMenu; 21 22 import javax.swing.JTextField; 22 23 import javax.swing.RepaintManager; 23 import javax.swing.JMenuItem;24 import javax.swing.JPopupMenu;25 24 import javax.swing.UIManager; 26 25 import javax.swing.text.BadLocationException; … … 30 29 import org.openstreetmap.josm.gui.MapFrame; 31 30 import org.openstreetmap.josm.tools.Destroyable; 31 import org.openstreetmap.josm.tools.Logging; 32 32 import org.openstreetmap.josm.tools.Utils; 33 33 … … 254 254 */ 255 255 public static Color getHintTextColor() { 256 Color color = UIManager.getColor("TextField[Disabled].textForeground"); // Nimbus?256 var color = UIManager.getColor("TextField[Disabled].textForeground"); // Nimbus? 257 257 if (color == null) 258 258 color = UIManager.getColor("TextField.inactiveForeground"); … … 290 290 int x; 291 291 try { 292 x = modelToView(0).x;292 x = (int) Math.round(modelToView2D(0).getX()); 293 293 } catch (BadLocationException exc) { 294 Logging.trace(exc); 294 295 return; // can't happen 295 296 } … … 304 305 g.drawString(getHint(), x, getBaseline(getWidth(), getHeight())); 305 306 } else { 306 FontMetricsmetrics = g.getFontMetrics(g.getFont());307 final var metrics = g.getFontMetrics(g.getFont()); 307 308 int dx = metrics.stringWidth(getHint()); 308 309 g.drawString(getHint(), x - dx, getBaseline(getWidth(), getHeight())); -
trunk/src/org/openstreetmap/josm/io/NoteReader.java
r17712 r19048 52 52 * Reads both API style and planet dump style formats. 53 53 */ 54 private class Parser extends DefaultHandler {54 private final class Parser extends DefaultHandler { 55 55 56 56 private NoteParseMode parseMode; … … 73 73 public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { 74 74 buffer.setLength(0); 75 switch (qName) {75 switch (qName) { 76 76 case "osm": 77 77 parseMode = NoteParseMode.API; … … 92 92 93 93 //The rest only applies for dump mode 94 switch (qName) {94 switch (qName) { 95 95 case "note": 96 96 thisNote = parseNoteFull(attrs); … … 113 113 } 114 114 if ("comment".equals(qName)) { 115 User commentUser = User.createOsmUser(commentUid, commentUsername);115 final User commentUser; 116 116 if (commentUid == 0) { 117 117 commentUser = User.getAnonymous(); 118 } else { 119 commentUser = User.createOsmUser(commentUid, commentUsername); 118 120 } 119 121 if (parseMode == NoteParseMode.API) { … … 177 179 178 180 static LatLon parseLatLon(UnaryOperator<String> attrs) { 179 doublelat = Double.parseDouble(attrs.apply("lat"));180 doublelon = Double.parseDouble(attrs.apply("lon"));181 final var lat = Double.parseDouble(attrs.apply("lat")); 182 final var lon = Double.parseDouble(attrs.apply("lon")); 181 183 return new LatLon(lat, lon); 182 184 } … … 195 197 196 198 static Note parseNoteFull(UnaryOperator<String> attrs) { 197 Notenote = parseNoteBasic(attrs);199 final var note = parseNoteBasic(attrs); 198 200 String id = attrs.apply("id"); 199 201 if (id != null) { -
trunk/src/org/openstreetmap/josm/io/OsmPbfReader.java
r19038 r19048 16 16 import java.util.Set; 17 17 18 import org.apache.commons. compress.utils.CountingInputStream;18 import org.apache.commons.io.input.BoundedInputStream; 19 19 import org.openstreetmap.josm.data.Bounds; 20 20 import org.openstreetmap.josm.data.DataSource; … … 88 88 89 89 private void parse(InputStream source) throws IllegalDataException, IOException { 90 final CountingInputStream inputStream;90 final BoundedInputStream inputStream; 91 91 if (source.markSupported()) { 92 inputStream = new CountingInputStream(source);92 inputStream = new BoundedInputStream(source); 93 93 } else { 94 inputStream = new CountingInputStream(new BufferedInputStream(source));95 } 96 try ( ProtobufParser parser = new ProtobufParser(inputStream)) {97 final ByteArrayOutputStreambaos = new ByteArrayOutputStream();94 inputStream = new BoundedInputStream(new BufferedInputStream(source)); 95 } 96 try (var parser = new ProtobufParser(inputStream)) { 97 final var baos = new ByteArrayOutputStream(); 98 98 HeaderBlock headerBlock = null; 99 99 BlobHeader blobHeader = null; … … 106 106 } 107 107 // OSM PBF is fun -- it has *nested* pbf data 108 Blobblob = parseBlob(blobHeader, inputStream, parser, baos);108 final var blob = parseBlob(blobHeader, inputStream, parser, baos); 109 109 headerBlock = parseHeaderBlock(blob, baos); 110 110 checkRequiredFeatures(headerBlock); … … 114 114 throw new IllegalStateException("A header block must occur before the first data block"); 115 115 } 116 Blobblob = parseBlob(blobHeader, inputStream, parser, baos);116 final var blob = parseBlob(blobHeader, inputStream, parser, baos); 117 117 parseDataBlock(baos, headerBlock, blob); 118 118 blobHeader = null; … … 133 133 */ 134 134 @Nonnull 135 private static BlobHeader parseBlobHeader( CountingInputStream cis, ByteArrayOutputStream baos, ProtobufParser parser)135 private static BlobHeader parseBlobHeader(BoundedInputStream cis, ByteArrayOutputStream baos, ProtobufParser parser) 136 136 throws IOException, IllegalDataException { 137 137 String type = null; 138 138 byte[] indexData = null; 139 139 int datasize = Integer.MIN_VALUE; 140 intlength = 0;141 long start = cis.get BytesRead();142 while (parser.hasNext() && (length == 0 || cis.get BytesRead() - start < length)) {143 final ProtobufRecordcurrent = 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); 144 144 switch (current.getField()) { 145 145 case 1: … … 153 153 break; 154 154 default: 155 start = cis.get BytesRead();155 start = cis.getCount(); 156 156 length += current.asUnsignedVarInt().intValue(); 157 157 if (length > MAX_BLOBHEADER_SIZE) { // There is a hard limit of 64 KiB for the BlobHeader. It *should* be less than 32 KiB. … … 181 181 */ 182 182 @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) 184 184 throws IOException { 185 long start = cis.get BytesRead();185 long start = cis.getCount(); 186 186 int size = Integer.MIN_VALUE; 187 187 Blob.CompressionType type = null; … … 189 189 // Needed since size and compression type + compression data may be in a different order 190 190 byte[] bytes = null; 191 while (parser.hasNext() && cis.get BytesRead() - start < header.dataSize()) {191 while (parser.hasNext() && cis.getCount() - start < header.dataSize()) { 192 192 current = new ProtobufRecord(baos, parser); 193 193 switch (current.getField()) { … … 239 239 @Nonnull 240 240 private static HeaderBlock parseHeaderBlock(Blob blob, ByteArrayOutputStream baos) throws IOException { 241 try ( InputStreamblobInput = blob.inputStream();242 ProtobufParser parser = new ProtobufParser(blobInput)) {241 try (var blobInput = blob.inputStream(); 242 var parser = new ProtobufParser(blobInput)) { 243 243 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>(); 246 246 String program = null; 247 247 String source = null; … … 250 250 String osmosisReplicationBaseUrl = null; 251 251 while (parser.hasNext()) { 252 final ProtobufRecordcurrent = new ProtobufRecord(baos, parser);252 final var current = new ProtobufRecord(baos, parser); 253 253 switch (current.getField()) { 254 254 case 1: // bbox … … 311 311 String[] stringTable = null; // field 1, note that stringTable[0] is a delimiter, so it is always blank and unused 312 312 // field 2 -- we cannot parse these live just in case the following fields come later 313 List<ProtobufRecord> primitiveGroups = new ArrayList<>();314 intgranularity = 100; // field 17313 final var primitiveGroups = new ArrayList<ProtobufRecord>(); 314 var granularity = 100; // field 17 315 315 long latOffset = 0; // field 19 316 316 long lonOffset = 0; // field 20 317 intdateGranularity = 1000; // field 18, default is milliseconds since the 1970 epoch318 try ( InputStreaminputStream = 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)) { 320 320 while (parser.hasNext()) { 321 ProtobufRecordprotobufRecord = new ProtobufRecord(baos, parser);321 final var protobufRecord = new ProtobufRecord(baos, parser); 322 322 switch (protobufRecord.getField()) { 323 323 case 1: … … 343 343 } 344 344 } 345 final PrimitiveBlockRecordprimitiveBlockRecord = new PrimitiveBlockRecord(stringTable, granularity, latOffset, lonOffset,345 final var primitiveBlockRecord = new PrimitiveBlockRecord(stringTable, granularity, latOffset, lonOffset, 346 346 dateGranularity); 347 final DataSetds = getDataSet();347 final var ds = getDataSet(); 348 348 if (!primitiveGroups.isEmpty() && headerBlock.bbox() != null) { 349 349 try { … … 375 375 @Nullable 376 376 private static BBox parseBBox(ByteArrayOutputStream baos, ProtobufRecord current) throws IOException { 377 try ( ByteArrayInputStreambboxInputStream = new ByteArrayInputStream(current.getBytes());378 ProtobufParser bboxParser = new ProtobufParser(bboxInputStream)) {377 try (var bboxInputStream = new ByteArrayInputStream(current.getBytes()); 378 var bboxParser = new ProtobufParser(bboxInputStream)) { 379 379 double left = Double.NaN; 380 380 double right = Double.NaN; … … 382 382 double bottom = Double.NaN; 383 383 while (bboxParser.hasNext()) { 384 ProtobufRecordprotobufRecord = new ProtobufRecord(baos, bboxParser);384 final var protobufRecord = new ProtobufRecord(baos, bboxParser); 385 385 if (protobufRecord.getType() == WireType.VARINT) { 386 386 double value = protobufRecord.asSignedVarInt().longValue() * NANO_DEGREES; … … 419 419 @Nonnull 420 420 private static String[] parseStringTable(ByteArrayOutputStream baos, byte[] bytes) throws IOException { 421 try ( ByteArrayInputStreamis = 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>(); 424 424 while (parser.hasNext()) { 425 ProtobufRecordprotobufRecord = new ProtobufRecord(baos, parser);425 final var protobufRecord = new ProtobufRecord(baos, parser); 426 426 if (protobufRecord.getField() == 1) { 427 427 list.add(protobufRecord.asString().intern()); // field is technically repeated bytes … … 444 444 private void parsePrimitiveGroup(ByteArrayOutputStream baos, byte[] bytes, PrimitiveBlockRecord primitiveBlockRecord) 445 445 throws IllegalDataException, IOException { 446 try ( ByteArrayInputStreambais = new ByteArrayInputStream(bytes);447 ProtobufParser parser = new ProtobufParser(bais)) {446 try (var bais = new ByteArrayInputStream(bytes); 447 var parser = new ProtobufParser(bais)) { 448 448 while (parser.hasNext()) { 449 ProtobufRecordprotobufRecord = new ProtobufRecord(baos, parser);449 final var protobufRecord = new ProtobufRecord(baos, parser); 450 450 switch (protobufRecord.getField()) { 451 451 case 1: // Nodes, repeated … … 480 480 private void parseNode(ByteArrayOutputStream baos, byte[] bytes, PrimitiveBlockRecord primitiveBlockRecord) 481 481 throws IllegalDataException, IOException { 482 try ( ByteArrayInputStreambais = new ByteArrayInputStream(bytes);483 ProtobufParser parser = new ProtobufParser(bais)) {482 try (var bais = new ByteArrayInputStream(bytes); 483 var parser = new ProtobufParser(bais)) { 484 484 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>(); 487 487 Info info = null; 488 488 long lat = Long.MIN_VALUE; 489 489 long lon = Long.MIN_VALUE; 490 490 while (parser.hasNext()) { 491 ProtobufRecordprotobufRecord = new ProtobufRecord(baos, parser);491 final var protobufRecord = new ProtobufRecord(baos, parser); 492 492 switch (protobufRecord.getField()) { 493 493 case 1: … … 519 519 throw new IllegalDataException("OSM PBF did not provide all the required node information"); 520 520 } 521 NodeDatanode = new NodeData(id);521 final var node = new NodeData(id); 522 522 node.setCoor(calculateLatLon(primitiveBlockRecord, lat, lon)); 523 523 addTags(node, keys, values); … … 547 547 long[] keyVals = EMPTY_LONG; // technically can be int 548 548 Info[] denseInfo = null; 549 try ( ByteArrayInputStreambais = new ByteArrayInputStream(bytes);550 ProtobufParser parser = new ProtobufParser(bais)) {549 try (var bais = new ByteArrayInputStream(bytes); 550 var parser = new ProtobufParser(bais)) { 551 551 while (parser.hasNext()) { 552 ProtobufRecordprotobufRecord = new ProtobufRecord(baos, parser);552 final var protobufRecord = new ProtobufRecord(baos, parser); 553 553 switch (protobufRecord.getField()) { 554 554 case 1: // packed node ids, DELTA encoded … … 576 576 } 577 577 578 intkeyValIndex = 0; // This index must not reset between nodes, and must always increment578 var keyValIndex = 0; // This index must not reset between nodes, and must always increment 579 579 if (ids.length == lats.length && lats.length == lons.length && (denseInfo == null || denseInfo.length == lons.length)) { 580 580 long id = 0; 581 581 long lat = 0; 582 582 long lon = 0; 583 for ( inti = 0; i < ids.length; i++) {583 for (var i = 0; i < ids.length; i++) { 584 584 final NodeData node; 585 585 id += ids[i]; 586 586 node = new NodeData(id); 587 587 if (denseInfo != null) { 588 Infoinfo = denseInfo[i];588 final var info = denseInfo[i]; 589 589 setOsmPrimitiveData(primitiveBlockRecord, node, info); 590 590 } else { … … 638 638 // We don't do live drawing, so we don't care about lats and lons (we essentially throw them away with the current parser) 639 639 // This is for the optional feature "LocationsOnWays" 640 try ( ByteArrayInputStreambais = new ByteArrayInputStream(bytes);641 ProtobufParser parser = new ProtobufParser(bais)) {640 try (var bais = new ByteArrayInputStream(bytes); 641 var parser = new ProtobufParser(bais)) { 642 642 while (parser.hasNext()) { 643 ProtobufRecordprotobufRecord = new ProtobufRecord(baos, parser);643 final var protobufRecord = new ProtobufRecord(baos, parser); 644 644 switch (protobufRecord.getField()) { 645 645 case 1: … … 672 672 throw new IllegalDataException("A way with either no id or no nodes was found"); 673 673 } 674 WayDatawayData = 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); 676 676 long ref = 0; 677 677 for (long tRef : refs) { … … 701 701 throws IllegalDataException, IOException { 702 702 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>(); 705 705 Info info = null; 706 706 long[] rolesStringId = EMPTY_LONG; // Technically int 707 707 long[] memids = EMPTY_LONG; 708 708 long[] types = EMPTY_LONG; // Technically an enum 709 try ( ByteArrayInputStreambais = new ByteArrayInputStream(bytes);710 ProtobufParser parser = new ProtobufParser(bais)) {709 try (var bais = new ByteArrayInputStream(bytes); 710 var parser = new ProtobufParser(bais)) { 711 711 while (parser.hasNext()) { 712 ProtobufRecordprotobufRecord = new ProtobufRecord(baos, parser);712 final var protobufRecord = new ProtobufRecord(baos, parser); 713 713 switch (protobufRecord.getField()) { 714 714 case 1: … … 747 747 throw new IllegalDataException("OSM PBF contains a bad relation definition"); 748 748 } 749 RelationDatadata = new RelationData(id);749 final var data = new RelationData(id); 750 750 if (info != null) { 751 751 setOsmPrimitiveData(primitiveBlockRecord, data, info); … … 757 757 List<RelationMemberData> members = new ArrayList<>(rolesStringId.length); 758 758 long memberId = 0; 759 for ( inti = 0; i < rolesStringId.length; i++) {759 for (var i = 0; i < rolesStringId.length; i++) { 760 760 String role = primitiveBlockRecord.stringTable[(int) rolesStringId[i]]; 761 761 memberId += memids[i]; … … 777 777 @Nonnull 778 778 private static Info parseInfo(ByteArrayOutputStream baos, byte[] bytes) throws IOException { 779 try ( ByteArrayInputStreambais = new ByteArrayInputStream(bytes);780 ProtobufParser parser = new ProtobufParser(bais)) {779 try (var bais = new ByteArrayInputStream(bytes); 780 var parser = new ProtobufParser(bais)) { 781 781 int version = -1; 782 782 Long timestamp = null; … … 784 784 Integer uid = null; 785 785 Integer userSid = null; 786 booleanvisible = true;786 var visible = true; 787 787 while (parser.hasNext()) { 788 ProtobufRecordprotobufRecord = new ProtobufRecord(baos, parser);788 final var protobufRecord = new ProtobufRecord(baos, parser); 789 789 switch (protobufRecord.getField()) { 790 790 case 1: … … 839 839 } 840 840 Map<String, String> tagMap = new HashMap<>(keys.size()); 841 for ( inti = 0; i < keys.size(); i++) {841 for (var i = 0; i < keys.size(); i++) { 842 842 tagMap.put(keys.get(i), values.get(i)); 843 843 } … … 879 879 @Nonnull 880 880 private static long[] decodePackedSInt64(long[] numbers) { 881 for ( inti = 0; i < numbers.length; i++) {881 for (var i = 0; i < numbers.length; i++) { 882 882 numbers[i] = ProtobufParser.decodeZigZag(numbers[i]); 883 883 } … … 922 922 long[] userSid = EMPTY_LONG; // technically int 923 923 long[] visible = EMPTY_LONG; // optional, true if not set, technically booleans 924 try ( ByteArrayInputStreambais = new ByteArrayInputStream(bytes);925 ProtobufParser parser = new ProtobufParser(bais)) {924 try (var bais = new ByteArrayInputStream(bytes); 925 var parser = new ProtobufParser(bais)) { 926 926 while (parser.hasNext()) { 927 ProtobufRecordprotobufRecord = new ProtobufRecord(baos, parser);927 final var protobufRecord = new ProtobufRecord(baos, parser); 928 928 switch (protobufRecord.getField()) { 929 929 case 1: … … 956 956 } 957 957 if (version.length > 0) { 958 Info[]infos = new Info[version.length];958 final var infos = new Info[version.length]; 959 959 long lastTimestamp = 0; // delta encoded 960 960 long lastChangeset = 0; // delta encoded 961 961 long lastUid = 0; // delta encoded, 962 962 long lastUserSid = 0; // delta encoded, string id for username 963 for ( inti = 0; i < version.length; i++) {963 for (var i = 0; i < version.length; i++) { 964 964 if (timestamp.length > i) 965 965 lastTimestamp += timestamp[i]; -
trunk/src/org/openstreetmap/josm/tools/ImageResizeMode.java
r17144 r19048 87 87 */ 88 88 BufferedImage createBufferedImage(Dimension dim, Dimension icon, Consumer<Graphics2D> renderer, Image sourceIcon) { 89 final Dimensionreal = computeDimension(dim, icon);90 final BufferedImagebufferedImage = 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); 91 91 final Graphics2D g = bufferedImage.createGraphics(); 92 92 g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); … … 119 119 * @return a cache key 120 120 */ 121 @SuppressWarnings("EnumOrdinal") 121 122 int cacheKey(Dimension dim) { 122 123 return (ordinal() << 28) | ((dim.width & 0xfff) << 16) | (dim.height & 0xfff); -
trunk/src/org/openstreetmap/josm/tools/Utils.java
r18811 r19048 30 30 import java.nio.file.StandardCopyOption; 31 31 import java.nio.file.attribute.BasicFileAttributes; 32 import java.nio.file.attribute.FileTime;33 32 import java.security.MessageDigest; 34 33 import java.security.NoSuchAlgorithmException; … … 153 152 */ 154 153 public static <T> int indexOf(Iterable<? extends T> collection, Predicate<? super T> predicate) { 155 inti = 0;156 for ( Titem : collection) {154 var i = 0; 155 for (var item : collection) { 157 156 if (predicate.test(item)) 158 157 return i; … … 186 185 if (n <= 0) 187 186 throw new IllegalArgumentException("n must be <= 0 but is " + n); 188 intres = a % n;187 var res = a % n; 189 188 if (res < 0) { 190 189 res += n; … … 304 303 Logging.warn("Unable to create directory "+out.getPath()); 305 304 } 306 File[]files = in.listFiles();305 var files = in.listFiles(); 307 306 if (files != null) { 308 for ( Filef : files) {309 Filetarget = new File(out, f.getName());307 for (var f : files) { 308 var target = new File(out, f.getName()); 310 309 if (f.isDirectory()) { 311 310 copyDirectory(f, target); … … 325 324 public static boolean deleteDirectory(File path) { 326 325 if (path.exists()) { 327 File[]files = path.listFiles();326 var files = path.listFiles(); 328 327 if (files != null) { 329 for ( Filefile : files) {328 for (var file : files) { 330 329 if (file.isDirectory()) { 331 330 deleteDirectory(file); … … 372 371 */ 373 372 public static boolean deleteFile(File file, String warnMsg) { 374 booleanresult = file.delete();373 var result = file.delete(); 375 374 if (!result) { 376 375 Logging.warn(tr(warnMsg, file.getPath())); … … 398 397 */ 399 398 public static boolean mkDirs(File dir, String warnMsg) { 400 booleanresult = dir.mkdirs();399 var result = dir.mkdirs(); 401 400 if (!result) { 402 401 Logging.warn(tr(warnMsg, dir.getPath())); … … 498 497 throw new JosmRuntimeException(e); 499 498 } 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); 502 501 return toHexString(byteDigest); 503 502 } … … 518 517 } 519 518 520 final intlen = bytes.length;519 final var len = bytes.length; 521 520 if (len == 0) { 522 521 return ""; 523 522 } 524 523 525 char[]hexChars = new char[len * 2];526 intj = 0;524 var hexChars = new char[len * 2]; 525 var j = 0; 527 526 for (final int v : bytes) { 528 527 hexChars[j++] = HEX_ARRAY[(v & 0xf0) >> 4]; … … 542 541 */ 543 542 public static <T> List<T> topologicalSort(final MultiMap<T, T> dependencies) { 544 MultiMap<T, T> deps = new MultiMap<>();545 for ( Tkey : dependencies.keySet()) {543 var deps = new MultiMap<T, T>(); 544 for (var key : dependencies.keySet()) { 546 545 deps.putVoid(key); 547 for ( Tval : dependencies.get(key)) {546 for (var val : dependencies.get(key)) { 548 547 deps.putVoid(val); 549 548 deps.put(key, val); … … 551 550 } 552 551 553 intsize = deps.size();552 var size = deps.size(); 554 553 List<T> sorted = new ArrayList<>(); 555 for ( inti = 0; i < size; ++i) {556 Tparentless = deps.keySet().stream()554 for (var i = 0; i < size; ++i) { 555 var parentless = deps.keySet().stream() 557 556 .filter(key -> deps.get(key).isEmpty()) 558 557 .findFirst().orElse(null); … … 560 559 sorted.add(parentless); 561 560 deps.remove(parentless); 562 for ( Tkey : deps.keySet()) {561 for (var key : deps.keySet()) { 563 562 deps.remove(key, parentless); 564 563 } … … 680 679 return Collections.emptyMap(); 681 680 } else if (map.size() == 1) { 682 final Map.Entry<K, V>entry = map.entrySet().iterator().next();681 final var entry = map.entrySet().iterator().next(); 683 682 return Collections.singletonMap(entry.getKey(), entry.getValue()); 684 683 } else if (mapOfEntries != null) { … … 796 795 } 797 796 798 intstart = 0;799 intend = str.length();800 booleanleadingSkipChar = true;797 var start = 0; 798 var end = str.length(); 799 var leadingSkipChar = true; 801 800 while (leadingSkipChar && start < end) { 802 801 leadingSkipChar = isStrippedChar(str.charAt(start), skipChars); … … 805 804 } 806 805 } 807 booleantrailingSkipChar = true;806 var trailingSkipChar = true; 808 807 while (trailingSkipChar && end > start) { 809 808 trailingSkipChar = isStrippedChar(str.charAt(end - 1), skipChars); … … 867 866 Logging.debug(String.join(" ", command)); 868 867 } 869 Pathout = Files.createTempFile("josm_exec_" + command.get(0) + "_", ".txt");868 var out = Files.createTempFile("josm_exec_" + command.get(0) + "_", ".txt"); 870 869 try { 871 Processp = new ProcessBuilder(command).redirectErrorStream(true).redirectOutput(out.toFile()).start();870 var p = new ProcessBuilder(command).redirectErrorStream(true).redirectOutput(out.toFile()).start(); 872 871 if (!p.waitFor(timeout, unit) || p.exitValue() != 0) { 873 872 throw new ExecutionException(command.toString(), null); … … 889 888 */ 890 889 public static File getJosmTempDir() { 891 StringtmpDir = getSystemProperty("java.io.tmpdir");890 var tmpDir = getSystemProperty("java.io.tmpdir"); 892 891 if (tmpDir == null) { 893 892 return null; 894 893 } 895 FilejosmTmpDir = new File(tmpDir, "JOSM");894 final var josmTmpDir = new File(tmpDir, "JOSM"); 896 895 if (!josmTmpDir.exists() && !josmTmpDir.mkdirs()) { 897 896 Logging.warn("Unable to create temp directory " + josmTmpDir); … … 921 920 // Is it less than 1 hour ? 922 921 if (elapsedTime < MILLIS_OF_HOUR) { 923 final longmin = elapsedTime / MILLIS_OF_MINUTE;922 final var min = elapsedTime / MILLIS_OF_MINUTE; 924 923 return String.format("%d %s %d %s", min, tr("min"), (elapsedTime - min * MILLIS_OF_MINUTE) / MILLIS_OF_SECOND, tr("s")); 925 924 } 926 925 // Is it less than 1 day ? 927 926 if (elapsedTime < MILLIS_OF_DAY) { 928 final longhour = elapsedTime / MILLIS_OF_HOUR;927 final var hour = elapsedTime / MILLIS_OF_HOUR; 929 928 return String.format("%d %s %d %s", hour, tr("h"), (elapsedTime - hour * MILLIS_OF_HOUR) / MILLIS_OF_MINUTE, tr("min")); 930 929 } 931 longdays = elapsedTime / MILLIS_OF_DAY;930 var days = elapsedTime / MILLIS_OF_DAY; 932 931 return String.format("%d %s %d %s", days, trn("day", "days", days), (elapsedTime - days * MILLIS_OF_DAY) / MILLIS_OF_HOUR, tr("h")); 933 932 } … … 944 943 throw new IllegalArgumentException("bytes must be >= 0"); 945 944 } 946 intunitIndex = 0;945 var unitIndex = 0; 947 946 double value = bytes; 948 947 while (value >= 1024 && unitIndex < SIZE_UNITS.length) { … … 968 967 public static String getPositionListString(List<Integer> positionList) { 969 968 Collections.sort(positionList); 970 final StringBuilder sb = new StringBuilder(32);969 final var sb = new StringBuilder(32); 971 970 sb.append(positionList.get(0)); 972 intcnt = 0;971 var cnt = 0; 973 972 int last = positionList.get(0); 974 for ( inti = 1; i < positionList.size(); ++i) {973 for (var i = 1; i < positionList.size(); ++i) { 975 974 int cur = positionList.get(i); 976 975 if (cur == last + 1) { … … 1031 1030 */ 1032 1031 public static Throwable getRootCause(Throwable t) { 1033 Throwableresult = t;1032 var result = t; 1034 1033 if (result != null) { 1035 Throwablecause = result.getCause();1034 var cause = result.getCause(); 1036 1035 while (cause != null && !cause.equals(result)) { 1037 1036 result = cause; … … 1051 1050 */ 1052 1051 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); 1054 1053 biggerCopy[array.length] = item; 1055 1054 return biggerCopy; … … 1064 1063 */ 1065 1064 public static String shortenString(String s, int maxLength) { 1066 final Stringellipses = "...";1065 final var ellipses = "..."; 1067 1066 CheckParameterUtil.ensureThat(maxLength >= ellipses.length(), "maxLength is shorter than " + ellipses.length()); 1068 1067 if (s != null && s.length() > maxLength) { … … 1102 1101 if (elements.size() > maxElements) { 1103 1102 final Collection<T> r = new ArrayList<>(maxElements); 1104 final Iterator<T>it = elements.iterator();1103 final var it = elements.iterator(); 1105 1104 while (r.size() < maxElements - 1) { 1106 1105 r.add(it.next()); … … 1127 1126 return url; 1128 1127 1129 Stringquery = url.substring(url.indexOf('?') + 1);1130 1131 StringBuilder sb = new StringBuilder(url.substring(0, url.indexOf('?') + 1));1132 1133 for ( inti = 0; i < query.length(); i++) {1134 Stringc = 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); 1135 1134 if (URL_CHARS.contains(c)) { 1136 1135 sb.append(c); … … 1153 1152 */ 1154 1153 public static String encodeUrl(String s) { 1155 final Stringenc = StandardCharsets.UTF_8.name();1154 final var enc = StandardCharsets.UTF_8.name(); 1156 1155 try { 1157 1156 return URLEncoder.encode(s, enc); … … 1173 1172 */ 1174 1173 public static String decodeUrl(String s) { 1175 final Stringenc = StandardCharsets.UTF_8.name();1174 final var enc = StandardCharsets.UTF_8.name(); 1176 1175 try { 1177 1176 return URLDecoder.decode(s, enc); … … 1221 1220 @Override 1222 1221 public Thread newThread(final Runnable runnable) { 1223 final Threadthread = new Thread(runnable, String.format(Locale.ENGLISH, nameFormat, count.getAndIncrement()));1222 final var thread = new Thread(runnable, String.format(Locale.ENGLISH, nameFormat, count.getAndIncrement())); 1224 1223 thread.setPriority(threadPriority); 1225 1224 return thread; … … 1299 1298 public static boolean isSimilar(String string1, String string2) { 1300 1299 // check plain strings 1301 intdistance = getLevenshteinDistance(string1, string2);1300 var distance = getLevenshteinDistance(string1, string2); 1302 1301 1303 1302 // check if only the case differs, so we don't consider large distance as different strings … … 1340 1339 } 1341 1340 1342 for ( doublelength : values) {1341 for (var length : values) { 1343 1342 standardDeviation += Math.pow(length - mean, 2); 1344 1343 } … … 1361 1360 } 1362 1361 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}; 1364 1363 groups.add(current); 1365 for ( introw : integers) {1364 for (var row : integers) { 1366 1365 if (current[0] == Integer.MIN_VALUE) { 1367 1366 current[0] = row; … … 1398 1397 @SuppressWarnings("ThreadPriorityCheck") 1399 1398 public static ForkJoinPool newForkJoinPool(String pref, final String nameFormat, final int threadPriority) { 1400 intnoThreads = Config.getPref().getInt(pref, Runtime.getRuntime().availableProcessors());1399 final var noThreads = Config.getPref().getInt(pref, Runtime.getRuntime().availableProcessors()); 1401 1400 return new ForkJoinPool(noThreads, new ForkJoinPool.ForkJoinWorkerThreadFactory() { 1402 1401 final AtomicLong count = new AtomicLong(0); … … 1468 1467 if (value != null) { 1469 1468 try { 1470 Stringold = System.setProperty(key, value);1469 var old = System.setProperty(key, value); 1471 1470 if (Logging.isDebugEnabled() && !value.equals(old)) { 1472 1471 if (!key.toLowerCase(Locale.ENGLISH).contains("password")) { … … 1494 1493 */ 1495 1494 public static boolean hasExtension(String filename, String... extensions) { 1496 Stringname = filename.toLowerCase(Locale.ENGLISH).replace("?format=raw", "");1495 var name = filename.toLowerCase(Locale.ENGLISH).replace("?format=raw", ""); 1497 1496 return Arrays.stream(extensions) 1498 1497 .anyMatch(ext -> name.endsWith('.' + ext.toLowerCase(Locale.ENGLISH))); … … 1523 1522 return new byte[0]; 1524 1523 } 1525 try ( ByteArrayOutputStreambout = new ByteArrayOutputStream(stream.available())) {1526 byte[]buffer = new byte[8192];1527 booleanfinished = false;1524 try (stream; var bout = new ByteArrayOutputStream(stream.available())) { 1525 final var buffer = new byte[8192]; 1526 var finished = false; 1528 1527 do { 1529 intread = stream.read(buffer);1528 var read = stream.read(buffer); 1530 1529 if (read >= 0) { 1531 1530 bout.write(buffer, 0, read); … … 1537 1536 return new byte[0]; 1538 1537 return bout.toByteArray(); 1539 } finally {1540 stream.close();1541 1538 } 1542 1539 } … … 1603 1600 */ 1604 1601 public static List<GlyphVector> getGlyphVectorsBidi(String string, Font font, FontRenderContext frc) { 1605 List<GlyphVector> gvs = new ArrayList<>();1606 Bidibidi = 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 ( inti = 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) { 1610 1607 levels[i] = (byte) bidi.getRunLevel(i); 1611 Stringsubstr = string.substring(bidi.getRunStart(i), bidi.getRunLimit(i));1612 intdir = 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; 1613 1610 dirStrings[i] = new DirectionString(dir, substr); 1614 1611 } 1615 1612 Bidi.reorderVisually(levels, 0, dirStrings, 0, levels.length); 1616 for ( DirectionStringdirString : dirStrings) {1617 char[]chars = dirString.str.toCharArray();1613 for (var dirString : dirStrings) { 1614 var chars = dirString.str.toCharArray(); 1618 1615 gvs.add(font.layoutGlyphVector(frc, chars, 0, chars.length, dirString.direction)); 1619 1616 } … … 1712 1709 public static int getJavaVersion() { 1713 1710 // Switch to Runtime.version() once we move past Java 8 1714 Stringversion = Objects.requireNonNull(getSystemProperty("java.version"));1711 var version = Objects.requireNonNull(getSystemProperty("java.version")); 1715 1712 if (version.startsWith("1.")) { 1716 1713 version = version.substring(2); … … 1721 1718 // 9 1722 1719 // 9.0.1 1723 intdotPos = version.indexOf('.');1724 intdashPos = version.indexOf('-');1720 var dotPos = version.indexOf('.'); 1721 var dashPos = version.indexOf('-'); 1725 1722 return Integer.parseInt(version.substring(0, 1726 1723 dotPos > -1 ? dotPos : dashPos > -1 ? dashPos : version.length())); … … 1734 1731 public static int getJavaUpdate() { 1735 1732 // Switch to Runtime.version() once we move past Java 8 1736 Stringversion = Objects.requireNonNull(getSystemProperty("java.version"));1733 var version = Objects.requireNonNull(getSystemProperty("java.version")); 1737 1734 if (version.startsWith("1.")) { 1738 1735 version = version.substring(2); … … 1745 1742 // 17.0.4.1+1-LTS 1746 1743 // $MAJOR.$MINOR.$SECURITY.$PATCH 1747 intundePos = version.indexOf('_');1748 intdashPos = version.indexOf('-');1744 var undePos = version.indexOf('_'); 1745 var dashPos = version.indexOf('-'); 1749 1746 if (undePos > -1) { 1750 1747 return Integer.parseInt(version.substring(undePos + 1, 1751 1748 dashPos > -1 ? dashPos : version.length())); 1752 1749 } 1753 intfirstDotPos = version.indexOf('.');1754 intsecondDotPos = version.indexOf('.', firstDotPos + 1);1750 var firstDotPos = version.indexOf('.'); 1751 var secondDotPos = version.indexOf('.', firstDotPos + 1); 1755 1752 if (firstDotPos == secondDotPos) { 1756 1753 return 0; … … 1767 1764 public static int getJavaBuild() { 1768 1765 // Switch to Runtime.version() once we move past Java 8 1769 Stringversion = Objects.requireNonNull(getSystemProperty("java.runtime.version"));1770 intbPos = version.indexOf('b');1771 intpPos = version.indexOf('+');1766 var version = Objects.requireNonNull(getSystemProperty("java.runtime.version")); 1767 var bPos = version.indexOf('b'); 1768 var pPos = version.indexOf('+'); 1772 1769 try { 1773 1770 return Integer.parseInt(version.substring(bPos > -1 ? bPos + 1 : pPos + 1)); … … 1786 1783 try { 1787 1784 Object value; 1788 Class<?>c = Class.forName("com.sun.deploy.config.BuiltInProperties");1785 var c = Class.forName("com.sun.deploy.config.BuiltInProperties"); 1789 1786 try { 1790 1787 value = c.getDeclaredField("JRE_EXPIRATION_DATE").get(null); … … 1810 1807 public static String getJavaLatestVersion() { 1811 1808 try { 1812 String[]versions = HttpClient.create(1809 var versions = HttpClient.create( 1813 1810 new URL(Config.getPref().get( 1814 1811 "java.baseline.version.url", … … 1816 1813 .connect().fetchContent().split("\n", -1); 1817 1814 if (getJavaVersion() <= 11 && isRunningWebStart()) { // OpenWebStart currently only has Java 11 1818 for ( Stringversion : versions) {1815 for (var version : versions) { 1819 1816 if (version.startsWith("11")) { 1820 1817 return version; … … 1822 1819 } 1823 1820 } else if (getJavaVersion() <= 17) { 1824 for ( Stringversion : versions) {1821 for (var version : versions) { 1825 1822 if (version.startsWith("17")) { // Use current Java LTS 1826 1823 return version; … … 1945 1942 return url.openStream(); 1946 1943 } catch (FileNotFoundException | InvalidPathException e) { 1947 URLbetterUrl = betterJarUrl(url);1944 final var betterUrl = betterJarUrl(url); 1948 1945 if (betterUrl != null) { 1949 1946 try { … … 1982 1979 public static URL betterJarUrl(URL jarUrl, URL defaultUrl) throws IOException { 1983 1980 // Workaround to https://bugs.openjdk.java.net/browse/JDK-4523159 1984 StringurlPath = jarUrl.getPath().replace("%20", " ");1981 var urlPath = jarUrl.getPath().replace("%20", " "); 1985 1982 if (urlPath.startsWith("file:/") && urlPath.split("!", -1).length > 2) { 1986 1983 // Locate jar file 1987 intindex = urlPath.lastIndexOf("!/");1988 PathjarFile = Paths.get(urlPath.substring("file:/".length(), index));1989 Pathfilename = jarFile.getFileName();1990 FileTimejarTime = 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(); 1991 1988 // Copy it to temp directory (hopefully free of exclamation mark) if needed (missing or older jar) 1992 PathjarCopy = Paths.get(getSystemProperty("java.io.tmpdir")).resolve(filename);1989 final var jarCopy = Paths.get(getSystemProperty("java.io.tmpdir")).resolve(filename); 1993 1990 if (!jarCopy.toFile().exists() || 1994 1991 Files.readAttributes(jarCopy, BasicFileAttributes.class).lastModifiedTime().compareTo(jarTime) < 0) { … … 2029 2026 Logging.trace(e); 2030 2027 try { 2031 URLbetterUrl = betterJarUrl(cl.getResource(path));2028 final var betterUrl = betterJarUrl(cl.getResource(path)); 2032 2029 if (betterUrl != null) { 2033 2030 return betterUrl.openStream();
Note:
See TracChangeset
for help on using the changeset viewer.