From 48f9f8376d17ccaeb20371135a2541b3a5566aaf Mon Sep 17 00:00:00 2001 From: "taylor.smock" Date: Mon, 16 Oct 2023 17:03:11 +0000 Subject: [PATCH] See #23218: Use newer error_prone versions when compiling on Java 11+ error_prone 2.11 dropped support for compiling with Java 8, although it still supports compiling for Java 8. The "major" new check for us is `NotJavadoc` since we used `/**` in quite a few places which were not javadoc. Other "new" checks that are of interest: * `AlreadyChecked`: `if (foo) { doFoo(); } else if (!foo) { doBar(); }` * `UnnecessaryStringBuilder`: Avoid `StringBuilder` (Java converts `+` to `StringBuilder` behind-the-scenes, but may also do something else if it performs better) * `NonApiType`: Avoid specific interface types in function definitions * `NamedLikeContextualKeyword`: Avoid using restricted names for classes and methods * `UnusedMethod`: Unused private methods should be removed This fixes most of the new error_prone issues and some SonarLint issues. git-svn-id: https://josm.openstreetmap.de/svn/trunk@18871 0c6e7542-c601-0410-84e7-c038aed88b3b --- build.xml | 8 +- ivysettings.xml | 3 + .../josm/actions/CloseChangesetAction.java | 9 +- .../josm/actions/JoinAreasAction.java | 2 +- .../josm/actions/OpenFileAction.java | 4 +- .../josm/actions/ShowStatusReportAction.java | 2 +- .../josm/actions/UploadAction.java | 10 +- .../actions/mapmode/ParallelWayAction.java | 53 +++++----- .../josm/actions/search/SearchAction.java | 7 +- .../josm/command/PurgeCommand.java | 6 +- src/org/openstreetmap/josm/data/Bounds.java | 5 +- .../openstreetmap/josm/data/StructUtils.java | 42 ++++---- .../data/imagery/AbstractWMSTileSource.java | 16 ++- .../josm/data/imagery/WMTSTileSource.java | 9 +- .../vectortile/mapbox/style/Expression.java | 11 +-- .../vectortile/mapbox/style/Layers.java | 19 ++-- .../openstreetmap/josm/data/osm/DataSet.java | 2 + .../openstreetmap/josm/data/osm/NodePair.java | 12 +-- .../osm/visitor/paint/StyledMapRenderer.java | 52 +++++----- .../data/projection/datum/NTV2SubGrid.java | 46 +++++---- .../josm/data/sources/SourceInfo.java | 17 ++-- .../josm/data/validation/tests/Addresses.java | 2 +- .../validation/tests/MultipolygonTest.java | 4 +- .../data/validation/tests/PowerLines.java | 1 + .../validation/tests/UnconnectedWays.java | 4 +- src/org/openstreetmap/josm/gui/MapFrame.java | 19 ++-- .../josm/gui/NavigatableComponent.java | 98 +++++++++---------- .../josm/gui/bbox/SlippyMapBBoxChooser.java | 5 +- .../RelationMemberListMergeModel.java | 7 +- .../josm/gui/dialogs/DialogsPanel.java | 24 ++--- .../josm/gui/dialogs/ToggleDialog.java | 22 ++--- .../relation/sort/RelationSortUtils.java | 4 +- .../sort/WayConnectionTypeCalculator.java | 18 ++-- .../download/OverpassQueryWizardDialog.java | 7 +- .../gui/layer/AbstractTileSourceLayer.java | 67 +++++++------ .../josm/gui/layer/WMSLayer.java | 8 +- .../josm/gui/layer/WMTSLayer.java | 6 +- .../gui/layer/geoimage/GeoImageLayer.java | 25 +++-- .../josm/gui/layer/geoimage/ImageDisplay.java | 1 + .../josm/gui/layer/gpx/GpxDrawHelper.java | 65 +++++++----- .../gui/layer/imagery/LoadAllTilesAction.java | 4 - .../josm/gui/mappaint/mapcss/Selector.java | 6 +- .../josm/gui/preferences/SourceEditor.java | 14 +-- .../gui/preferences/ToolbarPreferences.java | 48 +++++---- .../preferences/display/ColorPreference.java | 2 +- .../imagery/CacheSettingsPanel.java | 4 +- .../preferences/plugin/PluginPreference.java | 4 +- .../projection/ProjectionPreference.java | 92 ++++++++--------- .../tagging/presets/TaggingPresetMenu.java | 3 +- .../tagging/presets/TaggingPresetReader.java | 12 +-- .../gui/tagging/presets/items/KeyedItem.java | 2 +- .../josm/gui/widgets/MultiSplitLayout.java | 13 ++- src/org/openstreetmap/josm/io/OsmApi.java | 37 ++++--- .../josm/io/OsmHistoryReader.java | 4 +- .../josm/io/imagery/ImageryReader.java | 2 +- .../josm/io/imagery/WMSImagery.java | 48 ++++----- .../handler/LoadAndZoomHandler.java | 2 +- .../handler/LoadDataHandler.java | 2 +- .../openstreetmap/josm/tools/Geometry.java | 46 ++++----- .../josm/tools/ReflectionUtils.java | 2 +- .../openstreetmap/josm/tools/Shortcut.java | 19 ++-- tools/ivy.xml | 2 +- 62 files changed, 555 insertions(+), 535 deletions(-) diff --git a/build.xml b/build.xml index 6305ee6ae3a..e361bf7ddd4 100644 --- a/build.xml +++ b/build.xml @@ -220,6 +220,12 @@ Build-Date: ${build.tstamp} + + + + + + @@ -249,7 +255,7 @@ Build-Date: ${build.tstamp} - + diff --git a/ivysettings.xml b/ivysettings.xml index 6e9cdfcff9f..f02e7f83064 100644 --- a/ivysettings.xml +++ b/ivysettings.xml @@ -5,4 +5,7 @@ + + + diff --git a/src/org/openstreetmap/josm/actions/CloseChangesetAction.java b/src/org/openstreetmap/josm/actions/CloseChangesetAction.java index 02e8c0d456e..9a079bfc57b 100644 --- a/src/org/openstreetmap/josm/actions/CloseChangesetAction.java +++ b/src/org/openstreetmap/josm/actions/CloseChangesetAction.java @@ -35,7 +35,7 @@ /** * User action to close open changesets. - * + *

* The list of open changesets will be downloaded from the server and presented * to the user. */ @@ -109,11 +109,12 @@ protected void cancel() { @Override protected void finish() { SwingUtilities.invokeLater(() -> { - if (lastException != null) { - ExceptionDialogUtil.explainException(lastException); + Exception exception = getLastException(); + if (exception != null) { + ExceptionDialogUtil.explainException(exception); } ChangesetCache.getInstance().update(changesets); - if (!canceled && lastException == null) { + if (!isCanceled() && exception == null) { onPostDownloadOpenChangesets(); } }); diff --git a/src/org/openstreetmap/josm/actions/JoinAreasAction.java b/src/org/openstreetmap/josm/actions/JoinAreasAction.java index fec9fe392a5..3615ad59a86 100644 --- a/src/org/openstreetmap/josm/actions/JoinAreasAction.java +++ b/src/org/openstreetmap/josm/actions/JoinAreasAction.java @@ -245,7 +245,7 @@ public AssembledMultipolygon(AssembledPolygon way) { } /** - * This hepler class implements algorithm traversing trough connected ways. + * This helper class implements algorithm traversing through connected ways. * Assumes you are going in clockwise orientation. * @author viesturs */ diff --git a/src/org/openstreetmap/josm/actions/OpenFileAction.java b/src/org/openstreetmap/josm/actions/OpenFileAction.java index b2882845812..be8153cd796 100644 --- a/src/org/openstreetmap/josm/actions/OpenFileAction.java +++ b/src/org/openstreetmap/josm/actions/OpenFileAction.java @@ -274,7 +274,7 @@ protected void alertFilesWithUnknownImporter(Collection files) { protected void realRun() throws SAXException, IOException, OsmTransferException { if (Utils.isEmpty(files)) return; - /** + /* * Find the importer with the chosen file filter */ FileImporter chosenImporter = null; @@ -285,7 +285,7 @@ protected void realRun() throws SAXException, IOException, OsmTransferException } } } - /** + /* * If the filter hasn't been changed in the dialog, chosenImporter is null now. * When the filter has been set explicitly to AllFormatsImporter, treat this the same. */ diff --git a/src/org/openstreetmap/josm/actions/ShowStatusReportAction.java b/src/org/openstreetmap/josm/actions/ShowStatusReportAction.java index 2a1f27e4114..3483442798e 100644 --- a/src/org/openstreetmap/josm/actions/ShowStatusReportAction.java +++ b/src/org/openstreetmap/josm/actions/ShowStatusReportAction.java @@ -268,7 +268,7 @@ private static List paramCleanup(Collection params) { * @return map that maps shortened name to full directory path */ static Map getAnonimicDirectorySymbolMap() { - /** maps the anonymized name to the actual used path */ + /* maps the anonymized name to the actual used path */ Map map = new LinkedHashMap<>(); map.put(PlatformManager.isPlatformWindows() ? "%JAVA_HOME%" : "${JAVA_HOME}", getSystemEnv("JAVA_HOME")); map.put("", getSystemProperty("java.home")); diff --git a/src/org/openstreetmap/josm/actions/UploadAction.java b/src/org/openstreetmap/josm/actions/UploadAction.java index b0bd3d48e24..4104b9bb367 100644 --- a/src/org/openstreetmap/josm/actions/UploadAction.java +++ b/src/org/openstreetmap/josm/actions/UploadAction.java @@ -72,27 +72,27 @@ public class UploadAction extends AbstractUploadAction { private static final String IS_ASYNC_UPLOAD_ENABLED = "asynchronous.upload"; static { - /** + /* * Calls validator before upload. */ UPLOAD_HOOKS.add(new ValidateUploadHook()); - /** + /* * Fixes database errors */ UPLOAD_HOOKS.add(new FixDataHook()); - /** + /* * Checks server capabilities before upload. */ UPLOAD_HOOKS.add(new ApiPreconditionCheckerHook()); - /** + /* * Adjusts the upload order of new relations */ UPLOAD_HOOKS.add(new RelationUploadOrderHook()); - /** + /* * Removes discardable tags like created_by on modified objects */ LATE_UPLOAD_HOOKS.add(new DiscardTagsHook()); diff --git a/src/org/openstreetmap/josm/actions/mapmode/ParallelWayAction.java b/src/org/openstreetmap/josm/actions/mapmode/ParallelWayAction.java index 55b14af6394..79d75a00964 100644 --- a/src/org/openstreetmap/josm/actions/mapmode/ParallelWayAction.java +++ b/src/org/openstreetmap/josm/actions/mapmode/ParallelWayAction.java @@ -55,35 +55,30 @@ /** * MapMode for making parallel ways. - * + *

* All calculations are done in projected coordinates. - * + *

* TODO: + *

* == Functionality == - * - * 1. Use selected nodes as split points for the selected ways. - * + *

    + *
  1. Use selected nodes as split points for the selected ways. + *

    * The ways containing the selected nodes will be split and only the "inner" - * parts will be copied - * - * 2. Enter exact offset - * - * 3. Improve snapping - * - * 4. Visual cues could be better - * - * 5. (long term) Parallelize and adjust offsets of existing ways - * + * parts will be copied

  2. + *
  3. Enter exact offset
  4. + *
  5. Improve snapping
  6. + *
  7. Visual cues could be better
  8. + *
  9. (long term) Parallelize and adjust offsets of existing ways
  10. + *
* == Code quality == - * - * a) The mode, flags, and modifiers might be updated more than necessary. - * - * Not a performance problem, but better if they where more centralized - * - * b) Extract generic MapMode services into a super class and/or utility class - * - * c) Maybe better to simply draw our own source way highlighting? - * + *
    + *
  1. The mode, flags, and modifiers might be updated more than necessary. + *

    + * Not a performance problem, but better if they where more centralized

  2. + *
  3. Extract generic MapMode services into a super class and/or utility class
  4. + *
  5. Maybe better to simply draw our own source way highlighting?
  6. + *
* Current code doesn't not take into account that ways might been highlighted * by other than us. Don't think that situation should ever happen though. * @@ -351,7 +346,7 @@ private static void removeWayHighlighting(Collection ways) { @Override public void mouseDragged(MouseEvent e) { - // WTF.. the event passed here doesn't have button info? + // WTF... the event passed here doesn't have button info? // Since we get this event from other buttons too, we must check that // _BUTTON1_ is down. if (!mouseIsDown) @@ -455,7 +450,7 @@ private boolean matchesCurrentModifiers(Map spec) { if (shift) { modifiers.add(Modifier.SHIFT); } - return spec.entrySet().stream().allMatch(entry -> modifiers.contains(entry.getKey()) == entry.getValue().booleanValue()); + return spec.entrySet().stream().allMatch(entry -> modifiers.contains(entry.getKey()) == entry.getValue()); } private boolean isModifiersValidForDragMode() { @@ -464,11 +459,11 @@ private boolean isModifiersValidForDragMode() { } private void updateFlagsOnlyChangeableOnPress() { - copyTags = COPY_TAGS_DEFAULT.get().booleanValue() != matchesCurrentModifiers(COPY_TAGS_MODIFIER_COMBO); + copyTags = COPY_TAGS_DEFAULT.get() != matchesCurrentModifiers(COPY_TAGS_MODIFIER_COMBO); } private void updateFlagsChangeableAlways() { - snap = SNAP_DEFAULT.get().booleanValue() != matchesCurrentModifiers(SNAP_MODIFIER_COMBO); + snap = SNAP_DEFAULT.get() != matchesCurrentModifiers(SNAP_MODIFIER_COMBO); } // We keep the source ways and the selection in sync so the user can see the source way's tags @@ -553,7 +548,7 @@ private static String prefKey(String subKey) { private static class KeyboardModifiersProperty extends AbstractToStringProperty> { KeyboardModifiersProperty(String key, String defaultValue) { - super(key, createFromString(defaultValue)); + this(key, createFromString(defaultValue)); } KeyboardModifiersProperty(String key, Map defaultValue) { diff --git a/src/org/openstreetmap/josm/actions/search/SearchAction.java b/src/org/openstreetmap/josm/actions/search/SearchAction.java index a113f6218fc..d544f3698f6 100644 --- a/src/org/openstreetmap/josm/actions/search/SearchAction.java +++ b/src/org/openstreetmap/josm/actions/search/SearchAction.java @@ -41,6 +41,7 @@ import org.openstreetmap.josm.gui.preferences.ToolbarPreferences.ActionParser; import org.openstreetmap.josm.gui.progress.ProgressMonitor; import org.openstreetmap.josm.gui.tagging.ac.AutoCompComboBoxModel; +import org.openstreetmap.josm.gui.widgets.JosmComboBoxModel; import org.openstreetmap.josm.spi.preferences.Config; import org.openstreetmap.josm.tools.Logging; import org.openstreetmap.josm.tools.Shortcut; @@ -65,10 +66,10 @@ public class SearchAction extends JosmAction implements ParameterizedAction { private static final String SEARCH_EXPRESSION = "searchExpression"; - private static AutoCompComboBoxModel model = new AutoCompComboBoxModel<>(); + private static final AutoCompComboBoxModel model = new AutoCompComboBoxModel<>(); /** preferences reader/writer with automatic transmogrification to and from String */ - private static AutoCompComboBoxModel.Preferences prefs = model.prefs( + private static final JosmComboBoxModel.Preferences prefs = model.prefs( SearchSetting::readFromString, SearchSetting::writeToString); static { @@ -490,6 +491,6 @@ protected void updateEnabledState() { @Override public List> getActionParameters() { - return Collections.>singletonList(new SearchSettingsActionParameter(SEARCH_EXPRESSION)); + return Collections.singletonList(new SearchSettingsActionParameter(SEARCH_EXPRESSION)); } } diff --git a/src/org/openstreetmap/josm/command/PurgeCommand.java b/src/org/openstreetmap/josm/command/PurgeCommand.java index a29e92693b6..38df24c2f19 100644 --- a/src/org/openstreetmap/josm/command/PurgeCommand.java +++ b/src/org/openstreetmap/josm/command/PurgeCommand.java @@ -60,7 +60,7 @@ public PurgeCommand(DataSet data, Collection toPurge, Collection toPurge, Collection makeIncomplete) { - /** + /* * The topological sort is to avoid missing way nodes and missing * relation members when adding primitives back to the dataset on undo. * @@ -159,7 +159,7 @@ public static List topoSort(Collection sel) { // Nodes not deleted in the first pass Set remainingNodes = new HashSet<>(in.size()); - /** + /* * First add nodes that have no way referrer. */ outer: @@ -179,7 +179,7 @@ public static List topoSort(Collection sel) { } } - /** + /* * Then add all ways, each preceded by its (remaining) nodes. */ for (Iterator it = in.iterator(); it.hasNext();) { diff --git a/src/org/openstreetmap/josm/data/Bounds.java b/src/org/openstreetmap/josm/data/Bounds.java index 47d9ed19947..a66d23a9089 100644 --- a/src/org/openstreetmap/josm/data/Bounds.java +++ b/src/org/openstreetmap/josm/data/Bounds.java @@ -552,9 +552,8 @@ public double getArea() { * @return The string encoded bounds */ public String encodeAsString(String separator) { - return new StringBuilder() - .append(minLat).append(separator).append(minLon).append(separator) - .append(maxLat).append(separator).append(maxLon).toString(); + return minLat + separator + minLon + separator + + maxLat + separator + maxLon; } /** diff --git a/src/org/openstreetmap/josm/data/StructUtils.java b/src/org/openstreetmap/josm/data/StructUtils.java index b3adf5e5dd3..438619b2ce7 100644 --- a/src/org/openstreetmap/josm/data/StructUtils.java +++ b/src/org/openstreetmap/josm/data/StructUtils.java @@ -19,6 +19,14 @@ import java.util.Set; import java.util.stream.Collectors; +import org.openstreetmap.josm.spi.preferences.IPreferences; +import org.openstreetmap.josm.tools.JosmRuntimeException; +import org.openstreetmap.josm.tools.Logging; +import org.openstreetmap.josm.tools.MultiMap; +import org.openstreetmap.josm.tools.ReflectionUtils; +import org.openstreetmap.josm.tools.StringParser; +import org.openstreetmap.josm.tools.Utils; + import jakarta.json.Json; import jakarta.json.JsonArray; import jakarta.json.JsonArrayBuilder; @@ -29,17 +37,9 @@ import jakarta.json.JsonValue; import jakarta.json.JsonWriter; -import org.openstreetmap.josm.spi.preferences.IPreferences; -import org.openstreetmap.josm.tools.JosmRuntimeException; -import org.openstreetmap.josm.tools.Logging; -import org.openstreetmap.josm.tools.MultiMap; -import org.openstreetmap.josm.tools.ReflectionUtils; -import org.openstreetmap.josm.tools.StringParser; -import org.openstreetmap.josm.tools.Utils; - /** * Utility methods to convert struct-like classes to a string map and back. - * + *

* A "struct" is a class that has some fields annotated with {@link StructEntry}. * Those fields will be respected when converting an object to a {@link Map} and back. * @since 12851 @@ -106,10 +106,10 @@ public static List getListOfStructs(IPreferences preferences, String key, /** * Convenience method that saves a MapListSetting which is provided as a collection of objects. - * + *

* Each object is converted to a Map<String, String> using the fields with {@link StructEntry} annotation. * The field name is the key and the value will be converted to a string. - * + *

* Considers only fields that have the {@code @StructEntry} annotation. * In addition it does not write fields with null values. (Thus they are cleared) * Default values are given by the field values after default constructor has been called. @@ -148,11 +148,11 @@ public enum SerializeOptions { /** * Convert an object to a String Map, by using field names and values as map key and value. - * + *

* The field value is converted to a String. - * + *

* Only fields with annotation {@link StructEntry} are taken into account. - * + *

* Fields will not be written to the map if the value is null or unchanged * (compared to an object created with the no-arg-constructor). * The {@link WriteExplicitly} annotation overrides this behavior, i.e. the default value will also be written. @@ -163,7 +163,7 @@ public enum SerializeOptions { * @param options optional serialization options * @return the resulting map (same data content as struct) */ - public static HashMap serializeStruct(T struct, Class klass, SerializeOptions... options) { + public static Map serializeStruct(T struct, Class klass, SerializeOptions... options) { List optionsList = Arrays.asList(options); T structPrototype; try { @@ -172,7 +172,7 @@ public static HashMap serializeStruct(T struct, Class kla throw new IllegalArgumentException(ex); } - HashMap hash = new LinkedHashMap<>(); + Map hash = new LinkedHashMap<>(); for (Field f : getDeclaredFieldsInClassOrSuperTypes(klass)) { if (f.getAnnotation(StructEntry.class) == null) { continue; @@ -207,10 +207,10 @@ public static HashMap serializeStruct(T struct, Class kla /** * Converts a String-Map to an object of a certain class, by comparing map keys to field names of the class and assigning * map values to the corresponding fields. - * + *

* The map value (a String) is converted to the field type. Supported types are: boolean, Boolean, int, Integer, double, * Double, String, Map<String, String> and Map<String, List<String>>. - * + *

* Only fields with annotation {@link StructEntry} are taken into account. * @param the class * @param hash the string map with initial values @@ -218,7 +218,7 @@ public static HashMap serializeStruct(T struct, Class kla * @return an object of class T, initialized as described above */ public static T deserializeStruct(Map hash, Class klass) { - T struct = null; + T struct; try { struct = klass.getConstructor().newInstance(); } catch (ReflectiveOperationException ex) { @@ -283,7 +283,7 @@ private static String mapToJson(Map map) { @SuppressWarnings({ "rawtypes", "unchecked" }) private static Map mapFromJson(String s) { - Map ret = null; + Map ret; try (JsonReader reader = Json.createReader(new StringReader(s))) { JsonObject object = reader.readObject(); ret = new HashMap(Utils.hashMapInitialCapacity(object.size())); @@ -321,7 +321,7 @@ private static String multiMapToJson(MultiMap map) { @SuppressWarnings({ "rawtypes", "unchecked" }) private static MultiMap multiMapFromJson(String s) { - MultiMap ret = null; + MultiMap ret; try (JsonReader reader = Json.createReader(new StringReader(s))) { JsonObject object = reader.readObject(); ret = new MultiMap(object.size()); diff --git a/src/org/openstreetmap/josm/data/imagery/AbstractWMSTileSource.java b/src/org/openstreetmap/josm/data/imagery/AbstractWMSTileSource.java index c14d06e872a..985139d5288 100644 --- a/src/org/openstreetmap/josm/data/imagery/AbstractWMSTileSource.java +++ b/src/org/openstreetmap/josm/data/imagery/AbstractWMSTileSource.java @@ -231,14 +231,12 @@ protected String getBbox(int zoom, int tilex, int tiley, boolean switchLatLon) { } private static String getBboxstr(double x1, double x2, double x3, double x4) { - return new StringBuilder(64) - .append(LATLON_FORMAT.format(x1)) - .append(',') - .append(LATLON_FORMAT.format(x2)) - .append(',') - .append(LATLON_FORMAT.format(x3)) - .append(',') - .append(LATLON_FORMAT.format(x4)) - .toString(); + return LATLON_FORMAT.format(x1) + + ',' + + LATLON_FORMAT.format(x2) + + ',' + + LATLON_FORMAT.format(x3) + + ',' + + LATLON_FORMAT.format(x4); } } diff --git a/src/org/openstreetmap/josm/data/imagery/WMTSTileSource.java b/src/org/openstreetmap/josm/data/imagery/WMTSTileSource.java index 60275759282..29a895ca966 100644 --- a/src/org/openstreetmap/josm/data/imagery/WMTSTileSource.java +++ b/src/org/openstreetmap/josm/data/imagery/WMTSTileSource.java @@ -27,6 +27,7 @@ import java.util.Collection; import java.util.Collections; import java.util.Deque; +import java.util.HashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; @@ -230,7 +231,7 @@ public static class Layer { /** * Get title of the layer for user display. - * + *

* This is either the content of the Title element (if available) or * the layer identifier (as fallback) * @return title of the layer for user display @@ -506,7 +507,7 @@ public static WMTSCapabilities getCapabilities(String url, Map h * @throws XMLStreamException See {@link XMLStreamReader} */ private static Collection parseContents(XMLStreamReader reader) throws XMLStreamException { - Map matrixSetById = new ConcurrentHashMap<>(); + Map matrixSetById = new HashMap<>(); Collection layers = new ArrayList<>(); for (int event = reader.getEventType(); reader.hasNext() && !(event == END_ELEMENT && QN_CONTENTS.equals(reader.getName())); @@ -899,10 +900,10 @@ public String getTileUrl(int zoom, int tilex, int tiley) { .replace("{TileMatrix}", tileMatrix.identifier) .replace("{TileRow}", Integer.toString(tiley)) .replace("{TileCol}", Integer.toString(tilex)) - .replaceAll("(?i)\\{style\\}", this.currentLayer.style); + .replaceAll("(?i)\\{style}", this.currentLayer.style); for (Dimension d : currentLayer.dimensions) { - url = url.replaceAll("(?i)\\{"+d.identifier+"\\}", d.defaultValue); + url = url.replaceAll("(?i)\\{"+d.identifier+"}", d.defaultValue); } return url; diff --git a/src/org/openstreetmap/josm/data/imagery/vectortile/mapbox/style/Expression.java b/src/org/openstreetmap/josm/data/imagery/vectortile/mapbox/style/Expression.java index 33264edfded..f33a9896590 100644 --- a/src/org/openstreetmap/josm/data/imagery/vectortile/mapbox/style/Expression.java +++ b/src/org/openstreetmap/josm/data/imagery/vectortile/mapbox/style/Expression.java @@ -19,7 +19,6 @@ public final class Expression { /** An empty expression to use */ public static final Expression EMPTY_EXPRESSION = new Expression(JsonValue.NULL); - private static final String EMPTY_STRING = ""; private final String mapcssFilterExpression; @@ -37,13 +36,13 @@ public Expression(JsonValue value) { } else if (Arrays.asList("<=", ">=", ">", "<", "!=").contains(array.getString(0))) { this.mapcssFilterExpression = convertToString(array.get(1)) + array.getString(0) + convertToString(array.get(2)); } else { - this.mapcssFilterExpression = EMPTY_STRING; + this.mapcssFilterExpression = ""; } } else { - this.mapcssFilterExpression = EMPTY_STRING; + this.mapcssFilterExpression = ""; } } else { - this.mapcssFilterExpression = EMPTY_STRING; + this.mapcssFilterExpression = ""; } } @@ -74,13 +73,13 @@ private static String convertToString(JsonValue value) { + '}'; case NULL: default: - return EMPTY_STRING; + return ""; } } @Override public String toString() { - return !EMPTY_STRING.equals(this.mapcssFilterExpression) ? '[' + this.mapcssFilterExpression + ']' : EMPTY_STRING; + return !"".equals(this.mapcssFilterExpression) ? '[' + this.mapcssFilterExpression + ']' : ""; } @Override diff --git a/src/org/openstreetmap/josm/data/imagery/vectortile/mapbox/style/Layers.java b/src/org/openstreetmap/josm/data/imagery/vectortile/mapbox/style/Layers.java index c9e51a6ce0a..60cea226c0c 100644 --- a/src/org/openstreetmap/josm/data/imagery/vectortile/mapbox/style/Layers.java +++ b/src/org/openstreetmap/josm/data/imagery/vectortile/mapbox/style/Layers.java @@ -14,15 +14,15 @@ import java.util.stream.Collectors; import java.util.stream.Stream; +import org.openstreetmap.josm.gui.mappaint.StyleKeys; +import org.openstreetmap.josm.tools.Utils; + import jakarta.json.JsonArray; import jakarta.json.JsonNumber; import jakarta.json.JsonObject; import jakarta.json.JsonString; import jakarta.json.JsonValue; -import org.openstreetmap.josm.gui.mappaint.StyleKeys; -import org.openstreetmap.josm.tools.Utils; - /** * Mapbox style layers * @author Taylor Smock @@ -58,7 +58,6 @@ enum Type { SKY } - private static final String EMPTY_STRING = ""; private static final char SEMI_COLON = ';'; private static final Pattern CURLY_BRACES = Pattern.compile("(\\{(.*?)})"); private static final String PAINT = "paint"; @@ -147,13 +146,13 @@ public Layers(final String styleId, final JsonObject layerInfo) { this.paintProperties = parsePaintBackground(paintObject); break; default: - this.paintProperties = EMPTY_STRING; + this.paintProperties = ""; } } else { - this.paintProperties = EMPTY_STRING; + this.paintProperties = ""; } } else { - this.paintProperties = EMPTY_STRING; + this.paintProperties = ""; } this.sourceLayer = layerInfo.getString("source-layer", null); } @@ -357,7 +356,7 @@ private String parsePaintSymbol( // text-field if (layoutObject.containsKey("text-field")) { sb.append(StyleKeys.TEXT).append(':') - .append(layoutObject.getString("text-field").replace("}", EMPTY_STRING).replace("{", EMPTY_STRING)) + .append(layoutObject.getString("text-field").replace("}", "").replace("{", "")) .append(SEMI_COLON); } // text-font @@ -460,7 +459,7 @@ private static String parsePaintFill(final JsonObject paintObject) { @Override public String toString() { if (this.filter.toString().isEmpty() && this.paintProperties.isEmpty()) { - return EMPTY_STRING; + return ""; } else if (this.type == Type.BACKGROUND) { // AFAIK, paint has no zoom levels, and doesn't accept a layer return "canvas{" + this.paintProperties + "}"; @@ -476,7 +475,7 @@ public String toString() { } else if (this.minZoom > Integer.MIN_VALUE) { zoomSelector = MessageFormat.format("|z{0}-{1}", this.minZoom, this.maxZoom); } else { - zoomSelector = EMPTY_STRING; + zoomSelector = ""; } final String commonData = zoomSelector + this.filter.toString() + "::" + this.id + "{" + this.paintProperties + "}"; diff --git a/src/org/openstreetmap/josm/data/osm/DataSet.java b/src/org/openstreetmap/josm/data/osm/DataSet.java index ebdafb7e1ac..cc3a63285c8 100644 --- a/src/org/openstreetmap/josm/data/osm/DataSet.java +++ b/src/org/openstreetmap/josm/data/osm/DataSet.java @@ -315,6 +315,8 @@ public Lock getReadLock() { * * @return list of history entries */ + // This needs to return something like a Sequenced Collection (Java 21) + @SuppressWarnings({"NonApiType", "squid:S1319"}) public LinkedList> getSelectionHistory() { return selectionHistory; } diff --git a/src/org/openstreetmap/josm/data/osm/NodePair.java b/src/org/openstreetmap/josm/data/osm/NodePair.java index 378b4318d24..4cd3b7d6649 100644 --- a/src/org/openstreetmap/josm/data/osm/NodePair.java +++ b/src/org/openstreetmap/josm/data/osm/NodePair.java @@ -75,13 +75,11 @@ public NodePair swap() { @Override public String toString() { - return new StringBuilder() - .append('[') - .append(a.getId()) - .append(',') - .append(b.getId()) - .append(']') - .toString(); + return "[" + + a.getId() + + ',' + + b.getId() + + ']'; } /** diff --git a/src/org/openstreetmap/josm/data/osm/visitor/paint/StyledMapRenderer.java b/src/org/openstreetmap/josm/data/osm/visitor/paint/StyledMapRenderer.java index b27acb4bc5b..c003bab88b8 100644 --- a/src/org/openstreetmap/josm/data/osm/visitor/paint/StyledMapRenderer.java +++ b/src/org/openstreetmap/josm/data/osm/visitor/paint/StyledMapRenderer.java @@ -124,29 +124,29 @@ public static class StyleRecord implements Comparable { this.osm = osm; this.flags = flags; - long order = 0; + long styleOrder = 0; if ((this.flags & FLAG_DISABLED) == 0) { - order |= 1; + styleOrder |= 1; } - order <<= 24; - order |= floatToFixed(this.style.majorZIndex, 24); + styleOrder <<= 24; + styleOrder |= floatToFixed(this.style.majorZIndex, 24); // selected on top of member of selected on top of unselected // FLAG_DISABLED bit is the same at this point, but we simply ignore it - order <<= 4; - order |= this.flags & 0xf; + styleOrder <<= 4; + styleOrder |= this.flags & 0xf; - order <<= 24; - order |= floatToFixed(this.style.zIndex, 24); + styleOrder <<= 24; + styleOrder |= floatToFixed(this.style.zIndex, 24); - order <<= 1; + styleOrder <<= 1; // simple node on top of icons and shapes if (DefaultStyles.SIMPLE_NODE_ELEMSTYLE.equals(this.style)) { - order |= 1; + styleOrder |= 1; } - this.order = order; + this.order = styleOrder; } /** @@ -244,15 +244,15 @@ public String toString() { /** * Check, if this System has the GlyphVector double translation bug. - * + *

* With this bug, gv.setGlyphTransform(i, trfm) has a different * effect than on most other systems, namely the translation components * ("m02" & "m12", {@link AffineTransform}) appear to be twice as large, as * they actually are. The rotation is unaffected (scale & shear not tested * so far). - * + *

* This bug has only been observed on Mac OS X, see #7841. - * + *

* After switch to Java 7, this test is a false positive on Mac OS X (see #10446), * i.e. it returns true, but the real rendering code does not require any special * handling. @@ -585,7 +585,7 @@ public void drawArea(IWay w, Color color, MapImage fillImage, Float extent, F /** * Determine, if partial fill should be turned off for this object, because * only a small unfilled gap in the center of the area would be left. - * + *

* This is used to get a cleaner look for urban regions with many small * areas like buildings, etc. * @param ap the area and the perimeter of the object @@ -622,7 +622,7 @@ public void drawBoxText(INode n, BoxTextElement bs) { double x = p.getInViewX() + bs.xOffset; double y = p.getInViewY() + bs.yOffset; - /** + /* * * left-above __center-above___ right-above * left-top| |right-top @@ -1016,7 +1016,7 @@ public void drawRestriction(IRelation r, MapImage icon, boolean disabled) { IWay viaWay = (IWay) via; INode firstNode = viaWay.firstNode(); INode lastNode = viaWay.lastNode(); - Boolean onewayvia = Boolean.FALSE; + boolean onewayvia = Boolean.FALSE; String onewayviastr = viaWay.get("oneway"); if (onewayviastr != null) { @@ -1422,7 +1422,7 @@ public void getSettings(boolean virtual) { showIcons = paintSettings.getShowIconsDistance() > circum; isOutlineOnly = paintSettings.isOutlineOnly(); - antialiasing = PREFERENCE_ANTIALIASING_USE.get() ? + antialiasing = Boolean.TRUE.equals(PREFERENCE_ANTIALIASING_USE.get()) ? RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, antialiasing); @@ -1483,12 +1483,12 @@ private static Path2D.Double getPFClip(PolyData pd, double extent) { /** * Fix the clipping area of unclosed polygons for partial fill. - * + *

* The current algorithm for partial fill simply strokes the polygon with a * large stroke width after masking the outside with a clipping area. * This works, but for unclosed polygons, the mask can crop the corners at * both ends (see #12104). - * + *

* This method fixes the clipping area by sort of adding the corners to the * clip outline. * @@ -1531,7 +1531,7 @@ private static void buildPFClip(Path2D.Double clip, List nodes, /** * Get the point to add to the clipping area for partial fill of unclosed polygons. - * + *

* (p1,p2) is the first or last way segment and p3 the * opposite endpoint. * @@ -1692,8 +1692,8 @@ private void paintWithLock(final OsmData data, boolean renderVirtual return; } - for (StyleRecord record : sorted) { - paintRecord(record); + for (StyleRecord styleRecord : sorted) { + paintRecord(styleRecord); } drawVirtualNodes(data, bbox); @@ -1709,11 +1709,11 @@ private void paintWithLock(final OsmData data, boolean renderVirtual } } - private void paintRecord(StyleRecord record) { + private void paintRecord(StyleRecord styleRecord) { try { - record.paintPrimitive(paintSettings, this); + styleRecord.paintPrimitive(paintSettings, this); } catch (RuntimeException e) { - throw BugReport.intercept(e).put("record", record); + throw BugReport.intercept(e).put("record", styleRecord); } } } diff --git a/src/org/openstreetmap/josm/data/projection/datum/NTV2SubGrid.java b/src/org/openstreetmap/josm/data/projection/datum/NTV2SubGrid.java index 8d598d250ca..9d3f66d3040 100644 --- a/src/org/openstreetmap/josm/data/projection/datum/NTV2SubGrid.java +++ b/src/org/openstreetmap/josm/data/projection/datum/NTV2SubGrid.java @@ -310,30 +310,28 @@ public String toString() { * @return textual details about the sub grid */ public String getDetails() { - return new StringBuilder(256) - .append("Sub Grid : ") - .append(subGridName) - .append("\nParent : ") - .append(parentSubGridName) - .append("\nCreated : ") - .append(created) - .append("\nUpdated : ") - .append(updated) - .append("\nMin Lat : ") - .append(minLat) - .append("\nMax Lat : ") - .append(maxLat) - .append("\nMin Lon : ") - .append(minLon) - .append("\nMax Lon : ") - .append(maxLon) - .append("\nLat Intvl: ") - .append(latInterval) - .append("\nLon Intvl: ") - .append(lonInterval) - .append("\nNode Cnt : ") - .append(nodeCount) - .toString(); + return "Sub Grid : " + + subGridName + + "\nParent : " + + parentSubGridName + + "\nCreated : " + + created + + "\nUpdated : " + + updated + + "\nMin Lat : " + + minLat + + "\nMax Lat : " + + maxLat + + "\nMin Lon : " + + minLon + + "\nMax Lon : " + + maxLon + + "\nLat Intvl: " + + latInterval + + "\nLon Intvl: " + + lonInterval + + "\nNode Cnt : " + + nodeCount; } /** diff --git a/src/org/openstreetmap/josm/data/sources/SourceInfo.java b/src/org/openstreetmap/josm/data/sources/SourceInfo.java index de08441aba0..1829f18666c 100644 --- a/src/org/openstreetmap/josm/data/sources/SourceInfo.java +++ b/src/org/openstreetmap/josm/data/sources/SourceInfo.java @@ -85,7 +85,7 @@ public class SourceInfo, U extends ISourceType, /** * creation date of the source (in the form YYYY-MM-DD;YYYY-MM-DD, where * DD and MM as well as a second date are optional). - * + *

* Also used as time filter for WMS time={time} parameter (such as Sentinel-2) * @since 11570 */ @@ -105,7 +105,7 @@ public class SourceInfo, U extends ISourceType, protected T category; /** category of the imagery (input string, not saved, copied or used otherwise except for error checks) */ protected String categoryOriginalString; - /** when adding a field, also adapt the: + /* when adding a field, also adapt the: * {@link #ImageryPreferenceEntry ImageryPreferenceEntry object} * {@link #ImageryPreferenceEntry#ImageryPreferenceEntry(ImageryInfo) ImageryPreferenceEntry constructor} * {@link #ImageryInfo(ImageryPreferenceEntry) ImageryInfo constructor} @@ -148,7 +148,7 @@ public int hashCode() { /** * Check if this object equals another SourceInfo with respect to the properties * that get written to the preference file. - * + *

* This should be overridden and called in subclasses. * * @param other the SourceInfo object to compare to @@ -218,13 +218,12 @@ public static String getLocalizedCountry(String countryCode) { @Override public String toString() { // Used in imagery preferences filtering, so must be efficient - return new StringBuilder(name) - .append('[').append(countryCode) + return name + + '[' + countryCode + // appending the localized country in toString() allows us to filter imagery preferences table with it! - .append("] ('").append(getLocalizedCountry(countryCode)).append(')') - .append(" - ").append(url) - .append(" - ").append(sourceType) - .toString(); + "] ('" + getLocalizedCountry(countryCode) + ')' + + " - " + url + + " - " + sourceType; } @Override diff --git a/src/org/openstreetmap/josm/data/validation/tests/Addresses.java b/src/org/openstreetmap/josm/data/validation/tests/Addresses.java index 6dffd3cbb16..4f1fc1e50f7 100644 --- a/src/org/openstreetmap/josm/data/validation/tests/Addresses.java +++ b/src/org/openstreetmap/josm/data/validation/tests/Addresses.java @@ -427,7 +427,7 @@ protected void checkDistance(OsmPrimitive house, Collection street) { private void checkIfObsolete(Relation r) { if (r.isIncomplete()) return; - /** array of country codes for which the test should be performed. For now, only Germany */ + /* array of country codes for which the test should be performed. For now, only Germany */ String[] countryCodes = {"DE"}; TagMap neededtagsForHouse = new TagMap(); for (Entry tag : r.getKeys().entrySet()) { diff --git a/src/org/openstreetmap/josm/data/validation/tests/MultipolygonTest.java b/src/org/openstreetmap/josm/data/validation/tests/MultipolygonTest.java index e92d557c2ec..99bd1a93dbe 100644 --- a/src/org/openstreetmap/josm/data/validation/tests/MultipolygonTest.java +++ b/src/org/openstreetmap/josm/data/validation/tests/MultipolygonTest.java @@ -601,9 +601,9 @@ private void findIntersectingWaysIncomplete(Relation r) { * @return map with crossing ways and the related segments */ private static Map, List> findIntersectingWays(Relation r, boolean findSharedWaySegments) { - /** All way segments, grouped by cells */ + /* All way segments, grouped by cells */ final Map> cellSegments = new HashMap<>(1000); - /** The detected crossing ways */ + /* The detected crossing ways */ final Map, List> crossingWays = new HashMap<>(50); for (Way w: r.getMemberPrimitives(Way.class)) { diff --git a/src/org/openstreetmap/josm/data/validation/tests/PowerLines.java b/src/org/openstreetmap/josm/data/validation/tests/PowerLines.java index c03dcdec61b..05da44e6cf2 100644 --- a/src/org/openstreetmap/josm/data/validation/tests/PowerLines.java +++ b/src/org/openstreetmap/josm/data/validation/tests/PowerLines.java @@ -568,6 +568,7 @@ SegmentInfo getLongestSegment() { } /** + * Get the detected segments * @return the detected segments */ List getSegments() { diff --git a/src/org/openstreetmap/josm/data/validation/tests/UnconnectedWays.java b/src/org/openstreetmap/josm/data/validation/tests/UnconnectedWays.java index 79a897da122..8fb5cd97fad 100644 --- a/src/org/openstreetmap/josm/data/validation/tests/UnconnectedWays.java +++ b/src/org/openstreetmap/josm/data/validation/tests/UnconnectedWays.java @@ -460,7 +460,7 @@ boolean isConnectedTo(Node startNode) { * @param parent the previous parent way * @return true if a reasonable connection was found */ - private boolean isConnectedTo(Node node, LinkedHashSet visited, double len, Way parent) { + private boolean isConnectedTo(Node node, Set visited, double len, Way parent) { if (len > maxLen) { return false; } @@ -479,7 +479,7 @@ private boolean isConnectedTo(Node node, LinkedHashSet visited, double len } if (visited != null) { visited.add(node); - List wantedParents = node.getParentWays().stream().filter(pw -> isWantedWay(pw)) + List wantedParents = node.getParentWays().stream().filter(UnconnectedWays.this::isWantedWay) .collect(Collectors.toList()); if (wantedParents.size() > 1 && wantedParents.indexOf(parent) != wantedParents.size() - 1) { // we want to find a different way. so move known way to the end of the list diff --git a/src/org/openstreetmap/josm/gui/MapFrame.java b/src/org/openstreetmap/josm/gui/MapFrame.java index d266c430116..95b47ce9ebd 100644 --- a/src/org/openstreetmap/josm/gui/MapFrame.java +++ b/src/org/openstreetmap/josm/gui/MapFrame.java @@ -214,12 +214,12 @@ public MapFrame(ViewportData viewportData) { dialogsPanel = new DialogsPanel(splitPane); splitPane.setRightComponent(dialogsPanel); - /** + /* * All additional space goes to the mapView */ splitPane.setResizeWeight(1.0); - /** + /* * Some beautifications. */ splitPane.setDividerSize(5); @@ -514,7 +514,7 @@ public boolean selectMapMode(MapMode newMapMode, Layer newLayer) { public void fillPanel(Container panel) { panel.add(this, BorderLayout.CENTER); - /** + /* * sideToolBar: add map modes icons */ if (Config.getPref().getBoolean("sidetoolbar.mapmodes.visible", true)) { @@ -525,7 +525,7 @@ public void fillPanel(Container panel) { sideToolBar.add(listAllMapModesAction.createButton()); } - /** + /* * sideToolBar: add toggle dialogs icons */ if (Config.getPref().getBoolean("sidetoolbar.toggledialogs.visible", true)) { @@ -537,30 +537,29 @@ public void fillPanel(Container panel) { sideToolBar.add(listAllDialogsAction.createButton()); } - /** + /* * sideToolBar: add dynamic popup menu */ sideToolBar.setComponentPopupMenu(new SideToolbarPopupMenu()); ((JToolBar) sideToolBar).setFloatable(false); sideToolBar.setBorder(BorderFactory.createEmptyBorder(0, 1, 0, 1)); - /** + /* * sideToolBar: decide scroll- and visibility */ if (Config.getPref().getBoolean("sidetoolbar.scrollable", true)) { - final ScrollViewport svp = new ScrollViewport(sideToolBar, ScrollViewport.VERTICAL_DIRECTION); - sideToolBar = svp; + sideToolBar = new ScrollViewport(sideToolBar, ScrollViewport.VERTICAL_DIRECTION); } sideToolBar.setVisible(SIDE_TOOLBAR_VISIBLE.get()); sidetoolbarPreferencesChangedListener = e -> sideToolBar.setVisible(e.getProperty().get()); SIDE_TOOLBAR_VISIBLE.addListener(sidetoolbarPreferencesChangedListener); - /** + /* * sideToolBar: add it to the panel */ panel.add(sideToolBar, BorderLayout.WEST); - /** + /* * statusLine: add to panel */ if (statusLine != null && Config.getPref().getBoolean("statusline.visible", true)) { diff --git a/src/org/openstreetmap/josm/gui/NavigatableComponent.java b/src/org/openstreetmap/josm/gui/NavigatableComponent.java index e9202d42584..228d1a9e8e4 100644 --- a/src/org/openstreetmap/josm/gui/NavigatableComponent.java +++ b/src/org/openstreetmap/josm/gui/NavigatableComponent.java @@ -44,6 +44,7 @@ import org.openstreetmap.josm.data.osm.BBox; import org.openstreetmap.josm.data.osm.DataSet; import org.openstreetmap.josm.data.osm.IPrimitive; +import org.openstreetmap.josm.data.osm.IWaySegment; import org.openstreetmap.josm.data.osm.Node; import org.openstreetmap.josm.data.osm.OsmPrimitive; import org.openstreetmap.josm.data.osm.Relation; @@ -208,14 +209,14 @@ private void updateHoveredPrimitive(IPrimitive hovered, MouseEvent e) { // The only events that may move/resize this map view are window movements or changes to the map view size. // We can clean this up more by only recalculating the state on repaint. - private final transient HierarchyListener hierarchyListener = e -> { + private final transient HierarchyListener hierarchyListenerNavigatableComponent = e -> { long interestingFlags = HierarchyEvent.ANCESTOR_MOVED | HierarchyEvent.SHOWING_CHANGED; if ((e.getChangeFlags() & interestingFlags) != 0) { updateLocationState(); } }; - private final transient ComponentAdapter componentListener = new ComponentAdapter() { + private final transient ComponentAdapter componentListenerNavigatableComponent = new ComponentAdapter() { @Override public void componentShown(ComponentEvent e) { updateLocationState(); @@ -253,16 +254,16 @@ public NavigatableComponent() { @Override public void addNotify() { updateLocationState(); - addHierarchyListener(hierarchyListener); - addComponentListener(componentListener); + addHierarchyListener(hierarchyListenerNavigatableComponent); + addComponentListener(componentListenerNavigatableComponent); addPrimitiveHoverMouseListeners(); super.addNotify(); } @Override public void removeNotify() { - removeHierarchyListener(hierarchyListener); - removeComponentListener(componentListener); + removeHierarchyListener(hierarchyListenerNavigatableComponent); + removeComponentListener(componentListenerNavigatableComponent); removePrimitiveHoverMouseListeners(); super.removeNotify(); } @@ -289,7 +290,7 @@ public void setNativeScaleLayer(NativeScaleLayer nativeScaleLayer) { /** * Replies the layer which scale is set to. - * @return the current scale layer (may be null) + * @return the current scale layer (may be {@code null}) */ public NativeScaleLayer getNativeScaleLayer() { return nativeScaleLayer; @@ -323,7 +324,7 @@ public double scaleZoomManyTimes(int times) { if (nativeScaleLayer != null) { ScaleList scaleList = nativeScaleLayer.getNativeScales(); if (scaleList != null) { - if (PROP_ZOOM_INTERMEDIATE_STEPS.get()) { + if (Boolean.TRUE.equals(PROP_ZOOM_INTERMEDIATE_STEPS.get())) { scaleList = scaleList.withIntermediateSteps(PROP_ZOOM_RATIO.get()); } Scale s = scaleList.scaleZoomTimes(getScale(), PROP_ZOOM_RATIO.get(), times); @@ -365,7 +366,7 @@ public double scaleSnap(double scale, boolean floor) { if (nativeScaleLayer != null) { ScaleList scaleList = nativeScaleLayer.getNativeScales(); if (scaleList != null) { - if (PROP_ZOOM_INTERMEDIATE_STEPS.get()) { + if (Boolean.TRUE.equals(PROP_ZOOM_INTERMEDIATE_STEPS.get())) { scaleList = scaleList.withIntermediateSteps(PROP_ZOOM_RATIO.get()); } Scale snapscale = scaleList.getSnapScale(scale, PROP_ZOOM_RATIO.get(), floor); @@ -477,7 +478,7 @@ public double getDist100Pixel(boolean alwaysPositive) { /** * Returns the current center of the viewport. - * + *

* (Use {@link #zoomTo(EastNorth)} to the change the center.) * * @return the current center of the viewport @@ -488,7 +489,7 @@ public EastNorth getCenter() { /** * Returns the current scale. - * + *

* In east/north units per pixel. * * @return the current scale @@ -589,7 +590,7 @@ public Point2D getPoint2D(EastNorth p) { /** * Return the point on the screen where this Coordinate would be. - * + *

* Alternative: {@link #getState()}, then {@link MapViewState#getPointFor(ILatLon)} * @param latlon The point, where this geopoint would be drawn. * @return The point on screen where "point" would be drawn, relative to the own top/left. @@ -604,7 +605,7 @@ public Point2D getPoint2D(ILatLon latlon) { /** * Return the point on the screen where this Coordinate would be. - * + *

* Alternative: {@link #getState()}, then {@link MapViewState#getPointFor(ILatLon)} * @param latlon The point, where this geopoint would be drawn. * @return The point on screen where "point" would be drawn, relative to the own top/left. @@ -615,7 +616,7 @@ public Point2D getPoint2D(LatLon latlon) { /** * Return the point on the screen where this Node would be. - * + *

* Alternative: {@link #getState()}, then {@link MapViewState#getPointFor(ILatLon)} * @param n The node, where this geopoint would be drawn. * @return The point on screen where "node" would be drawn, relative to the own top/left. @@ -826,9 +827,7 @@ public void run() { try { for (int i = 0; i < frames && !doStop; i++) { final EastNorth z = oldCenter.interpolate(finalNewCenter, (1.0+i) / frames); - GuiHelper.runInEDTAndWait(() -> { - zoomTo(z); - }); + GuiHelper.runInEDTAndWait(() -> zoomTo(z)); Thread.sleep(sleepTime); } } catch (InterruptedException ex) { @@ -1108,8 +1107,7 @@ public final List getNearestNodes(Point p, if (minDistSq == null) { if (!nlist.isEmpty()) { minDistSq = distSq; - nearestList = new ArrayList<>(); - nearestList.addAll(nlist); + nearestList = new ArrayList<>(nlist); } } else { if (distSq-minDistSq < 16) { @@ -1140,16 +1138,16 @@ public final List getNearestNodes(Point p, Predicate predica /** * The *result* depends on the current map selection state IF use_selected is true. - * + *

* If more than one node within node.snap-distance pixels is found, * the nearest node selected is returned IF use_selected is true. - * + *

* Else the nearest new/id=0 node within about the same distance * as the true nearest node is returned. - * + *

* If no such node is found either, the true nearest node to p is returned. - * - * Finally, if a node is not found at all, null is returned. + *

+ * Finally, if a node is not found at all, {@code null} is returned. * * @param p the screen point * @param predicate this parameter imposes a condition on the returned object, e.g. @@ -1164,18 +1162,18 @@ public final Node getNearestNode(Point p, Predicate predicate, boo /** * The *result* depends on the current map selection state IF use_selected is true - * + *

* If more than one node within node.snap-distance pixels is found, * the nearest node selected is returned IF use_selected is true. - * + *

* If there are no selected nodes near that point, the node that is related to some of the preferredRefs - * + *

* Else the nearest new/id=0 node within about the same distance * as the true nearest node is returned. - * + *

* If no such node is found either, the true nearest node to p is returned. - * - * Finally, if a node is not found at all, null is returned. + *

+ * Finally, if a node is not found at all, {@code null} is returned. * * @param p the screen point * @param predicate this parameter imposes a condition on the returned object, e.g. @@ -1288,11 +1286,11 @@ private Map> getNearestWaySegmentsImpl(Point p, Predica /* perpendicular distance squared * loose some precision to account for possible deviations in the calculation above * e.g. if identical (A and B) come about reversed in another way, values may differ - * -- zero out least significant 32 dual digits of mantissa.. + * -- zero out least significant 32 dual digits of mantissa. */ double perDistSq = Double.longBitsToDouble( Double.doubleToLongBits(a - (a - b + c) * (a - b + c) / 4 / c) - >> 32 << 32); // resolution in numbers with large exponent not needed here.. + >> 32 << 32); // resolution in numbers with large exponent not needed here. if (perDistSq < snapDistanceSq && a < c + snapDistanceSq && b < c + snapDistanceSq) { nearestMap.computeIfAbsent(perDistSq, k -> new LinkedList<>()).add(new WaySegment(w, i)); @@ -1461,7 +1459,7 @@ public final List getNearestWays(Point p, List nearestList = getNearestWaySegmentsImpl(p, predicate).values().stream() .flatMap(Collection::stream) .filter(ws -> wset.add(ws.getWay())) - .map(ws -> ws.getWay()) + .map(IWaySegment::getWay) .collect(Collectors.toList()); if (ignore != null) { nearestList.removeAll(ignore); @@ -1503,13 +1501,13 @@ public final Way getNearestWay(Point p, Predicate predicate) { * The *result* does not depend on the current map selection state, * neither does the result *order*. * It solely depends on the distance to point p. - * + *

* First, nodes will be searched. If there are nodes within BBox found, * return a collection of those nodes only. - * + *

* If no nodes are found, search for nearest ways. If there are ways * within BBox found, return a collection of those ways only. - * + *

* If nothing is found, return an empty collection. * * @param p The point on screen. @@ -1573,18 +1571,18 @@ private boolean isPrecedenceNode(Node osm, Point p, boolean useSelected) { /** * The *result* depends on the current map selection state IF use_selected is true. - * + *

* IF use_selected is true, use {@link #getNearestNode(Point, Predicate)} to find * the nearest, selected node. If not found, try {@link #getNearestWaySegment(Point, Predicate)} * to find the nearest selected way. - * + *

* IF use_selected is false, or if no selected primitive was found, do the following. - * + *

* If the nearest node found is within 4px of p, simply take it. * Else, find the nearest way segment. Then, if p is closer to its * middle than to the node, take the way segment, else take the node. - * - * Finally, if no nearest primitive is found at all, return null. + *

+ * Finally, if no nearest primitive is found at all, return {@code null}. * * @param p The point on screen. * @param predicate the returned object has to fulfill certain properties. @@ -1636,7 +1634,7 @@ public final OsmPrimitive getNearestNodeOrWay(Point p, Predicate p /** * if r = 0 returns a, if r=1 returns b, - * if r = 0.5 returns center between a and b, etc.. + * if r = 0.5 returns center between a and b, etc. * * @param r scale value * @param a root of vector @@ -1672,7 +1670,7 @@ public final List getAllNearest(Point p, List nearestList = getNearestWaySegmentsImpl(p, predicate).values().stream() .flatMap(Collection::stream) .filter(ws -> wset.add(ws.getWay())) - .map(ws -> ws.getWay()) + .map(IWaySegment::getWay) .collect(Collectors.toList()); // add nearby nodes @@ -1723,17 +1721,17 @@ public String helpTopic() { } /** - * Return a ID which is unique as long as viewport dimensions are the same + * Return an ID which is unique as long as viewport dimensions are the same * @return A unique ID, as long as viewport dimensions are the same */ public int getViewID() { EastNorth center = getCenter(); - String x = new StringBuilder().append(center.east()) - .append('_').append(center.north()) - .append('_').append(getScale()) - .append('_').append(getWidth()) - .append('_').append(getHeight()) - .append('_').append(getProjection()).toString(); + String x = String.valueOf(center.east()) + + '_' + center.north() + + '_' + getScale() + + '_' + getWidth() + + '_' + getHeight() + + '_' + getProjection(); CRC32 id = new CRC32(); id.update(x.getBytes(StandardCharsets.UTF_8)); return (int) id.getValue(); diff --git a/src/org/openstreetmap/josm/gui/bbox/SlippyMapBBoxChooser.java b/src/org/openstreetmap/josm/gui/bbox/SlippyMapBBoxChooser.java index 37c72e22c71..491d63bee71 100644 --- a/src/org/openstreetmap/josm/gui/bbox/SlippyMapBBoxChooser.java +++ b/src/org/openstreetmap/josm/gui/bbox/SlippyMapBBoxChooser.java @@ -12,6 +12,7 @@ import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.Collectors; @@ -146,7 +147,7 @@ public SlippyMapBBoxChooser() { new SlippyMapController(this, this); } - private static LinkedHashMap getAllTileSources() { + private static Map getAllTileSources() { // using a LinkedHashMap of to retain ordering but provide deduplication return providers.stream().flatMap( provider -> provider.getTileSources().stream() @@ -365,7 +366,7 @@ public void setSizeButtonVisible(boolean visible) { * @since 6364 */ public final void refreshTileSources() { - final LinkedHashMap newTileSources = getAllTileSources(); + final Map newTileSources = getAllTileSources(); final TileSource currentTileSource = this.getTileController().getTileSource(); // re-add the currently active TileSource to prevent inconsistent display of menu diff --git a/src/org/openstreetmap/josm/gui/conflict/pair/relation/RelationMemberListMergeModel.java b/src/org/openstreetmap/josm/gui/conflict/pair/relation/RelationMemberListMergeModel.java index 72efcde3b29..c021cc85891 100644 --- a/src/org/openstreetmap/josm/gui/conflict/pair/relation/RelationMemberListMergeModel.java +++ b/src/org/openstreetmap/josm/gui/conflict/pair/relation/RelationMemberListMergeModel.java @@ -34,13 +34,10 @@ protected void buildMergedEntriesTableModel() { // the table model for merged entries is different because it supports // editing cells in the first column // - mergedEntriesTableModel = this.new EntriesTableModel(ListRole.MERGED_ENTRIES) { + mergedEntriesTableModel = new EntriesTableModel(ListRole.MERGED_ENTRIES) { @Override public boolean isCellEditable(int row, int column) { - switch(column) { - case 1: return true; - default: return false; - } + return column == 1; } }; } diff --git a/src/org/openstreetmap/josm/gui/dialogs/DialogsPanel.java b/src/org/openstreetmap/josm/gui/dialogs/DialogsPanel.java index c0916c9b4ba..66a2b88b197 100644 --- a/src/org/openstreetmap/josm/gui/dialogs/DialogsPanel.java +++ b/src/org/openstreetmap/josm/gui/dialogs/DialogsPanel.java @@ -174,7 +174,7 @@ public void reconstruct(Action action, ToggleDialog triggeredBy) { final int n = allDialogs.size(); - /** + /* * reset the panels */ for (JPanel p: panels) { @@ -182,7 +182,7 @@ public void reconstruct(Action action, ToggleDialog triggeredBy) { p.setVisible(false); } - /** + /* * Add the elements to their respective panel. * * Each panel contains one dialog in default view and zero or more @@ -215,7 +215,7 @@ public void reconstruct(Action action, ToggleDialog triggeredBy) { } final int numPanels = n - k; - /** + /* * Determine the panel geometry */ if (action == Action.RESTORE_SAVED || action == Action.ELEMENT_SHRINKS) { @@ -244,7 +244,7 @@ public void reconstruct(Action action, ToggleDialog triggeredBy) { } } - /** + /* * If we add additional dialogs on startup (e.g. geoimage), they may * not have an actual height yet. * In this case we simply reset everything to it's preferred size. @@ -254,23 +254,23 @@ public void reconstruct(Action action, ToggleDialog triggeredBy) { return; } - /** total Height */ + /* total Height */ final int h = mSpltPane.getMultiSplitLayout().getModel().getBounds().getSize().height; - /** space, that is available for dialogs in default view (after the reconfiguration) */ + /* space, that is available for dialogs in default view (after the reconfiguration) */ final int s2 = h - (numPanels - 1) * DIVIDER_SIZE - sumC; final int hpTrig = triggeredBy.getPreferredHeight(); if (hpTrig <= 0) throw new IllegalStateException(); // Must be positive - /** The new dialog gets a fair share */ + /* The new dialog gets a fair share */ final int hnTrig = hpTrig * s2 / (hpTrig + sumP); triggeredBy.setPreferredSize(new Dimension(Integer.MAX_VALUE, hnTrig)); - /** This is remaining for the other default view dialogs */ + /* This is remaining for the other default view dialogs */ final int r = s2 - hnTrig; - /** + /* * Take space only from dialogs that are relatively large */ int dm = 0; // additional space needed by the small dialogs @@ -288,7 +288,7 @@ public void reconstruct(Action action, ToggleDialog triggeredBy) { } } } - /** adjust, without changing the sum */ + /* adjust, without changing the sum */ for (final ToggleDialog dlg : allDialogs) { if (dlg != triggeredBy && dlg.isDialogInDefaultView()) { final int ha = dlg.getHeight(); @@ -305,7 +305,7 @@ public void reconstruct(Action action, ToggleDialog triggeredBy) { } } - /** + /* * create Layout */ final List ch = new ArrayList<>(); @@ -333,7 +333,7 @@ public void reconstruct(Action action, ToggleDialog triggeredBy) { mSpltPane.getMultiSplitLayout().setFloatingDividers(true); mSpltPane.revalidate(); - /** + /* * Hide the Panel, if there is nothing to show */ if (numPanels == 1 && panels.get(n-1).getComponents().length == 0) { diff --git a/src/org/openstreetmap/josm/gui/dialogs/ToggleDialog.java b/src/org/openstreetmap/josm/gui/dialogs/ToggleDialog.java index 085540514d2..5c1b5fa3e7c 100644 --- a/src/org/openstreetmap/josm/gui/dialogs/ToggleDialog.java +++ b/src/org/openstreetmap/josm/gui/dialogs/ToggleDialog.java @@ -255,9 +255,9 @@ public ToggleDialog(String name, String iconName, String tooltip, Shortcut short this.name = name; this.preferenceClass = prefClass; - /** Use the full width of the parent element */ + /* Use the full width of the parent element */ setPreferredSize(new Dimension(0, preferredHeight)); - /** Override any minimum sizes of child elements so the user can resize freely */ + /* Override any minimum sizes of child elements so the user can resize freely */ setMinimumSize(new Dimension(0, 0)); this.preferredHeight = Config.getPref().getInt(preferencePrefix+".preferredHeight", preferredHeight); toggleAction = new ToggleDialogAction(name, "dialogs/"+iconName, tooltip, shortcut, helpTopic()); @@ -267,7 +267,7 @@ public ToggleDialog(String name, String iconName, String tooltip, Shortcut short isCollapsed = Config.getPref().getBoolean(preferencePrefix+".minimized", false); buttonHiding = propButtonHiding.get(); - /** show the minimize button */ + /* show the minimize button */ titleBar = new TitleBar(name, iconName); add(titleBar, BorderLayout.NORTH); @@ -292,7 +292,7 @@ protected void registerInWindowMenu(boolean isExpert) { /** * The action to toggle the visibility state of this toggle dialog. - * + *

* Emits {@link PropertyChangeEvent}s for the property selected: *

    *
  • true, if the dialog is currently visible
  • @@ -381,7 +381,7 @@ public void unfurlDialog() { @Override public void buttonHidden() { - if ((Boolean) toggleAction.getValue("selected")) { + if (Boolean.TRUE.equals(toggleAction.getValue("selected"))) { toggleAction.actionPerformed(null); } } @@ -596,9 +596,7 @@ public void paintComponent(Graphics g) { // show the help button addButton(new JButton(ImageProvider.get("help", ImageProvider.ImageSizes.SMALLICON)), - tr("Open help for this panel"), e -> { - HelpBrowser.setUrlForHelpTopic(helpTopic()); - }); + tr("Open help for this panel"), e -> HelpBrowser.setUrlForHelpTopic(helpTopic())); // show the sticky button addButton(new JButton(ImageProvider.get("misc", "sticky")), tr("Undock the panel"), e -> { @@ -966,13 +964,13 @@ protected final Component createLayout(Component data, boolean scroll, Collectio final JPanel buttonRowPanel = new JPanel(Config.getPref().getBoolean("dialog.align.left", false) ? new FlowLayout(FlowLayout.LEFT) : new GridLayout(1, buttonRow.size())); buttonsPanel.add(buttonRowPanel); - for (SideButton button : buttonRow) { - buttonRowPanel.add(button); - javax.swing.Action action = button.getAction(); + for (SideButton sideButton : buttonRow) { + buttonRowPanel.add(sideButton); + javax.swing.Action action = sideButton.getAction(); if (action != null) { buttonActions.add(action); } else { - Logging.warn("Button " + button + " doesn't have action defined"); + Logging.warn("Button " + sideButton + " doesn't have action defined"); Logging.error(new Exception()); } } diff --git a/src/org/openstreetmap/josm/gui/dialogs/relation/sort/RelationSortUtils.java b/src/org/openstreetmap/josm/gui/dialogs/relation/sort/RelationSortUtils.java index dbd6b9b4bb7..1bf6a5ae734 100644 --- a/src/org/openstreetmap/josm/gui/dialogs/relation/sort/RelationSortUtils.java +++ b/src/org/openstreetmap/josm/gui/dialogs/relation/sort/RelationSortUtils.java @@ -46,8 +46,8 @@ static > Direction roundaboutType(W w) { INode n2 = w.getNode(1); INode n3 = w.getNode(2); if (n1 != null && n2 != null && n3 != null && w.isClosed()) { - /** do some simple determinant / cross product test on the first 3 nodes - to see, if the roundabout goes clock wise or ccw */ + /* do some simple determinant / cross product test on the first 3 nodes + to see, if the roundabout goes clock wise or ccw */ EastNorth en1 = n1.getEastNorth(); EastNorth en2 = n2.getEastNorth(); EastNorth en3 = n3.getEastNorth(); diff --git a/src/org/openstreetmap/josm/gui/dialogs/relation/sort/WayConnectionTypeCalculator.java b/src/org/openstreetmap/josm/gui/dialogs/relation/sort/WayConnectionTypeCalculator.java index b1c79d6b512..0cdf1bbf8d4 100644 --- a/src/org/openstreetmap/josm/gui/dialogs/relation/sort/WayConnectionTypeCalculator.java +++ b/src/org/openstreetmap/josm/gui/dialogs/relation/sort/WayConnectionTypeCalculator.java @@ -6,8 +6,8 @@ import static org.openstreetmap.josm.gui.dialogs.relation.sort.WayConnectionType.Direction.NONE; import java.util.ArrayList; +import java.util.Collections; import java.util.List; -import java.util.stream.Collectors; import org.openstreetmap.josm.data.osm.Node; import org.openstreetmap.josm.data.osm.Relation; @@ -44,9 +44,7 @@ public List updateLinks(List members) { */ public List updateLinks(Relation r, List members) { this.members = members; - final List con = members.stream() - .map(ignore -> (WayConnectionType) null) - .collect(Collectors.toList()); + final List con = new ArrayList<>(Collections.nCopies(members.size(), null)); firstGroupIdx = 0; @@ -164,7 +162,7 @@ private WayConnectionType computeNextWayConnection(Relation r, List * If both ways are not linked in any way, NONE is returned. - * + *

    * Else the direction is given as follows: * Let the relation be a route of oneway streets, and someone travels them in the given order. * Direction is FORWARD if it is legal and BACKWARD if it is illegal to do so for the given way. @@ -362,7 +360,7 @@ private Direction determineDirection(int refI, final Direction refDirection, int if (wayRef == null || way == null) return NONE; - /** the list of nodes the way k can dock to */ + /* the list of nodes the way k can dock to */ List refNodes = new ArrayList<>(); switch (refDirection) { @@ -418,7 +416,7 @@ public void clear() { members = null; } - private boolean isConnected(Way way1, Way way2) { + private static boolean isConnected(Way way1, Way way2) { return way1 != null && way2 != null && way1.isUsable() && way2.isUsable() && (way1.isFirstLastNode(way2.firstNode()) || way1.isFirstLastNode(way2.lastNode())); } diff --git a/src/org/openstreetmap/josm/gui/download/OverpassQueryWizardDialog.java b/src/org/openstreetmap/josm/gui/download/OverpassQueryWizardDialog.java index 78810cd4976..1fde2932928 100644 --- a/src/org/openstreetmap/josm/gui/download/OverpassQueryWizardDialog.java +++ b/src/org/openstreetmap/josm/gui/download/OverpassQueryWizardDialog.java @@ -15,6 +15,7 @@ import org.openstreetmap.josm.gui.dialogs.SearchDialog; import org.openstreetmap.josm.gui.download.overpass.OverpassWizardRegistration.OverpassWizardCallbacks; import org.openstreetmap.josm.gui.tagging.ac.AutoCompComboBoxModel; +import org.openstreetmap.josm.gui.widgets.JosmComboBoxModel; import org.openstreetmap.josm.tools.Logging; import org.openstreetmap.josm.tools.SearchCompilerQueryWizard; import org.openstreetmap.josm.tools.UncheckedParseException; @@ -28,7 +29,7 @@ public final class OverpassQueryWizardDialog extends SearchDialog { private static final ListProperty OVERPASS_WIZARD_HISTORY = - new ListProperty("download.overpass.wizard", new ArrayList()); + new ListProperty("download.overpass.wizard", new ArrayList<>()); private final OverpassWizardCallbacks callbacks; // dialog buttons @@ -36,10 +37,10 @@ public final class OverpassQueryWizardDialog extends SearchDialog { private static final int BUILD_AN_EXECUTE_QUERY = 1; private static final int CANCEL = 2; - private AutoCompComboBoxModel model; + private final AutoCompComboBoxModel model; /** preferences reader/writer with automatic transmogrification to and from String */ - private AutoCompComboBoxModel.Preferences prefs; + private final JosmComboBoxModel.Preferences prefs; /** * Create a new {@link OverpassQueryWizardDialog} diff --git a/src/org/openstreetmap/josm/gui/layer/AbstractTileSourceLayer.java b/src/org/openstreetmap/josm/gui/layer/AbstractTileSourceLayer.java index 4b8cbf3bce5..89d48a0f6ee 100644 --- a/src/org/openstreetmap/josm/gui/layer/AbstractTileSourceLayer.java +++ b/src/org/openstreetmap/josm/gui/layer/AbstractTileSourceLayer.java @@ -199,7 +199,7 @@ public void mouseClicked(MouseEvent e) { if (!isVisible()) return; if (e.getButton() == MouseEvent.BUTTON3) { Component component = e.getComponent(); - if (POPUP_MENU_ENABLED.get() && component.isShowing()) { + if (Boolean.TRUE.equals(POPUP_MENU_ENABLED.get()) && component.isShowing()) { new TileSourceLayerPopup(e.getX(), e.getY()).show(component, e.getX(), e.getY()); } } else if (e.getButton() == MouseEvent.BUTTON1) { @@ -421,7 +421,7 @@ private ShowTileInfoAction(AbstractTileSourceLayer layer, Tile tile) { } private static String getSizeString(int size) { - return new StringBuilder().append(size).append('x').append(size).toString(); + return Integer.toString(size) + 'x' + size; } @Override @@ -451,9 +451,9 @@ public void actionPerformed(ActionEvent ae) { content.add(Arrays.asList(tr("Tile size"), getSizeString(tile.getTileSource().getTileSize()))); content.add(Arrays.asList(tr("Tile display size"), - new StringBuilder().append(displaySize.getWidth()) - .append('x') - .append(displaySize.getHeight()).toString())); + Double.toString(displaySize.getWidth()) + + 'x' + + displaySize.getHeight())); if (layer.coordinateConverter.requiresReprojection()) { content.add(Arrays.asList(tr("Reprojection"), tile.getTileSource().getServerCRS() + @@ -560,7 +560,7 @@ public LayerPainter attachToMapView(MapViewEvent event) { event.getMapView().addMouseListener(adapter); MapView.addZoomChangeListener(this); - if (this instanceof NativeScaleLayer && NavigatableComponent.PROP_ZOOM_SCALE_FOLLOW_NATIVE_RES_AT_LOAD.get()) { + if (this instanceof NativeScaleLayer && Boolean.TRUE.equals(NavigatableComponent.PROP_ZOOM_SCALE_FOLLOW_NATIVE_RES_AT_LOAD.get())) { event.getMapView().setNativeScaleLayer((NativeScaleLayer) this); } @@ -639,37 +639,42 @@ protected int estimateTileCacheSize() { if (tileSource != null) { tileSize = tileSource.getTileSize(); } - /** + /* * As we can see part of the tile at the top and at the bottom, use Math.ceil(...) + 1 to accommodate for that */ int maxYtiles = (int) Math.ceil((double) height / tileSize + 1); int maxXtiles = (int) Math.ceil((double) width / tileSize + 1); int visibleTiles = maxXtiles * maxYtiles; - /** - * Take into account ZOOM_OFFSET to calculate real number of tiles and multiply by 7, to cover all tiles, that might be - * accessed when looking for tiles outside current zoom level. - * - * Currently we use otherZooms = {1, 2, -1, -2, -3, -4, -5} - * - * The value should be sum(2^x for x in (-5 to 2)) - 1 - * -1 to exclude current zoom level - * - * Check call to tryLoadFromDifferentZoom - * @see #tryLoadFromDifferentZoom(Graphics2D, int, List,int) - * @see #drawInViewArea((Graphics2D, MapView, ProjectionBounds) - * - * Add +2 to maxYtiles / maxXtiles to add space in cache for extra tiles in current zoom level that are - * download by overloadTiles(). This is not added in computation of visibleTiles as this unnecessarily grow the cache size - * @see #overloadTiles() - */ - int ret = (int) Math.ceil( - Math.pow(2d, ZOOM_OFFSET.get()) * // use offset to decide, how many tiles are visible - visibleTiles * 7 + // 7 to cover tiles from other zooms as described above - ((maxYtiles + 2) * (maxXtiles +2))); // to add as many tiles as they will be accessed on current zoom level + + int ret = calculateRealTiles(visibleTiles, maxXtiles, maxYtiles); Logging.info("AbstractTileSourceLayer: estimated visible tiles: {0}, estimated cache size: {1}", visibleTiles, ret); return ret; } + /** + * Take into account ZOOM_OFFSET to calculate real number of tiles and multiply by 7, to cover all tiles, that might be + * accessed when looking for tiles outside current zoom level. + *

    + * Currently we use otherZooms = {1, 2, -1, -2, -3, -4, -5} + *

    + * The value should be sum(2^x for x in (-5 to 2)) - 1 + * -1 to exclude current zoom level + *

    + * Check call to tryLoadFromDifferentZoom + * @see #tryLoadFromDifferentZoom(Graphics2D, int, List, int) + * @see #drawInViewArea(Graphics2D, MapView, ProjectionBounds) + * + * Add +2 to maxYtiles / maxXtiles to add space in cache for extra tiles in current zoom level that are + * download by overloadTiles(). This is not added in computation of visibleTiles as this unnecessarily grow the cache size + * @see TileSet#overloadTiles() + */ + private static int calculateRealTiles(int visibleTiles, int maxXtiles, int maxYtiles) { + return (int) Math.ceil( + Math.pow(2d, ZOOM_OFFSET.get()) * // use offset to decide, how many tiles are visible + visibleTiles * 7 + // 7 to cover tiles from other zooms as described above + ((maxYtiles + 2) * (maxXtiles +2))); // to add as many tiles as they will be accessed on current zoom level + } + @Override public void displaySettingsChanged(DisplaySettingsChangeEvent e) { if (tileSource == null) { @@ -1324,7 +1329,7 @@ private void loadAllTiles(boolean force) { * Extend tile loading corridor, so that no flickering happens when panning */ private void overloadTiles() { - /** + /* * consult calculation in estimateTileCacheSize() before changing values here. * * @see #estimateTileCacheSize() @@ -1595,7 +1600,7 @@ private void drawInViewArea(Graphics2D g, MapView mv, ProjectionBounds pb) { ts.overloadTiles(); } if (getDisplaySettings().isAutoZoom()) { - /** + /* * consult calculation in estimateTileCacheSize() before changing values here. * * @see #estimateTileCacheSize() @@ -1946,7 +1951,7 @@ public void run() { /** * Calculates tiles, that needs to be downloaded to cache, gets a current tile loader and creates a task to download * all of the tiles. Buffer contains at least one tile. - * + *

    * To prevent accidental clear of the queue, new download executor is created with separate queue * * @param progressMonitor progress monitor for download task diff --git a/src/org/openstreetmap/josm/gui/layer/WMSLayer.java b/src/org/openstreetmap/josm/gui/layer/WMSLayer.java index 540f4d67bba..c329ef815d2 100644 --- a/src/org/openstreetmap/josm/gui/layer/WMSLayer.java +++ b/src/org/openstreetmap/josm/gui/layer/WMSLayer.java @@ -41,7 +41,7 @@ */ public class WMSLayer extends AbstractCachedTileSourceLayer { private static final String PREFERENCE_PREFIX = "imagery.wms"; - /** + /* * Registers all setting properties */ static { @@ -147,9 +147,7 @@ public void projectionChanged(Projection oldValue, Projection newValue) { } private Projection chooseProjection(Projection requested) { - if (serverProjections.contains(requested.toCode())) { - return requested; - } else { + if (!serverProjections.contains(requested.toCode())) { LatLon center = MainApplication.isDisplayingMapView() ? requested.eastNorth2latlon(MainApplication.getMap().mapView.getCenter()) : null; Projection firstNonNullproj = null; @@ -172,8 +170,8 @@ private Projection chooseProjection(Projection requested) { return selectProjection(firstNonNullproj); } Logging.warn(tr("Unable to find supported projection for layer {0}. Using {1}.", getName(), requested.toCode())); - return requested; } + return requested; } private Projection selectProjection(Projection proj) { diff --git a/src/org/openstreetmap/josm/gui/layer/WMTSLayer.java b/src/org/openstreetmap/josm/gui/layer/WMTSLayer.java index 7f1b131b1d2..d8e1545d834 100644 --- a/src/org/openstreetmap/josm/gui/layer/WMTSLayer.java +++ b/src/org/openstreetmap/josm/gui/layer/WMTSLayer.java @@ -22,9 +22,9 @@ /** * WMTS layer based on AbstractTileSourceLayer. Overrides few methods to align WMTS to Tile based computations * but most magic is done within WMTSTileSource class. - * + *

    * Full specification of the protocol available at: - * http://www.opengeospatial.org/standards/wmts + * OpenGIS Web Map Tile Service Implementation Standard * * @author Wiktor Niesiobędzki * @@ -32,7 +32,7 @@ public class WMTSLayer extends AbstractCachedTileSourceLayer implements NativeScaleLayer { private static final String PREFERENCE_PREFIX = "imagery.wmts"; - /** + /* * Registers all setting properties */ static { diff --git a/src/org/openstreetmap/josm/gui/layer/geoimage/GeoImageLayer.java b/src/org/openstreetmap/josm/gui/layer/geoimage/GeoImageLayer.java index 38b12821d6e..da9414f0b6e 100644 --- a/src/org/openstreetmap/josm/gui/layer/geoimage/GeoImageLayer.java +++ b/src/org/openstreetmap/josm/gui/layer/geoimage/GeoImageLayer.java @@ -21,7 +21,6 @@ import java.awt.image.BufferedImage; import java.io.File; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; @@ -192,18 +191,18 @@ public GeoImageLayer(final List data, GpxData gpxData, final String this.useThumbs = useThumbs; this.data.addImageDataUpdateListener(this); this.data.setLayer(this); - synchronized (ImageViewerDialog.class) { - if (!ImageViewerDialog.hasInstance()) { - GuiHelper.runInEDTAndWait(ImageViewerDialog::createInstance); - } + if (!ImageViewerDialog.hasInstance()) { + GuiHelper.runInEDTAndWait(() -> { + if (!ImageViewerDialog.hasInstance()) { + ImageViewerDialog.createInstance(); + } + }); } if (getInvalidGeoImages().size() == data.size()) { this.data.setSelectedImage(this.data.getFirstImage()); // We do have to wrap the EDT call in a worker call, since layers may be created in the EDT. // And the layer must be added to the layer list in order for the dialog to work properly. - MainApplication.worker.execute(() -> GuiHelper.runInEDT(() -> { - ImageViewerDialog.getInstance().displayImages(this.getSelection()); - })); + MainApplication.worker.execute(() -> GuiHelper.runInEDT(() -> ImageViewerDialog.getInstance().displayImages(this.getSelection()))); } } @@ -812,7 +811,7 @@ public synchronized void startLoadThumbs() { /** * Stop to load thumbnails. - * + *

    * Can be called at any time to make sure that the * thumbnail loader is stopped. */ @@ -825,7 +824,7 @@ public synchronized void stopLoadThumbs() { /** * Called to signal that the loading of thumbnails has finished. - * + *

    * Usually called from {@link ThumbsLoader} in another thread. */ public void thumbsLoaded() { @@ -873,7 +872,7 @@ public GpxData getGpxData() { public GpxLayer getGpxLayer() { return gpxData != null ? MainApplication.getLayerManager().getLayersOfType(GpxLayer.class) .stream().filter(l -> gpxData.equals(l.getGpxData())) - .findFirst().orElseThrow(() -> new IllegalStateException()) : null; + .findFirst().orElseThrow(IllegalStateException::new) : null; } /** @@ -911,7 +910,7 @@ public synchronized GpxData getFauxGpxData() { if (gpxLayer != null) return gpxLayer.data; if (gpxFauxData == null) { gpxFauxData = new GpxData(); - gpxFauxData.addTrack(new GpxTrack(Arrays.asList( + gpxFauxData.addTrack(new GpxTrack(Collections.singletonList( data.getImages().stream().map(ImageEntry::asWayPoint).filter(Objects::nonNull).collect(toList())), Collections.emptyMap())); } @@ -973,7 +972,7 @@ public String getChangesetSourceTag() { @Override public Data getData() { - return data; + return getImageData(); } void applyTmp() { diff --git a/src/org/openstreetmap/josm/gui/layer/geoimage/ImageDisplay.java b/src/org/openstreetmap/josm/gui/layer/geoimage/ImageDisplay.java index 310924a43fb..7f3a1d40776 100644 --- a/src/org/openstreetmap/josm/gui/layer/geoimage/ImageDisplay.java +++ b/src/org/openstreetmap/josm/gui/layer/geoimage/ImageDisplay.java @@ -119,6 +119,7 @@ public class ImageDisplay extends JComponent implements Destroyable, PreferenceC private class UpdateImageThread extends Thread { private boolean restart; + @SuppressWarnings("DoNotCall") // we are calling `run` from the thread we want it to be running on (aka recursive) @Override public void run() { updateProcessedImage(); diff --git a/src/org/openstreetmap/josm/gui/layer/gpx/GpxDrawHelper.java b/src/org/openstreetmap/josm/gui/layer/gpx/GpxDrawHelper.java index 340bd0ff14f..e39bf2acf42 100644 --- a/src/org/openstreetmap/josm/gui/layer/gpx/GpxDrawHelper.java +++ b/src/org/openstreetmap/josm/gui/layer/gpx/GpxDrawHelper.java @@ -239,7 +239,7 @@ public class GpxDrawHelper implements SoMChangeListener, MapViewPaintable.LayerP private void setupColors() { hdopAlpha = Config.getPref().getInt("hdop.color.alpha", -1); velocityScale = ColorScale.createHSBScale(256); - /** Colors (without custom alpha channel, if given) for HDOP painting. **/ + /* Colors (without custom alpha channel, if given) for HDOP painting. */ hdopScale = ColorScale.createHSBScale(256).makeReversed().addTitle(tr("HDOP")); qualityScale = ColorScale.createFixedScale(rtkLibQualityColors).addTitle(tr("Quality")).addColorBarTitles(rtkLibQualityNames); fixScale = ColorScale.createFixedScale(gpsFixQualityColors).addTitle(tr("GPS fix")).addColorBarTitles(gpsFixQualityNames); @@ -768,9 +768,14 @@ private void drawLines(Graphics2D g, MapView mv, List visibleSegments) * @param visibleSegments segments visible in the current scope of mv */ private void drawArrows(Graphics2D g, MapView mv, List visibleSegments) { - /**************************************************************** - ********** STEP 3b - DRAW NICE ARROWS ************************** - ****************************************************************/ + drawArrows3b(g, mv, visibleSegments); + drawArrows3c(g, mv, visibleSegments); + } + + /**************************************************************** + ********** STEP 3b - DRAW NICE ARROWS ************************** + ****************************************************************/ + private void drawArrows3b(Graphics2D g, MapView mv, List visibleSegments) { if (lines && arrows && !arrowsFast) { Point old = null; Point oldA = null; // last arrow painted @@ -797,10 +802,12 @@ private void drawArrows(Graphics2D g, MapView mv, List visibleSegments } } // end for trkpnt } + } - /**************************************************************** - ********** STEP 3c - DRAW FAST ARROWS ************************** - ****************************************************************/ + /**************************************************************** + ********** STEP 3c - DRAW FAST ARROWS ************************** + ****************************************************************/ + private void drawArrows3c(Graphics2D g, MapView mv, List visibleSegments) { if (lines && arrows && arrowsFast) { Point old = null; Point oldA = null; // last arrow painted @@ -835,11 +842,17 @@ private void drawArrows(Graphics2D g, MapView mv, List visibleSegments * @param visibleSegments segments visible in the current scope of mv */ private void drawPoints(Graphics2D g, MapView mv, List visibleSegments) { - /**************************************************************** - ********** STEP 3d - DRAW LARGE POINTS AND HDOP CIRCLE ********* - ****************************************************************/ + drawPointsStep3d(g, mv, visibleSegments); + drawPointsStep3e(g, mv, visibleSegments); + drawPointsStep3f(g, mv, visibleSegments); + } + + /**************************************************************** + ********** STEP 3d - DRAW LARGE POINTS AND HDOP CIRCLE ********* + ****************************************************************/ + private void drawPointsStep3d(Graphics2D g, MapView mv, List visibleSegments) { if (large || hdopCircle) { - final int halfSize = largesize/2; + final int halfSize = largesize / 2; for (WayPoint trkPnt : visibleSegments) { LatLon c = trkPnt.getCoor(); if (Double.isNaN(c.lat()) || Double.isNaN(c.lon())) { @@ -854,13 +867,13 @@ private void drawPoints(Graphics2D g, MapView mv, List visibleSegments hdop = 0; } Color customColoringTransparent = hdopAlpha < 0 ? trkPnt.customColoring : - new Color((trkPnt.customColoring.getRGB() & 0x00ffffff) | (hdopAlpha << 24), true); + new Color((trkPnt.customColoring.getRGB() & 0x00ffffff) | (hdopAlpha << 24), true); g.setColor(customColoringTransparent); // hdop circles int hdopp = mv.getPoint(new LatLon( trkPnt.getCoor().lat(), - trkPnt.getCoor().lon() + 2d*6*hdop*360/40000000d)).x - screen.x; - g.drawArc(screen.x-hdopp/2, screen.y-hdopp/2, hdopp, hdopp, 0, 360); + trkPnt.getCoor().lon() + 2d * 6 * hdop * 360 / 40000000d)).x - screen.x; + g.drawArc(screen.x - hdopp / 2, screen.y - hdopp / 2, hdopp, hdopp, 0, 360); } if (large) { // color the large GPS points like the gps lines @@ -869,21 +882,23 @@ private void drawPoints(Graphics2D g, MapView mv, List visibleSegments g.setColor(colorCacheTransparent); } else { Color customColoringTransparent = largePointAlpha < 0 ? trkPnt.customColoring : - new Color((trkPnt.customColoring.getRGB() & 0x00ffffff) | (largePointAlpha << 24), true); + new Color((trkPnt.customColoring.getRGB() & 0x00ffffff) | (largePointAlpha << 24), true); g.setColor(customColoringTransparent); colorCache = trkPnt.customColoring; colorCacheTransparent = customColoringTransparent; } } - g.fillRect(screen.x-halfSize, screen.y-halfSize, largesize, largesize); + g.fillRect(screen.x - halfSize, screen.y - halfSize, largesize, largesize); } } // end for trkpnt } // end if large || hdopcircle + } - /**************************************************************** - ********** STEP 3e - DRAW SMALL POINTS FOR LINES *************** - ****************************************************************/ + /**************************************************************** + ********** STEP 3e - DRAW SMALL POINTS FOR LINES *************** + ****************************************************************/ + private void drawPointsStep3e(Graphics2D g, MapView mv, List visibleSegments) { if (!large && lines) { g.setColor(neutralColor); for (WayPoint trkPnt : visibleSegments) { @@ -898,10 +913,12 @@ private void drawPoints(Graphics2D g, MapView mv, List visibleSegments } } // end for trkpnt } // end if large + } - /**************************************************************** - ********** STEP 3f - DRAW SMALL POINTS INSTEAD OF LINES ******** - ****************************************************************/ + /**************************************************************** + ********** STEP 3f - DRAW SMALL POINTS INSTEAD OF LINES ******** + ****************************************************************/ + private void drawPointsStep3f(Graphics2D g, MapView mv, List visibleSegments) { if (!large && !lines) { g.setColor(neutralColor); for (WayPoint trkPnt : visibleSegments) { @@ -1307,10 +1324,8 @@ private void drawHeatMapGrayMap(Graphics2D g, BufferedImage imgGray, int sampleR lastPixelX = 0; lastPixelColor = thePixelColor - 1; } - boolean bDrawIt = false; - // when one of segment is mapped to black - bDrawIt = bDrawIt || (lastPixelColor == 0) || (thePixelColor == 0); + boolean bDrawIt = (lastPixelColor == 0) || (thePixelColor == 0); // different color bDrawIt = bDrawIt || (Math.abs(lastPixelColor-thePixelColor) > 0); diff --git a/src/org/openstreetmap/josm/gui/layer/imagery/LoadAllTilesAction.java b/src/org/openstreetmap/josm/gui/layer/imagery/LoadAllTilesAction.java index c4e68fcd58c..1af45cb7cd7 100644 --- a/src/org/openstreetmap/josm/gui/layer/imagery/LoadAllTilesAction.java +++ b/src/org/openstreetmap/josm/gui/layer/imagery/LoadAllTilesAction.java @@ -1,10 +1,6 @@ // License: GPL. For details, see LICENSE file. package org.openstreetmap.josm.gui.layer.imagery; -/** - * Load all tiles. - * @since 11950 (extracted from {@link AbstractTileSourceLayer}) - */ import static org.openstreetmap.josm.tools.I18n.tr; import java.awt.event.ActionEvent; diff --git a/src/org/openstreetmap/josm/gui/mappaint/mapcss/Selector.java b/src/org/openstreetmap/josm/gui/mappaint/mapcss/Selector.java index e0afab5105e..89fcd5ea219 100644 --- a/src/org/openstreetmap/josm/gui/mappaint/mapcss/Selector.java +++ b/src/org/openstreetmap/josm/gui/mappaint/mapcss/Selector.java @@ -45,7 +45,7 @@ /** * MapCSS selector. - * + *

    * A rule has two parts, a selector and a declaration block * e.g. *

    @@ -54,7 +54,7 @@
      * 
    * * The selector decides, if the declaration block gets applied or not. - * + *

    * All implementing classes of Selector are immutable. */ public interface Selector { @@ -354,7 +354,7 @@ private Area getAreaEastNorth(IPrimitive p, Environment e) { private Map, List> findCrossings(IPrimitive area, Map> cellSegments) { - /** The detected crossing ways */ + /* The detected crossing ways */ Map, List> crossingWays = new HashMap<>(50); if (area instanceof Way) { CrossingWays.findIntersectingWay((Way) area, cellSegments, crossingWays, false); diff --git a/src/org/openstreetmap/josm/gui/preferences/SourceEditor.java b/src/org/openstreetmap/josm/gui/preferences/SourceEditor.java index 0402a1084ef..543060ca5c3 100644 --- a/src/org/openstreetmap/josm/gui/preferences/SourceEditor.java +++ b/src/org/openstreetmap/josm/gui/preferences/SourceEditor.java @@ -764,7 +764,7 @@ public SourceEntry setValue(int index, SourceEntry value) { private static void prepareFileChooser(String url, AbstractFileChooser fc) { if (Utils.isBlank(url)) return; - URL sourceUrl = null; + URL sourceUrl; try { sourceUrl = new URL(url); } catch (MalformedURLException e) { @@ -815,7 +815,7 @@ public EditSourceEntryDialog(Component parent, String title, SourceEntry e) { tfURL = new JosmTextField(60); p.add(new JLabel(tr("URL / File:")), GBC.std().insets(15, 0, 5, 0)); p.add(tfURL, GBC.std().insets(0, 0, 5, 5)); - JButton fileChooser = new JButton(new LaunchFileChooserAction()); + JButton fileChooser = new JButton(new LaunchFileChooserSourceTypeAction()); fileChooser.setMargin(new Insets(0, 0, 0, 0)); p.add(fileChooser, GBC.eol().insets(0, 0, 5, 5)); @@ -847,8 +847,8 @@ public void setupDialog() { updateOkButtonState(); } - class LaunchFileChooserAction extends AbstractAction { - LaunchFileChooserAction() { + class LaunchFileChooserSourceTypeAction extends AbstractAction { + LaunchFileChooserSourceTypeAction() { new ImageProvider("open").getResource().attachImageIcon(this); putValue(SHORT_DESCRIPTION, tr("Launch a file chooser to select a file")); } @@ -1534,7 +1534,7 @@ protected final void build() { gc.fill = GridBagConstraints.BOTH; gc.weightx = 0.0; gc.weighty = 1.0; - add(new JButton(new LaunchFileChooserAction())); + add(new JButton(new LaunchFileChooserEditCellAction())); tfFileName.addFocusListener( new FocusAdapter() { @@ -1621,8 +1621,8 @@ public Component getTableCellEditorComponent(JTable table, Object value, boolean return this; } - class LaunchFileChooserAction extends AbstractAction { - LaunchFileChooserAction() { + class LaunchFileChooserEditCellAction extends AbstractAction { + LaunchFileChooserEditCellAction() { putValue(NAME, "..."); putValue(SHORT_DESCRIPTION, tr("Launch a file chooser to select a file")); } diff --git a/src/org/openstreetmap/josm/gui/preferences/ToolbarPreferences.java b/src/org/openstreetmap/josm/gui/preferences/ToolbarPreferences.java index c6a029b3f85..947ae93fd6f 100644 --- a/src/org/openstreetmap/josm/gui/preferences/ToolbarPreferences.java +++ b/src/org/openstreetmap/josm/gui/preferences/ToolbarPreferences.java @@ -23,6 +23,7 @@ import java.util.Arrays; import java.util.Collection; import java.util.Collections; +import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -298,13 +299,13 @@ public ActionDefinition loadAction(String actionName) { if (action == null) return null; - ActionDefinition result = new ActionDefinition(action); + ActionDefinition actionDefinition = new ActionDefinition(action); if (action instanceof ParameterizedAction) { skip('('); ParameterizedAction parametrizedAction = (ParameterizedAction) action; - Map> actionParams = new ConcurrentHashMap<>(); + Map> actionParams = new HashMap<>(); for (ActionParameter param: parametrizedAction.getActionParameters()) { actionParams.put(param.getName(), param); } @@ -316,7 +317,7 @@ public ActionDefinition loadAction(String actionName) { if (!paramName.isEmpty() && !paramValue.isEmpty()) { ActionParameter actionParam = actionParams.get(paramName); if (actionParam != null) { - result.getParameters().put(paramName, actionParam.readFromString(paramValue)); + actionDefinition.getParameters().put(paramName, actionParam.readFromString(paramValue)); } } skip(','); @@ -331,16 +332,16 @@ public ActionDefinition loadAction(String actionName) { skip('='); String paramValue = readTillChar(',', '}'); if ("icon".equals(paramName) && !paramValue.isEmpty()) { - result.setIcon(paramValue); + actionDefinition.setIcon(paramValue); } else if ("name".equals(paramName) && !paramValue.isEmpty()) { - result.setName(paramValue); + actionDefinition.setName(paramValue); } skip(','); } skip('}'); } - return result; + return actionDefinition; } private void escape(String s) { @@ -797,18 +798,25 @@ public Settings(DefaultMutableTreeNode rootActionsNode) { private JButton createButton(String name) { JButton b = new JButton(); - if ("up".equals(name)) { - b.setIcon(ImageProvider.get("dialogs", "up", ImageSizes.LARGEICON)); - b.setToolTipText(tr("Move the currently selected members up")); - } else if ("down".equals(name)) { - b.setIcon(ImageProvider.get("dialogs", "down", ImageSizes.LARGEICON)); - b.setToolTipText(tr("Move the currently selected members down")); - } else if ("<".equals(name)) { - b.setIcon(ImageProvider.get("dialogs/conflict", "copybeforecurrentright", ImageSizes.LARGEICON)); - b.setToolTipText(tr("Add all objects selected in the current dataset before the first selected member")); - } else if (">".equals(name)) { - b.setIcon(ImageProvider.get("dialogs", "delete", ImageSizes.LARGEICON)); - b.setToolTipText(tr("Remove")); + switch (name) { + case "up": + b.setIcon(ImageProvider.get("dialogs", "up", ImageSizes.LARGEICON)); + b.setToolTipText(tr("Move the currently selected members up")); + break; + case "down": + b.setIcon(ImageProvider.get("dialogs", "down", ImageSizes.LARGEICON)); + b.setToolTipText(tr("Move the currently selected members down")); + break; + case "<": + b.setIcon(ImageProvider.get("dialogs/conflict", "copybeforecurrentright", ImageSizes.LARGEICON)); + b.setToolTipText(tr("Add all objects selected in the current dataset before the first selected member")); + break; + case ">": + b.setIcon(ImageProvider.get("dialogs", "delete", ImageSizes.LARGEICON)); + b.setToolTipText(tr("Remove")); + break; + default: + // do nothing } b.addActionListener(moveAction); b.setActionCommand(name); @@ -1043,7 +1051,7 @@ private static void loadAction(DefaultMutableTreeNode node, MenuElement menu, Ma action.getClass().getName())); continue; } else if (!(tb instanceof String)) { - if (!(tb instanceof Boolean) || (Boolean) tb) { + if (!(tb instanceof Boolean) || Boolean.TRUE.equals(tb)) { Logging.info(tr("Strange toolbar value: {0}", action.getClass().getName())); } @@ -1161,7 +1169,7 @@ public Action unregister(Action action) { /** * Parse the toolbar preference setting and construct the toolbar GUI control. - * + *

    * Call this, if anything has changed in the toolbar settings and you want to refresh * the toolbar content (e.g. after registering actions in a plugin) */ diff --git a/src/org/openstreetmap/josm/gui/preferences/display/ColorPreference.java b/src/org/openstreetmap/josm/gui/preferences/display/ColorPreference.java index 65e5e2870ca..9c1f2e3248d 100644 --- a/src/org/openstreetmap/josm/gui/preferences/display/ColorPreference.java +++ b/src/org/openstreetmap/josm/gui/preferences/display/ColorPreference.java @@ -215,7 +215,7 @@ public String getColumnName(int column) { @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { if (columnIndex == 1 && aValue instanceof Color) { - data.get(rowIndex).info.setValue((Color) aValue); + getEntry(rowIndex).info.setValue((Color) aValue); fireTableCellUpdated(rowIndex, columnIndex); } } diff --git a/src/org/openstreetmap/josm/gui/preferences/imagery/CacheSettingsPanel.java b/src/org/openstreetmap/josm/gui/preferences/imagery/CacheSettingsPanel.java index 22c1a1b5cb1..85d92116c99 100644 --- a/src/org/openstreetmap/josm/gui/preferences/imagery/CacheSettingsPanel.java +++ b/src/org/openstreetmap/josm/gui/preferences/imagery/CacheSettingsPanel.java @@ -8,12 +8,12 @@ import java.io.File; import java.util.ArrayList; import java.util.Comparator; +import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; import javax.swing.AbstractAction; import javax.swing.JLabel; @@ -119,7 +119,7 @@ private static Long getCacheSize(CacheAccess ca */ public static String[][] getCacheStats(CacheAccess cache) { Set keySet = cache.getCacheControl().getKeySet(); - Map temp = new ConcurrentHashMap<>(); // use int[] as a Object reference to int, gives better performance + Map temp = new HashMap<>(); // use int[] as a Object reference to int, gives better performance for (String key: keySet) { String[] keyParts = key.split(":", 2); if (keyParts.length == 2) { diff --git a/src/org/openstreetmap/josm/gui/preferences/plugin/PluginPreference.java b/src/org/openstreetmap/josm/gui/preferences/plugin/PluginPreference.java index 3648b820252..5c197ef85fa 100644 --- a/src/org/openstreetmap/josm/gui/preferences/plugin/PluginPreference.java +++ b/src/org/openstreetmap/josm/gui/preferences/plugin/PluginPreference.java @@ -305,7 +305,7 @@ public boolean ok() { if (!deactivatedPlugins.isEmpty()) { boolean requiresRestart = PluginHandler.removePlugins(deactivatedPlugins); if (requiresRestart) - return requiresRestart; + return true; } return model.getNewlyActivatedPlugins().stream().anyMatch(pi -> !pi.canloadatruntime); } @@ -520,7 +520,7 @@ private void activatePlugins(JTextArea textField, boolean deleteNotInList) { // This pattern matches the default list format JOSM uses for bug reports. // It removes a list item mark at the beginning of the line: +, -, * // It removes the version number after the plugin, like: 123, (123), (v5.7alpha3), (1b3), (v1-SNAPSHOT-1)... - Pattern regex = Pattern.compile("^[-+\\*\\s]*|\\s[\\d\\s]*(\\([^\\(\\)\\[\\]]*\\))?[\\d\\s]*$"); + Pattern regex = Pattern.compile("^[-+*\\s]*|\\s[\\d\\s]*(\\([^()\\[\\]]*\\))?[\\d\\s]*$"); for (String line : lines) { String name = regex.matcher(line).replaceAll(""); if (name.isEmpty()) { diff --git a/src/org/openstreetmap/josm/gui/preferences/projection/ProjectionPreference.java b/src/org/openstreetmap/josm/gui/preferences/projection/ProjectionPreference.java index 04c393a6bdb..93c1be6e9b3 100644 --- a/src/org/openstreetmap/josm/gui/preferences/projection/ProjectionPreference.java +++ b/src/org/openstreetmap/josm/gui/preferences/projection/ProjectionPreference.java @@ -50,15 +50,15 @@ /** * Projection preferences. - * + *

    * How to add new Projections: * - Find EPSG code for the projection. - * - Look up the parameter string for Proj4, e.g. on http://spatialreference.org/ + * - Look up the parameter string for Proj4, e.g. on https://spatialreference.org/ * and add it to the file 'data/projection/epsg' in JOSM trunk * - Search for official references and verify the parameter values. These * documents are often available in the local language only. * - Use {@link #registerProjectionChoice}, to make the entry known to JOSM. - * + *

    * In case there is no EPSG code: * - override {@link AbstractProjectionChoice#getProjection()} and provide * a manual implementation of the projection. Use {@link CustomProjection} @@ -86,57 +86,57 @@ public PreferenceSetting createPreferenceSetting() { /** * Mercator Projection. - * + *

    * The center of the mercator projection is always the 0 grad coordinate. - * - * See also USGS Bulletin 1532 (http://pubs.usgs.gov/bul/1532/report.pdf) - * initially EPSG used 3785 but that has been superseded by 3857, see https://www.epsg-registry.org/ + *

    + * See also USGS Bulletin 1532 + * initially EPSG used 3785 but that has been superseded by 3857, see epsg-registry.org */ public static final ProjectionChoice mercator = registerProjectionChoice(tr("Mercator"), "core:mercator", 3857); /** * Lambert conic conform 4 zones using the French geodetic system NTF. - * + *

    * This newer version uses the grid translation NTF<->RGF93 provided by IGN for a submillimetric accuracy. * (RGF93 is the French geodetic system similar to WGS84 but not mathematically equal) - * - * Source: http://geodesie.ign.fr/contenu/fichiers/Changement_systeme_geodesique.pdf + *

    + * Source: Changement_systeme_geodesique.pdf */ public static final ProjectionChoice lambert = new LambertProjectionChoice(); /** * French regions in the Caribbean Sea and Indian Ocean. - * + *

    * Using the UTM transvers Mercator projection and specific geodesic settings. */ public static final ProjectionChoice utm_france_dom = new UTMFranceDOMProjectionChoice(); /** * Lambert Conic Conform 9 Zones projection. - * + *

    * As specified by the IGN in this document - * http://geodesie.ign.fr/contenu/fichiers/documentation/rgf93/cc9zones.pdf + * cc9zones.pdf */ public static final ProjectionChoice lambert_cc9 = new LambertCC9ZonesProjectionChoice(); static { - /************************ + /* *********************** * Global projections. */ - /** + /* * * UTM. */ registerProjectionChoice(new UTMProjectionChoice()); - /************************ + /* *********************** * Regional - alphabetical order by country code. */ - /** + /* * Belgian Lambert 72 projection. - * + *

    * As specified by the Belgian IGN in this document: * http://www.ngi.be/Common/Lambert2008/Transformation_Geographic_Lambert_FR.pdf * @@ -144,9 +144,9 @@ public PreferenceSetting createPreferenceSetting() { */ registerProjectionChoice(tr("Belgian Lambert 1972"), "core:belgianLambert1972", 31370); // BE - /** + /* * Belgian Lambert 2008 projection. - * + *

    * As specified by the Belgian IGN in this document: * http://www.ngi.be/Common/Lambert2008/Transformation_Geographic_Lambert_FR.pdf * @@ -154,12 +154,12 @@ public PreferenceSetting createPreferenceSetting() { */ registerProjectionChoice(tr("Belgian Lambert 2008"), "core:belgianLambert2008", 3812); // BE - /** + /* * SwissGrid CH1903 / L03, see https://en.wikipedia.org/wiki/Swiss_coordinate_system. - * + *

    * Actually, what we have here, is CH1903+ (EPSG:2056), but without * the additional false easting of 2000km and false northing 1000 km. - * + *

    * To get to CH1903, a shift file is required. So currently, there are errors * up to 1.6m (depending on the location). */ @@ -167,89 +167,89 @@ public PreferenceSetting createPreferenceSetting() { registerProjectionChoice(new GaussKruegerProjectionChoice()); // DE - /** + /* * Estonian Coordinate System of 1997. - * + *

    * Thanks to Johan Montagnat and its geoconv java converter application * (https://www.i3s.unice.fr/~johan/gps/ , published under GPL license) * from which some code and constants have been reused here. */ registerProjectionChoice(tr("Lambert Zone (Estonia)"), "core:lambertest", 3301); // EE - /** + /* * Lambert conic conform 4 zones using the French geodetic system NTF. - * + *

    * This newer version uses the grid translation NTF<->RGF93 provided by IGN for a submillimetric accuracy. * (RGF93 is the French geodetic system similar to WGS84 but not mathematically equal) - * - * Source: http://geodesie.ign.fr/contenu/fichiers/Changement_systeme_geodesique.pdf + *

    + * Source: https://geodesie.ign.fr/contenu/fichiers/Changement_systeme_geodesique.pdf * @author Pieren */ registerProjectionChoice(lambert); // FR - /** + /* * Lambert 93 projection. - * + *

    * As specified by the IGN in this document - * http://geodesie.ign.fr/contenu/fichiers/documentation/rgf93/Lambert-93.pdf + * https://geodesie.ign.fr/contenu/fichiers/documentation/rgf93/Lambert-93.pdf * @author Don-vip */ registerProjectionChoice(tr("Lambert 93 (France)"), "core:lambert93", 2154); // FR - /** + /* * Lambert Conic Conform 9 Zones projection. - * + *

    * As specified by the IGN in this document - * http://geodesie.ign.fr/contenu/fichiers/documentation/rgf93/cc9zones.pdf + * https://geodesie.ign.fr/contenu/fichiers/documentation/rgf93/cc9zones.pdf * @author Pieren */ registerProjectionChoice(lambert_cc9); // FR - /** + /* * French departements in the Caribbean Sea and Indian Ocean. - * + *

    * Using the UTM transvers Mercator projection and specific geodesic settings. */ registerProjectionChoice(utm_france_dom); // FR - /** + /* * LKS-92/ Latvia TM projection. - * + *

    * Based on data from spatialreference.org. - * http://spatialreference.org/ref/epsg/3059/ + * https://spatialreference.org/ref/epsg/3059/ * * @author Viesturs Zarins */ registerProjectionChoice(tr("LKS-92 (Latvia TM)"), "core:tmerclv", 3059); // LV - /** + /* * Netherlands RD projection * * @author vholten */ registerProjectionChoice(tr("Rijksdriehoekscoördinaten (Netherlands)"), "core:dutchrd", 28992); // NL - /** + /* * PUWG 1992 and 2000 are the official cordinate systems in Poland. - * + *

    * They use the same math as UTM only with different constants. * * @author steelman */ registerProjectionChoice(new PuwgProjectionChoice()); // PL - /** + /* * SWEREF99 projections. Official coordinate system in Sweden. */ registerProjectionChoice(tr("SWEREF99 TM / EPSG:3006 (Sweden)"), "core:sweref99tm", 3006); // SE registerProjectionChoice(tr("SWEREF99 13 30 / EPSG:3008 (Sweden)"), "core:sweref99", 3008); // SE - /************************ + /* *********************** * Projection by Code. */ registerProjectionChoice(new CodeProjectionChoice()); - /************************ + /* *********************** * Custom projection. */ registerProjectionChoice(new CustomProjectionChoice()); diff --git a/src/org/openstreetmap/josm/gui/tagging/presets/TaggingPresetMenu.java b/src/org/openstreetmap/josm/gui/tagging/presets/TaggingPresetMenu.java index 09891588c80..046d256bd08 100644 --- a/src/org/openstreetmap/josm/gui/tagging/presets/TaggingPresetMenu.java +++ b/src/org/openstreetmap/josm/gui/tagging/presets/TaggingPresetMenu.java @@ -34,6 +34,7 @@ * Used, to create the nested directory structure in the preset main menu entry. */ public class TaggingPresetMenu extends TaggingPreset { + /** The menu to show users */ public JMenu menu; // set by TaggingPresets private static class PresetTextComparator implements Comparator, Serializable { @@ -72,7 +73,7 @@ public int hashCode() { @Override public void setDisplayName() { putValue(Action.NAME, getName()); - /** Tooltips should be shown for the toolbar buttons, but not in the menu. */ + /* Tooltips should be shown for the toolbar buttons, but not in the menu. */ putValue(OPTIONAL_TOOLTIP_TEXT, group != null ? tr("Preset group {1} / {0}", getLocaleName(), group.getName()) : tr("Preset group {0}", getLocaleName())); diff --git a/src/org/openstreetmap/josm/gui/tagging/presets/TaggingPresetReader.java b/src/org/openstreetmap/josm/gui/tagging/presets/TaggingPresetReader.java index f82a668937a..7798e42f53c 100644 --- a/src/org/openstreetmap/josm/gui/tagging/presets/TaggingPresetReader.java +++ b/src/org/openstreetmap/josm/gui/tagging/presets/TaggingPresetReader.java @@ -166,7 +166,7 @@ private static XmlObjectParser buildParser() { * @throws SAXException if any XML error occurs */ public static Collection readAll(Reader in, boolean validate) throws SAXException { - return readAll(in, validate, new HashSetWithLast()); + return readAll(in, validate, new HashSetWithLast<>()); } /** @@ -180,18 +180,18 @@ public static Collection readAll(Reader in, boolean validate) thr static Collection readAll(Reader in, boolean validate, HashSetWithLast all) throws SAXException { XmlObjectParser parser = buildParser(); - /** to detect end of {@code } */ + /* to detect end of {@code } */ CheckGroup lastcheckgroup = null; - /** to detect end of {@code } */ + /* to detect end of {@code } */ TaggingPresetMenu lastmenu = null; - /** to detect end of reused {@code } */ + /* to detect end of reused {@code } */ TaggingPresetMenu lastmenuOriginal = null; Roles lastrole = null; final List checks = new LinkedList<>(); final List listEntries = new LinkedList<>(); final Map> byId = new HashMap<>(); final Deque lastIds = new ArrayDeque<>(); - /** lastIdIterators contains non empty iterators of items to be handled before obtaining the next item from the XML parser */ + /* lastIdIterators contains non empty iterators of items to be handled before obtaining the next item from the XML parser */ final Deque> lastIdIterators = new ArrayDeque<>(); if (validate) { @@ -350,7 +350,7 @@ static Collection readAll(Reader in, boolean validate, HashSetWit * @throws IOException if any I/O error occurs */ public static Collection readAll(String source, boolean validate) throws SAXException, IOException { - return readAll(source, validate, new HashSetWithLast()); + return readAll(source, validate, new HashSetWithLast<>()); } /** diff --git a/src/org/openstreetmap/josm/gui/tagging/presets/items/KeyedItem.java b/src/org/openstreetmap/josm/gui/tagging/presets/items/KeyedItem.java index a3f3d3ed951..d70e9e840b3 100644 --- a/src/org/openstreetmap/josm/gui/tagging/presets/items/KeyedItem.java +++ b/src/org/openstreetmap/josm/gui/tagging/presets/items/KeyedItem.java @@ -241,7 +241,7 @@ public Boolean matches(Map tags) { case KEY_REQUIRED: return tags.containsKey(key); case KEY_VALUE: - return tags.containsKey(key) && getValues().contains(tags.get(key)) ? Boolean.TRUE : null; + return (tags.containsKey(key) && getValues().contains(tags.get(key))) ? Boolean.TRUE : null; case KEY_VALUE_REQUIRED: return tags.containsKey(key) && getValues().contains(tags.get(key)); default: diff --git a/src/org/openstreetmap/josm/gui/widgets/MultiSplitLayout.java b/src/org/openstreetmap/josm/gui/widgets/MultiSplitLayout.java index 65e654e550a..e24b5c2f8a1 100644 --- a/src/org/openstreetmap/josm/gui/widgets/MultiSplitLayout.java +++ b/src/org/openstreetmap/josm/gui/widgets/MultiSplitLayout.java @@ -1119,13 +1119,12 @@ public void setName(String name) { @Override public String toString() { - return new StringBuilder("MultiSplitLayout.Leaf \"") - .append(getName()) - .append("\" weight=") - .append(getWeight()) - .append(' ') - .append(getBounds()) - .toString(); + return "MultiSplitLayout.Leaf \"" + + getName() + + "\" weight=" + + getWeight() + + ' ' + + getBounds(); } } diff --git a/src/org/openstreetmap/josm/io/OsmApi.java b/src/org/openstreetmap/josm/io/OsmApi.java index 674d93a4977..c253fd9a25b 100644 --- a/src/org/openstreetmap/josm/io/OsmApi.java +++ b/src/org/openstreetmap/josm/io/OsmApi.java @@ -306,9 +306,9 @@ private synchronized void initializeCapabilities(String xml) throws SAXException * @return XML string */ protected final String toXml(IPrimitive o, boolean addBody) { - StringWriter swriter = new StringWriter(); - try (OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(new PrintWriter(swriter), true, version)) { - swriter.getBuffer().setLength(0); + StringWriter stringWriter = new StringWriter(); + try (OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(new PrintWriter(stringWriter), true, version)) { + stringWriter.getBuffer().setLength(0); osmWriter.setWithBody(addBody); osmWriter.setChangeset(changeset); osmWriter.header(); @@ -318,7 +318,7 @@ protected final String toXml(IPrimitive o, boolean addBody) { } catch (IOException e) { Logging.warn(e); } - return swriter.toString(); + return stringWriter.toString(); } /** @@ -327,9 +327,9 @@ protected final String toXml(IPrimitive o, boolean addBody) { * @return XML string */ protected final String toXml(Changeset s) { - StringWriter swriter = new StringWriter(); - try (OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(new PrintWriter(swriter), true, version)) { - swriter.getBuffer().setLength(0); + StringWriter stringWriter = new StringWriter(); + try (OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(new PrintWriter(stringWriter), true, version)) { + stringWriter.getBuffer().setLength(0); osmWriter.header(); osmWriter.visit(s); osmWriter.footer(); @@ -337,7 +337,7 @@ protected final String toXml(Changeset s) { } catch (IOException e) { Logging.warn(e); } - return swriter.toString(); + return stringWriter.toString(); } private static String getBaseUrl(String serverUrl, String version) { @@ -347,7 +347,7 @@ private static String getBaseUrl(String serverUrl, String version) { } rv.append('/'); // this works around a ruby (or lighttpd) bug where two consecutive slashes in - // an URL will cause a "404 not found" response. + // a URL will cause a "404 not found" response. int p; while ((p = rv.indexOf("//", rv.indexOf("://")+2)) > -1) { rv.delete(p, p + 1); @@ -455,7 +455,7 @@ public void deletePrimitive(OsmPrimitive osm, ProgressMonitor monitor) throws Os /** * Creates a new changeset based on the keys in changeset. If this * method succeeds, changeset.getId() replies the id the server assigned to the new changeset - * + *

    * The changeset must not be null, but its key/value-pairs may be empty. * * @param changeset the changeset toe be created. Must not be null. @@ -740,7 +740,7 @@ protected final String sendRequest(String requestMethod, String urlSuffix, Strin /** * Generic method for sending requests to the OSM API. - * + *

    * This method will automatically re-try any requests that are answered with a 5xx * error code, or that resulted in a timeout exception from the TCP layer. * @@ -850,8 +850,6 @@ protected final String sendRequest(String requestMethod, String urlSuffix, Strin throw new OsmTransferException(e); } catch (IOException e) { throw new OsmTransferException(e); - } catch (OsmTransferException e) { - throw e; } } } @@ -921,13 +919,12 @@ private static StringBuilder noteStringBuilder(Note note) { */ public Note createNote(LatLon latlon, String text, ProgressMonitor monitor) throws OsmTransferException { initialize(monitor); - String noteUrl = new StringBuilder() - .append("notes?lat=") - .append(latlon.lat()) - .append("&lon=") - .append(latlon.lon()) - .append("&text=") - .append(Utils.encodeUrl(text)).toString(); + String noteUrl = "notes?lat=" + + latlon.lat() + + "&lon=" + + latlon.lon() + + "&text=" + + Utils.encodeUrl(text); return parseSingleNote(sendPostRequest(noteUrl, null, monitor)); } diff --git a/src/org/openstreetmap/josm/io/OsmHistoryReader.java b/src/org/openstreetmap/josm/io/OsmHistoryReader.java index 1e790e5d9e5..97ee549515e 100644 --- a/src/org/openstreetmap/josm/io/OsmHistoryReader.java +++ b/src/org/openstreetmap/josm/io/OsmHistoryReader.java @@ -39,8 +39,8 @@ private class Parser extends AbstractParser { protected String getCurrentPosition() { if (locator == null) return ""; - return new StringBuilder().append('(').append(locator.getLineNumber()) - .append(',').append(locator.getColumnNumber()).append(')').toString(); + return "(" + locator.getLineNumber() + + ',' + locator.getColumnNumber() + ')'; } @Override diff --git a/src/org/openstreetmap/josm/io/imagery/ImageryReader.java b/src/org/openstreetmap/josm/io/imagery/ImageryReader.java index 2da233b83f1..ee0ed9aed88 100644 --- a/src/org/openstreetmap/josm/io/imagery/ImageryReader.java +++ b/src/org/openstreetmap/josm/io/imagery/ImageryReader.java @@ -313,7 +313,7 @@ public void startElement(String namespaceURI, String localName, String qName, At break; default: // Do nothing } - /** + /* * Did not recognize the element, so the new state is UNKNOWN. * This includes the case where we are already inside an unknown * element, i.e. we do not try to understand the inner content diff --git a/src/org/openstreetmap/josm/io/imagery/WMSImagery.java b/src/org/openstreetmap/josm/io/imagery/WMSImagery.java index a70a3e72787..691b5a4210e 100644 --- a/src/org/openstreetmap/josm/io/imagery/WMSImagery.java +++ b/src/org/openstreetmap/josm/io/imagery/WMSImagery.java @@ -312,11 +312,12 @@ public String buildRootUrlWithoutCapabilities() { /** * Returns URL for accessing GetMap service. String will contain following parameters: - * * {proj} - that needs to be replaced with projection (one of {@link #getServerProjections(List)}) - * * {width} - that needs to be replaced with width of the tile - * * {height} - that needs to be replaces with height of the tile - * * {bbox} - that needs to be replaced with area that should be fetched (in {proj} coordinates) - * + *

      + *
    • {proj} - that needs to be replaced with projection (one of {@link #getServerProjections(List)})
    • + *
    • {width} - that needs to be replaced with width of the tile
    • + *
    • {height} - that needs to be replaces with height of the tile
    • + *
    • {bbox} - that needs to be replaced with area that should be fetched (in {proj} coordinates)
    • + *
    * Format of the response will be calculated using {@link #getPreferredFormat()} * * @param selectedLayers list of DefaultLayer selection of layers to be shown @@ -332,11 +333,12 @@ public String buildGetMapUrl(List selectedLayers, boolean transpar /** * Returns URL for accessing GetMap service. String will contain following parameters: - * * {proj} - that needs to be replaced with projection (one of {@link #getServerProjections(List)}) - * * {width} - that needs to be replaced with width of the tile - * * {height} - that needs to be replaces with height of the tile - * * {bbox} - that needs to be replaced with area that should be fetched (in {proj} coordinates) - * + *
      + *
    • {proj} - that needs to be replaced with projection (one of {@link #getServerProjections(List)})
    • + *
    • {width} - that needs to be replaced with width of the tile
    • + *
    • {height} - that needs to be replaces with height of the tile
    • + *
    • {bbox} - that needs to be replaced with area that should be fetched (in {proj} coordinates)
    • + *
    * Format of the response will be calculated using {@link #getPreferredFormat()} * * @param selectedLayers selected layers as subset of the tree returned by {@link #getLayers()} @@ -410,7 +412,7 @@ public String buildGetMapUrl(List selectedLayers, private boolean tagEquals(QName a, QName b) { boolean ret = a.equals(b); if (ret) { - return ret; + return true; } if (belowWMS130()) { @@ -487,8 +489,8 @@ private void parseCapability(XMLStreamReader reader) throws XMLStreamException { } private void parseRequest(XMLStreamReader reader) throws XMLStreamException { - String mode = ""; - String getMapUrl = ""; + String mode; + String newGetMapUrl = ""; if (GetCapabilitiesParseHelper.moveReaderToTag(reader, this::tagEquals, QN_GETMAP)) { for (int event = reader.getEventType(); reader.hasNext() && !(event == XMLStreamReader.END_ELEMENT && tagEquals(QN_GETMAP, reader.getName())); @@ -505,16 +507,16 @@ private void parseRequest(XMLStreamReader reader) throws XMLStreamException { this::tagEquals, QN_HTTP, QN_GET)) { mode = reader.getName().getLocalPart(); if (GetCapabilitiesParseHelper.moveReaderToTag(reader, this::tagEquals, QN_ONLINE_RESOURCE)) { - getMapUrl = reader.getAttributeValue(GetCapabilitiesParseHelper.XLINK_NS_URL, "href"); + newGetMapUrl = reader.getAttributeValue(GetCapabilitiesParseHelper.XLINK_NS_URL, "href"); } // TODO should we handle also POST? - if ("GET".equalsIgnoreCase(mode) && getMapUrl != null && !getMapUrl.isEmpty()) { + if ("GET".equalsIgnoreCase(mode) && newGetMapUrl != null && !newGetMapUrl.isEmpty()) { try { - String query = new URL(getMapUrl).getQuery(); + String query = new URL(newGetMapUrl).getQuery(); if (query == null) { - this.getMapUrl = getMapUrl + "?"; + this.getMapUrl = newGetMapUrl + "?"; } else { - this.getMapUrl = getMapUrl; + this.getMapUrl = newGetMapUrl; } } catch (MalformedURLException e) { throw new XMLStreamException(e); @@ -580,7 +582,7 @@ public boolean belowWMS130() { private void parseAndAddStyle(XMLStreamReader reader, LayerDetails ld) throws XMLStreamException { String name = null; - String title = null; + String styleTitle = null; for (int event = reader.getEventType(); reader.hasNext() && !(event == XMLStreamReader.END_ELEMENT && tagEquals(QN_STYLE, reader.getName())); event = reader.next()) { @@ -589,14 +591,14 @@ private void parseAndAddStyle(XMLStreamReader reader, LayerDetails ld) throws XM name = reader.getElementText(); } if (tagEquals(QN_TITLE, reader.getName())) { - title = reader.getElementText(); + styleTitle = reader.getElementText(); } } } if (name == null) { name = ""; } - ld.addStyle(name, title); + ld.addStyle(name, styleTitle); } private Bounds parseExGeographic(XMLStreamReader reader) throws XMLStreamException { @@ -664,8 +666,8 @@ private static double getDecimalDegree(String value) { } private static String normalizeUrl(String serviceUrlStr) throws MalformedURLException { - URL getCapabilitiesUrl = null; - String ret = null; + URL getCapabilitiesUrl; + String ret; if (!Pattern.compile(".*GetCapabilities.*", Pattern.CASE_INSENSITIVE).matcher(serviceUrlStr).matches()) { // If the url doesn't already have GetCapabilities, add it in diff --git a/src/org/openstreetmap/josm/io/remotecontrol/handler/LoadAndZoomHandler.java b/src/org/openstreetmap/josm/io/remotecontrol/handler/LoadAndZoomHandler.java index 03920315943..af1072c6907 100644 --- a/src/org/openstreetmap/josm/io/remotecontrol/handler/LoadAndZoomHandler.java +++ b/src/org/openstreetmap/josm/io/remotecontrol/handler/LoadAndZoomHandler.java @@ -195,7 +195,7 @@ protected void handleRequest() throws RequestHandlerErrorException { throw new RequestHandlerErrorException(ex); } - /** + /* * deselect objects if parameter addtags given */ if (args.containsKey("addtags") && !isKeepingCurrentSelection) { diff --git a/src/org/openstreetmap/josm/io/remotecontrol/handler/LoadDataHandler.java b/src/org/openstreetmap/josm/io/remotecontrol/handler/LoadDataHandler.java index ec3dcd285e5..e85bee3e13b 100644 --- a/src/org/openstreetmap/josm/io/remotecontrol/handler/LoadDataHandler.java +++ b/src/org/openstreetmap/josm/io/remotecontrol/handler/LoadDataHandler.java @@ -81,7 +81,7 @@ public PermissionPrefWithDefault getPermissionPref() { protected void validateRequest() throws RequestHandlerBadRequestException { validateDownloadParams(); this.data = args.get("data"); - /** + /* * Holds the mime type. Currently only OSM_MIME_TYPE is supported * But it could be extended to text/csv, application/gpx+xml, ... or even binary encoded data */ diff --git a/src/org/openstreetmap/josm/tools/Geometry.java b/src/org/openstreetmap/josm/tools/Geometry.java index 98cd6c5a34f..08c92fa4e33 100644 --- a/src/org/openstreetmap/josm/tools/Geometry.java +++ b/src/org/openstreetmap/josm/tools/Geometry.java @@ -88,7 +88,7 @@ public enum PolygonIntersection { * Will find all intersection and add nodes there for list of given ways. * Handles self-intersections too. * And makes commands to add the intersection points to ways. - * + *

    * Prerequisite: no two nodes have the same coordinates. * * @param ways a list of ways to test @@ -243,7 +243,7 @@ public static Set addIntersections(List ways, boolean test, List * (Imagine the path is continued beyond the endpoints, so you get two rays * starting from lineP2 and going through lineP1 and lineP3 respectively * which divide the plane into two parts. The test returns true, if testPoint @@ -531,7 +531,7 @@ public static EastNorth closestPointToLine(EastNorth lineP1, EastNorth lineP2, E /** * This method tests if secondNode is clockwise to first node. - * + *

    * The line through the two points commonNode and firstNode divides the * plane into two parts. The test returns true, if secondNode lies in * the part that is to the right when traveling in the direction from @@ -563,7 +563,7 @@ public static boolean angleIsClockwise(EastNorth commonNode, EastNorth firstNode * @since 6841 */ public static Area getArea(List polygon) { - Path2D path = new Path2D.Double(); + Path2D path = new Path2D.Double(Path2D.WIND_NON_ZERO, polygon.size()); boolean begin = true; for (INode n : polygon) { @@ -841,12 +841,14 @@ public static Double computeArea(IPrimitive osm) { /** * Determines whether a way is oriented clockwise. - * + *

    * Internals: Assuming a closed non-looping way, compute twice the area * of the polygon using the formula {@code 2 * area = sum (X[n] * Y[n+1] - X[n+1] * Y[n])}. * If the area is negative the way is ordered in a clockwise direction. - * - * See http://paulbourke.net/geometry/polyarea/ + *

    + * See + * https://paulbourke.net/geometry/polyarea/ + * * * @param w the way to be checked. * @return true if and only if way is oriented clockwise. @@ -993,7 +995,7 @@ public static EastNorth getCentroidEN(List nodes) { /** * Compute the center of the circle closest to different nodes. - * + *

    * Ensure exact center computation in case nodes are already aligned in circle. * This is done by least square method. * Let be a_i x + b_i y + c_i = 0 equations of bisectors of each edges. @@ -1012,7 +1014,7 @@ public static EastNorth getCentroidEN(List nodes) { public static EastNorth getCenter(List nodes) { int nc = nodes.size(); if (nc < 3) return null; - /** + /* * Equation of each bisector ax + by + c = 0 */ double[] a = new double[nc]; @@ -1159,7 +1161,7 @@ public static List filterInsidePolygon(Collection primit List res = new ArrayList<>(); if (!polygon.isClosed() || polygon.getNodesCount() <= 3) return res; - /** polygon area in east north space, calculated only when really needed */ + /* polygon area in east north space, calculated only when really needed */ Area polygonArea = null; for (IPrimitive p : primitives) { if (p instanceof INode) { @@ -1282,7 +1284,7 @@ public double getPerimeter() { /** * Calculate area and perimeter length of a polygon. - * + *

    * Uses current projection; units are that of the projected coordinates. * * @param nodes the list of nodes representing the polygon @@ -1326,9 +1328,9 @@ public static AreaAndPerimeter getAreaAndPerimeter(List nodes /** * Get the closest primitive to {@code osm} from the collection of * OsmPrimitive {@code primitives} - * + *

    * The {@code primitives} should be fully downloaded to ensure accuracy. - * + *

    * Note: The complexity of this method is O(n*m), where n is the number of * children {@code osm} has plus 1, m is the number of children the * collection of primitives have plus the number of primitives in the @@ -1350,9 +1352,9 @@ public static T getClosestPrimitive(OsmPrimitive osm, C /** * Get the closest primitives to {@code osm} from the collection of * OsmPrimitive {@code primitives} - * + *

    * The {@code primitives} should be fully downloaded to ensure accuracy. - * + *

    * Note: The complexity of this method is O(n*m), where n is the number of * children {@code osm} has plus 1, m is the number of children the * collection of primitives have plus the number of primitives in the @@ -1385,12 +1387,12 @@ public static Collection getClosestPrimitives(OsmPri /** * Get the furthest primitive to {@code osm} from the collection of * OsmPrimitive {@code primitives} - * + *

    * The {@code primitives} should be fully downloaded to ensure accuracy. - * + *

    * It does NOT give the furthest primitive based off of the furthest * part of that primitive - * + *

    * Note: The complexity of this method is O(n*m), where n is the number of * children {@code osm} has plus 1, m is the number of children the * collection of primitives have plus the number of primitives in the @@ -1411,12 +1413,12 @@ public static T getFurthestPrimitive(OsmPrimitive osm, /** * Get the furthest primitives to {@code osm} from the collection of * OsmPrimitive {@code primitives} - * + *

    * The {@code primitives} should be fully downloaded to ensure accuracy. - * + *

    * It does NOT give the furthest primitive based off of the furthest * part of that primitive - * + *

    * Note: The complexity of this method is O(n*m), where n is the number of * children {@code osm} has plus 1, m is the number of children the * collection of primitives have plus the number of primitives in the @@ -1453,7 +1455,7 @@ public static Collection getFurthestPrimitives(OsmPr * @return The distance between the primitives in meters * (or the unit of the current projection, see {@link Projection}). * May return {@link Double#NaN} if one of the primitives is incomplete. - * + *

    * Note: The complexity is O(n*m), where (n,m) are the number of child * objects the {@link OsmPrimitive}s have. * @since 15035 diff --git a/src/org/openstreetmap/josm/tools/ReflectionUtils.java b/src/org/openstreetmap/josm/tools/ReflectionUtils.java index 536abdff1bc..03e35ea2008 100644 --- a/src/org/openstreetmap/josm/tools/ReflectionUtils.java +++ b/src/org/openstreetmap/josm/tools/ReflectionUtils.java @@ -60,7 +60,7 @@ public static Class findCallerClass(Collection> exclusions) { }, exclusions); } - private static T findCaller(Function getter, Collection exclusions) { + private static T findCaller(Function getter, Collection exclusions) { StackTraceElement[] stack = Thread.currentThread().getStackTrace(); for (int i = 3; i < stack.length; i++) { T t = getter.apply(stack[i]); diff --git a/src/org/openstreetmap/josm/tools/Shortcut.java b/src/org/openstreetmap/josm/tools/Shortcut.java index 317b69bf2f1..3adf77cf689 100644 --- a/src/org/openstreetmap/josm/tools/Shortcut.java +++ b/src/org/openstreetmap/josm/tools/Shortcut.java @@ -27,13 +27,13 @@ /** * Global shortcut class. - * + *

    * Note: This class represents a single shortcut, contains the factory to obtain * shortcut objects from, manages shortcuts and shortcut collisions, and * finally manages loading and saving shortcuts to/from the preferences. - * + *

    * Action authors: You only need the {@link #registerShortcut} factory. Ignore everything else. - * + *

    * All: Use only public methods that are also marked to be used. The others are * public so the shortcut preferences can use them. * @since 1084 @@ -432,6 +432,11 @@ private static int findModifier(int group, Integer modifier) { } // shutdown handling + + /** + * Save shortcuts to preferences + * @return {@code true} if preferences were changed + */ public static boolean savePrefs() { return shortcuts.stream() .map(Shortcut::save) @@ -484,7 +489,7 @@ public static List registerMultiShortcuts(String shortText, String lon for (Character c : characters) { Integer code = (int) c; result.add(registerShortcut( - new StringBuilder(shortText).append(" (").append(i).append(')').toString(), longText, + shortText + " (" + i + ')', longText, // Add extended keyCode if not a regular one regularKeyCodes.containsKey(code) ? regularKeyCodes.get(code) : isDeadKey(code) ? code : c | KeyboardUtils.EXTENDED_KEYCODE_FLAG, @@ -500,7 +505,7 @@ static boolean isDeadKey(int keyCode) { /** * Register a shortcut. - * + *

    * Here you get your shortcuts from. The parameters are: * * @param shortText an ID. re-use a {@code "system:*"} ID if possible, else use something unique. @@ -622,10 +627,10 @@ private static KeyStroke getKeyStrokeForShortKey(String shortKey) { /** * Returns the tooltip text plus the {@linkplain #getKeyText(KeyStroke) key stroke text}. - * + *

    * Tooltips are usually not system dependent, unless the * JVM is too dumb to provide correct names for all the keys. - * + *

    * Some LAFs don't understand HTML, such as the OSX LAFs. * * @param tooltip Tooltip text to display diff --git a/tools/ivy.xml b/tools/ivy.xml index 6ad3330950f..22c911aef1b 100644 --- a/tools/ivy.xml +++ b/tools/ivy.xml @@ -30,7 +30,7 @@ - +