Changeset 11553 in josm for trunk/src/org


Ignore:
Timestamp:
2017-02-12T16:32:18+01:00 (7 years ago)
Author:
Don-vip
Message:

refactor handling of null values - use Java 8 Optional where possible

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

Legend:

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

    r11389 r11553  
    1717import java.util.Map;
    1818import java.util.Objects;
     19import java.util.Optional;
    1920import java.util.Set;
    2021import java.util.Stack;
     
    520521
    521522        protected List<NodePair> getOutboundPairs(Node node) {
    522             List<NodePair> l = successors.get(node);
    523             if (l == null)
    524                 return Collections.emptyList();
    525             return l;
     523            return Optional.ofNullable(successors.get(node)).orElseGet(Collections::emptyList);
    526524        }
    527525
  • trunk/src/org/openstreetmap/josm/actions/HelpAction.java

    r9320 r11553  
    88import java.awt.event.ActionEvent;
    99import java.awt.event.KeyEvent;
     10import java.util.Optional;
    1011
    1112import javax.swing.SwingUtilities;
     
    6263                topic = HelpUtil.getContextSpecificHelpTopic(SwingUtilities.getDeepestComponentAt(Main.parent, mouse.x, mouse.y));
    6364            }
    64             if (topic == null) {
    65                 HelpBrowser.setUrlForHelpTopic("/");
    66             } else {
    67                 HelpBrowser.setUrlForHelpTopic(topic);
    68             }
     65            HelpBrowser.setUrlForHelpTopic(Optional.ofNullable(topic).orElse("/"));
    6966        } else {
    7067            HelpBrowser.setUrlForHelpTopic("/");
  • trunk/src/org/openstreetmap/josm/actions/MergeNodesAction.java

    r11481 r11553  
    1515import java.util.List;
    1616import java.util.Objects;
     17import java.util.Optional;
    1718import java.util.Set;
    1819
     
    176177            lastNode = n;
    177178        }
    178         if (targetNode == null) {
    179             targetNode = oldestNode != null ? oldestNode : lastNode;
    180         }
    181         return targetNode;
    182     }
    183 
     179        return Optional.ofNullable(targetNode).orElse(oldestNode != null ? oldestNode : lastNode);
     180    }
    184181
    185182    /**
  • trunk/src/org/openstreetmap/josm/actions/PurgeAction.java

    r11343 r11553  
    307307    protected void updateEnabledState() {
    308308        DataSet ds = getLayerManager().getEditDataSet();
    309         if (ds == null) {
    310             setEnabled(false);
    311         } else {
    312             setEnabled(!ds.selectionEmpty());
    313         }
     309        setEnabled(ds != null && !ds.selectionEmpty());
    314310    }
    315311
  • trunk/src/org/openstreetmap/josm/actions/SplitWayAction.java

    r11452 r11553  
    1818import java.util.LinkedList;
    1919import java.util.List;
     20import java.util.Optional;
    2021import java.util.Set;
    2122import java.util.concurrent.atomic.AtomicInteger;
     
    562563            }
    563564            Relation c = null;
    564             String type = r.get("type");
    565             if (type == null) {
    566                 type = "";
    567             }
     565            String type = Optional.ofNullable(r.get("type")).orElse("");
    568566
    569567            int ic = 0;
  • trunk/src/org/openstreetmap/josm/actions/UpdateSelectionAction.java

    r10548 r11553  
    1010import java.util.Collection;
    1111import java.util.Collections;
     12import java.util.Optional;
    1213
    1314import javax.swing.JOptionPane;
     
    7273    public static void updatePrimitive(PrimitiveId id) {
    7374        ensureParameterNotNull(id, "id");
    74         if (Main.getLayerManager().getEditLayer() == null)
    75             throw new IllegalStateException(tr("No current dataset found"));
    76         OsmPrimitive primitive = Main.getLayerManager().getEditLayer().data.getPrimitiveById(id);
    77         if (primitive == null)
    78             throw new IllegalStateException(tr("Did not find an object with id {0} in the current dataset", id));
    79         updatePrimitives(Collections.singleton(primitive));
     75        updatePrimitives(Collections.singleton(Optional.ofNullable(Optional.ofNullable(
     76                Main.getLayerManager().getEditLayer()).orElseThrow(
     77                        () -> new IllegalStateException(tr("No current dataset found")))
     78                .data.getPrimitiveById(id)).orElseThrow(
     79                        () -> new IllegalStateException(tr("Did not find an object with id {0} in the current dataset", id)))));
    8080    }
    8181
  • trunk/src/org/openstreetmap/josm/actions/ValidateAction.java

    r10880 r11553  
    1010import java.util.Collection;
    1111import java.util.List;
     12import java.util.Optional;
    1213
    1314import org.openstreetmap.josm.Main;
     
    5556     * <p>
    5657     * If getSelectedItems is true, the selected items (or all items, if no one
    57      * is selected) are validated. If it is false, last selected items are
    58      * revalidated
     58     * is selected) are validated. If it is false, last selected items are revalidated
    5959     *
    6060     * @param getSelectedItems If selected or last selected items must be validated
     
    8383            }
    8484        } else {
    85             if (lastSelection == null) {
    86                 selection = Main.getLayerManager().getEditDataSet().allNonDeletedPrimitives();
    87             } else {
    88                 selection = lastSelection;
    89             }
     85            selection = Optional.ofNullable(lastSelection).orElseGet(
     86                    () -> Main.getLayerManager().getEditDataSet().allNonDeletedPrimitives());
    9087        }
    9188
    92         ValidationTask task = new ValidationTask(tests, selection, lastSelection);
    93         Main.worker.submit(task);
     89        Main.worker.submit(new ValidationTask(tests, selection, lastSelection));
    9490    }
    9591
  • trunk/src/org/openstreetmap/josm/actions/downloadtasks/DownloadOsmTask.java

    r10436 r11553  
    88import java.util.ArrayList;
    99import java.util.Collection;
     10import java.util.Optional;
    1011import java.util.concurrent.Future;
    1112import java.util.regex.Matcher;
     
    270271            OsmDataLayer layer = addNewLayerIfRequired(newLayerName);
    271272            if (layer == null) {
    272                 layer = getEditLayer();
    273                 if (layer == null) {
    274                     layer = getFirstDataLayer();
    275                 }
     273                layer = Optional.ofNullable(getEditLayer()).orElseGet(this::getFirstDataLayer);
    276274                layer.mergeFrom(dataSet);
    277275                if (zoomAfterDownload) {
  • trunk/src/org/openstreetmap/josm/actions/mapmode/SelectAction.java

    r11452 r11553  
    12611261     */
    12621262    protected static <T> Collection<T> asColl(T o) {
    1263         if (o == null)
    1264             return Collections.emptySet();
    1265         return Collections.singleton(o);
     1263        return o == null ? Collections.emptySet() : Collections.singleton(o);
    12661264    }
    12671265}
  • trunk/src/org/openstreetmap/josm/actions/search/SearchCompiler.java

    r11453 r11553  
    1616import java.util.Locale;
    1717import java.util.Map;
     18import java.util.Optional;
    1819import java.util.function.Predicate;
    1920import java.util.regex.Matcher;
     
    419420        @Override
    420421        public boolean match(Tagged osm) {
    421             Boolean ret = OsmUtils.getOsmBoolean(osm.get(key));
    422             if (ret == null)
    423                 return defaultValue;
    424             else
    425                 return ret;
     422            return Optional.ofNullable(OsmUtils.getOsmBoolean(osm.get(key))).orElse(defaultValue);
    426423        }
    427424
     
    949946            this.type = OsmPrimitiveType.from(type);
    950947            if (this.type == null)
    951                 throw new ParseError(tr("Unknown primitive type: {0}. Allowed values are node, way or relation",
    952                         type));
     948                throw new ParseError(tr("Unknown primitive type: {0}. Allowed values are node, way or relation", type));
    953949        }
    954950
     
    16231619     */
    16241620    public Match parse() throws ParseError {
    1625         Match m = parseExpression();
     1621        Match m = Optional.ofNullable(parseExpression()).orElse(Always.INSTANCE);
    16261622        if (!tokenizer.readIfEqual(Token.EOF))
    16271623            throw new ParseError(tr("Unexpected token: {0}", tokenizer.nextToken()));
    1628         if (m == null)
    1629             m = Always.INSTANCE;
    16301624        Main.debug("Parsed search expression is {0}", m);
    16311625        return m;
     
    17581752
    17591753    private Match parseFactor(String errorMessage) throws ParseError {
    1760         Match fact = parseFactor();
    1761         if (fact == null)
    1762             throw new ParseError(errorMessage);
    1763         else
    1764             return fact;
     1754        return Optional.ofNullable(parseFactor()).orElseThrow(() -> new ParseError(errorMessage));
    17651755    }
    17661756
  • trunk/src/org/openstreetmap/josm/command/AddPrimitivesCommand.java

    r11374 r11553  
    99import java.util.List;
    1010import java.util.Objects;
     11import java.util.Optional;
    1112
    1213import javax.swing.Icon;
     
    169170        Collection<OsmPrimitive> prims = new HashSet<>();
    170171        for (PrimitiveData d : data) {
    171             OsmPrimitive osm = getAffectedDataSet().getPrimitiveById(d);
    172             if (osm == null)
    173                 throw new JosmRuntimeException("No primitive found for " + d);
    174             prims.add(osm);
     172            prims.add(Optional.ofNullable(getAffectedDataSet().getPrimitiveById(d)).orElseThrow(
     173                    () -> new JosmRuntimeException("No primitive found for " + d)));
    175174        }
    176175        return prims;
  • trunk/src/org/openstreetmap/josm/data/Preferences.java

    r11527 r11553  
    283283     */
    284284    public void removeKeyPreferenceChangeListener(String key, PreferenceChangedListener listener) {
    285         ListenerList<PreferenceChangedListener> keyListener = keyListeners.get(key);
    286         if (keyListener == null) {
    287             throw new IllegalArgumentException("There are no listeners registered for " + key);
    288         }
    289         keyListener.removeListener(listener);
     285        Optional.ofNullable(keyListeners.get(key)).orElseThrow(
     286                () -> new IllegalArgumentException("There are no listeners registered for " + key))
     287        .removeListener(listener);
    290288    }
    291289
     
    11511149     */
    11521150    public <T> List<T> getListOfStructs(String key, Class<T> klass) {
    1153         List<T> r = getListOfStructs(key, null, klass);
    1154         if (r == null)
    1155             return Collections.emptyList();
    1156         else
    1157             return r;
     1151        return Optional.ofNullable(getListOfStructs(key, null, klass)).orElseGet(Collections::emptyList);
    11581152    }
    11591153
     
    11711165        if (prop == null)
    11721166            return def == null ? null : new ArrayList<>(def);
    1173         List<T> lst = new ArrayList<>();
    1174         for (Map<String, String> entries : prop) {
    1175             T struct = deserializeStruct(entries, klass);
    1176             lst.add(struct);
    1177         }
    1178         return lst;
     1167        return prop.stream().map(p -> deserializeStruct(p, klass)).collect(Collectors.toList());
    11791168    }
    11801169
     
    12041193        Collection<Map<String, String>> vals = new ArrayList<>();
    12051194        for (T struct : l) {
    1206             if (struct == null) {
    1207                 continue;
    1208             }
    1209             vals.add(serializeStruct(struct, klass));
     1195            if (struct != null) {
     1196                vals.add(serializeStruct(struct, klass));
     1197            }
    12101198        }
    12111199        return vals;
  • trunk/src/org/openstreetmap/josm/data/SystemOfMeasurement.java

    r11452 r11553  
    99import java.util.Locale;
    1010import java.util.Map;
     11import java.util.Optional;
    1112import java.util.concurrent.CopyOnWriteArrayList;
    1213
     
    115116     */
    116117    public static SystemOfMeasurement getSystemOfMeasurement() {
    117         SystemOfMeasurement som = SystemOfMeasurement.ALL_SYSTEMS.get(ProjectionPreference.PROP_SYSTEM_OF_MEASUREMENT.get());
    118         if (som == null)
    119             return SystemOfMeasurement.METRIC;
    120         return som;
     118        return Optional.ofNullable(SystemOfMeasurement.ALL_SYSTEMS.get(ProjectionPreference.PROP_SYSTEM_OF_MEASUREMENT.get()))
     119                .orElse(SystemOfMeasurement.METRIC);
    121120    }
    122121
  • trunk/src/org/openstreetmap/josm/data/UndoRedoHandler.java

    r11240 r11553  
    55import java.util.Iterator;
    66import java.util.LinkedList;
     7import java.util.Optional;
    78
    89import org.openstreetmap.josm.Main;
     
    7475     */
    7576    public synchronized void add(final Command c) {
    76         DataSet ds = c.getAffectedDataSet();
    77         if (ds == null) {
    78             // old, legacy behaviour
    79             ds = Main.getLayerManager().getEditDataSet();
    80         }
     77        DataSet ds = Optional.ofNullable(c.getAffectedDataSet()).orElseGet(() -> Main.getLayerManager().getEditDataSet());
    8178        Collection<? extends OsmPrimitive> oldSelection = null;
    8279        if (ds != null) {
  • trunk/src/org/openstreetmap/josm/data/gpx/ImmutableGpxTrack.java

    r10906 r11553  
    7070    @Override
    7171    public Bounds getBounds() {
    72         if (bounds == null)
    73             return null;
    74         else
    75             return new Bounds(bounds);
     72        return bounds == null ? null : new Bounds(bounds);
    7673    }
    7774
  • trunk/src/org/openstreetmap/josm/data/gpx/ImmutableGpxTrackSegment.java

    r10906 r11553  
    5454    @Override
    5555    public Bounds getBounds() {
    56         if (bounds == null)
    57             return null;
    58         else
    59             return new Bounds(bounds);
     56        return bounds == null ? null : new Bounds(bounds);
    6057    }
    6158
  • trunk/src/org/openstreetmap/josm/data/imagery/TMSCachedTileLoaderJob.java

    r11452 r11553  
    1111import java.util.Map;
    1212import java.util.Map.Entry;
     13import java.util.Optional;
    1314import java.util.Set;
    1415import java.util.concurrent.ConcurrentHashMap;
     
    9091        if (tile != null) {
    9192            TileSource tileSource = tile.getTileSource();
    92             String tsName = tileSource.getName();
    93             if (tsName == null) {
    94                 tsName = "";
    95             }
    96             return tsName.replace(':', '_') + ':' + tileSource.getTileId(tile.getZoom(), tile.getXtile(), tile.getYtile());
     93            return Optional.ofNullable(tileSource.getName()).orElse("").replace(':', '_') + ':'
     94                    + tileSource.getTileId(tile.getZoom(), tile.getXtile(), tile.getYtile());
    9795        }
    9896        return null;
  • trunk/src/org/openstreetmap/josm/data/imagery/WMTSTileSource.java

    r11516 r11553  
    1717import java.util.Map;
    1818import java.util.Map.Entry;
     19import java.util.Optional;
    1920import java.util.Set;
    2021import java.util.SortedSet;
     
    479480     */
    480481    private static TileMatrix parseTileMatrix(XMLStreamReader reader, String matrixCrs) throws XMLStreamException {
    481         Projection matrixProj = Projections.getProjectionByCode(matrixCrs);
     482        Projection matrixProj = Optional.ofNullable(Projections.getProjectionByCode(matrixCrs))
     483                .orElseGet(Main::getProjection); // use current projection if none found. Maybe user is using custom string
    482484        TileMatrix ret = new TileMatrix();
    483 
    484         if (matrixProj == null) {
    485             // use current projection if none found. Maybe user is using custom string
    486             matrixProj = Main.getProjection();
    487         }
    488485        for (int event = reader.getEventType();
    489486                reader.hasNext() && !(event == XMLStreamReader.END_ELEMENT && QN_TILEMATRIX.equals(reader.getName()));
  • trunk/src/org/openstreetmap/josm/data/osm/Relation.java

    r11383 r11553  
    99import java.util.List;
    1010import java.util.Map;
     11import java.util.Optional;
    1112import java.util.Set;
    1213import java.util.stream.Collectors;
     
    264265            List<RelationMember> newMembers = new ArrayList<>();
    265266            for (RelationMemberData member : relationData.getMembers()) {
    266                 OsmPrimitive primitive = getDataSet().getPrimitiveById(member);
    267                 if (primitive == null)
    268                     throw new AssertionError("Data consistency problem - relation with missing member detected");
    269                 newMembers.add(new RelationMember(member.getRole(), primitive));
     267                newMembers.add(new RelationMember(member.getRole(), Optional.ofNullable(getDataSet().getPrimitiveById(member))
     268                        .orElseThrow(() -> new AssertionError("Data consistency problem - relation with missing member detected"))));
    270269            }
    271270            setMembers(newMembers);
  • trunk/src/org/openstreetmap/josm/data/osm/RelationMember.java

    r10662 r11553  
    44import java.util.Arrays;
    55import java.util.Objects;
     6import java.util.Optional;
    67
    78import org.openstreetmap.josm.tools.CheckParameterUtil;
     
    133134    public RelationMember(String role, OsmPrimitive member) {
    134135        CheckParameterUtil.ensureParameterNotNull(member, "member");
    135         if (role == null) {
    136             role = "";
    137         }
    138         this.role = role;
     136        this.role = Optional.ofNullable(role).orElse("");
    139137        this.member = member;
    140138    }
     
    150148    }
    151149
    152     @Override public String toString() {
     150    @Override
     151    public String toString() {
    153152        return '"' + role + "\"=" + member;
    154153    }
  • trunk/src/org/openstreetmap/josm/data/osm/TagMap.java

    r10755 r11553  
    1313import java.util.Map;
    1414import java.util.NoSuchElementException;
     15import java.util.Objects;
    1516import java.util.Set;
    1617
     
    193194    @Override
    194195    public synchronized String put(String key, String value) {
    195         if (key == null) {
    196             throw new NullPointerException();
    197         }
    198         if (value == null) {
    199             throw new NullPointerException();
    200         }
     196        Objects.requireNonNull(key);
     197        Objects.requireNonNull(value);
    201198        int index = indexOfKey(tags, key);
    202199        int newTagArrayLength = tags.length;
  • trunk/src/org/openstreetmap/josm/data/osm/event/DataChangedEvent.java

    r5170 r11553  
    1313    private final List<AbstractDatasetChangedEvent> events;
    1414
     15    /**
     16     * Constructs a new {@code DataChangedEvent}
     17     * @param dataSet data set
     18     * @param events list of change events
     19     */
    1520    public DataChangedEvent(DataSet dataSet, List<AbstractDatasetChangedEvent> events) {
    1621        super(dataSet);
     
    1823    }
    1924
     25    /**
     26     * Constructs a new {@code DataChangedEvent}
     27     * @param dataSet data set
     28     */
    2029    public DataChangedEvent(DataSet dataSet) {
    2130        this(dataSet, null);
     
    2938    @Override
    3039    public Collection<OsmPrimitive> getPrimitives() {
    31         if (dataSet == null)
    32             return Collections.emptyList();
    33         else
    34             return dataSet.allPrimitives();
     40        return dataSet == null ? Collections.emptyList() : dataSet.allPrimitives();
    3541    }
    3642
     
    4147
    4248    /**
    43      *
     49     * Returns list of events that caused this DataChangedEvent.
    4450     * @return List of events that caused this DataChangedEvent. Might be null
    4551     */
     
    4753        return events;
    4854    }
    49 
    5055}
  • trunk/src/org/openstreetmap/josm/data/osm/history/HistoryOsmPrimitive.java

    r10378 r11553  
    197197
    198198    /**
    199      * Sets the tags for this history primitive. Removes all
    200      * tags if <code>tags</code> is null.
     199     * Sets the tags for this history primitive. Removes all tags if <code>tags</code> is null.
    201200     *
    202201     * @param tags the tags. May be null.
  • trunk/src/org/openstreetmap/josm/data/osm/visitor/paint/PaintColors.java

    r10874 r11553  
    66import java.awt.Color;
    77import java.util.List;
     8import java.util.Optional;
    89
    910import org.openstreetmap.josm.data.preferences.CachingProperty;
     
    7980    }
    8081
     82    /**
     83     * Returns the background color.
     84     * @return the background color
     85     */
    8186    public static Color getBackgroundColor() {
    8287        if (backgroundColorCache != null)
     
    9297            }
    9398        }
    94         if (backgroundColorCache == null) {
    95             return BACKGROUND.get();
    96         } else {
    97             return backgroundColorCache;
    98         }
     99        return Optional.ofNullable(backgroundColorCache).orElseGet(BACKGROUND::get);
    99100    }
    100101
  • trunk/src/org/openstreetmap/josm/data/osm/visitor/paint/StyledMapRenderer.java

    r11452 r11553  
    11181118                    lastNode = tmp;
    11191119                } else {
    1120                     onewayvia = OsmUtils.getOsmBoolean(onewayviastr);
    1121                     if (onewayvia == null) {
    1122                         onewayvia = Boolean.FALSE;
    1123                     }
     1120                    onewayvia = Optional.ofNullable(OsmUtils.getOsmBoolean(onewayviastr)).orElse(Boolean.FALSE);
    11241121                }
    11251122            }
  • trunk/src/org/openstreetmap/josm/data/osm/visitor/paint/relations/Multipolygon.java

    r11385 r11553  
    1111import java.util.Iterator;
    1212import java.util.List;
     13import java.util.Optional;
    1314import java.util.Set;
    1415
     
    668669
    669670            for (PolyData pdInner: innerPolygons) {
    670                 PolyData o = findOuterPolygon(pdInner, combinedPolygons);
    671                 if (o == null) {
    672                     o = outerPolygons.get(0);
    673                 }
    674                 o.addInner(pdInner);
     671                Optional.ofNullable(findOuterPolygon(pdInner, combinedPolygons)).orElseGet(() -> outerPolygons.get(0))
     672                    .addInner(pdInner);
    675673            }
    676674        }
  • trunk/src/org/openstreetmap/josm/data/preferences/AbstractProperty.java

    r11496 r11553  
    3838            if (this == obj)
    3939                return true;
    40             if (obj == null)
    41                 return false;
    42             if (getClass() != obj.getClass())
     40            if (obj == null || getClass() != obj.getClass())
    4341                return false;
    4442            @SuppressWarnings("unchecked")
     
    285283        if (this == obj)
    286284            return true;
    287         if (obj == null)
    288             return false;
    289         if (getClass() != obj.getClass())
     285        if (obj == null || getClass() != obj.getClass())
    290286            return false;
    291287        AbstractProperty<?> other = (AbstractProperty<?>) obj;
  • trunk/src/org/openstreetmap/josm/data/preferences/PreferencesReader.java

    r11453 r11553  
    1616import java.util.List;
    1717import java.util.Map;
     18import java.util.Optional;
    1819import java.util.SortedMap;
    1920import java.util.TreeMap;
     
    173174                        setting = new StringSetting(null);
    174175                    } else {
    175                         String value = parser.getAttributeValue(null, "value");
    176                         if (value == null) {
    177                             throw new XMLStreamException(tr("value expected"), parser.getLocation());
    178                         }
    179                         setting = new StringSetting(value);
     176                        setting = new StringSetting(Optional.ofNullable(parser.getAttributeValue(null, "value"))
     177                                .orElseThrow(() -> new XMLStreamException(tr("value expected"), parser.getLocation())));
    180178                    }
    181179                    if (defaults) {
  • trunk/src/org/openstreetmap/josm/data/preferences/PreferencesWriter.java

    r10824 r11553  
    66import java.util.List;
    77import java.util.Map;
     8import java.util.Optional;
    89import java.util.stream.Stream;
    910
     
    6869    private void addTime(Setting<?> setting) {
    6970        if (defaults) {
    70             Long time = setting.getTime();
    71             if (time == null)
    72                 throw new IllegalStateException();
    73             out.write("' time='" + time);
     71            out.write("' time='" + Optional.ofNullable(setting.getTime()).orElseThrow(IllegalStateException::new));
    7472        }
    7573    }
  • trunk/src/org/openstreetmap/josm/data/projection/CustomProjection.java

    r11100 r11553  
    1010import java.util.List;
    1111import java.util.Map;
     12import java.util.Optional;
    1213import java.util.concurrent.ConcurrentHashMap;
    1314import java.util.regex.Matcher;
     
    2223import org.openstreetmap.josm.data.projection.datum.Datum;
    2324import org.openstreetmap.josm.data.projection.datum.NTV2Datum;
    24 import org.openstreetmap.josm.data.projection.datum.NTV2GridShiftFileWrapper;
    2525import org.openstreetmap.josm.data.projection.datum.NullDatum;
    2626import org.openstreetmap.josm.data.projection.datum.SevenParameterDatum;
     
    252252            // "utm" is a shortcut for a set of parameters
    253253            if ("utm".equals(parameters.get(Param.proj.key))) {
    254                 String zoneStr = parameters.get(Param.zone.key);
    255                 if (zoneStr == null)
    256                     throw new ProjectionConfigurationException(tr("UTM projection (''+proj=utm'') requires ''+zone=...'' parameter."));
    257254                Integer zone;
    258255                try {
    259                     zone = Integer.valueOf(zoneStr);
     256                    zone = Integer.valueOf(Optional.ofNullable(parameters.get(Param.zone.key)).orElseThrow(
     257                            () -> new ProjectionConfigurationException(tr("UTM projection (''+proj=utm'') requires ''+zone=...'' parameter."))));
    260258                } catch (NumberFormatException e) {
    261259                    zone = null;
     
    394392        String initKey = parameters.get(Param.init.key);
    395393        if (initKey != null) {
    396             String init = Projections.getInit(initKey);
    397             if (init == null)
    398                 throw new ProjectionConfigurationException(tr("Value ''{0}'' for option +init not supported.", initKey));
    399394            Map<String, String> initp;
    400395            try {
    401                 initp = parseParameterList(init, ignoreUnknownParameter);
     396                initp = parseParameterList(Optional.ofNullable(Projections.getInit(initKey)).orElseThrow(
     397                        () -> new ProjectionConfigurationException(tr("Value ''{0}'' for option +init not supported.", initKey))),
     398                        ignoreUnknownParameter);
    402399                initp = resolveInits(initp, ignoreUnknownParameter);
    403400            } catch (ProjectionConfigurationException ex) {
     
    419416        String code = parameters.get(Param.ellps.key);
    420417        if (code != null) {
    421             Ellipsoid ellipsoid = Projections.getEllipsoid(code);
    422             if (ellipsoid == null) {
    423                 throw new ProjectionConfigurationException(tr("Ellipsoid ''{0}'' not supported.", code));
    424             } else {
    425                 return ellipsoid;
    426             }
     418            return Optional.ofNullable(Projections.getEllipsoid(code)).orElseThrow(
     419                () -> new ProjectionConfigurationException(tr("Ellipsoid ''{0}'' not supported.", code)));
    427420        }
    428421        String s = parameters.get(Param.a.key);
     
    465458        String datumId = parameters.get(Param.datum.key);
    466459        if (datumId != null) {
    467             Datum datum = Projections.getDatum(datumId);
    468             if (datum == null) throw new ProjectionConfigurationException(tr("Unknown datum identifier: ''{0}''", datumId));
    469             return datum;
     460            return Optional.ofNullable(Projections.getDatum(datumId)).orElseThrow(
     461                    () -> new ProjectionConfigurationException(tr("Unknown datum identifier: ''{0}''", datumId)));
    470462        }
    471463        if (ellps == null) {
     
    483475            if ("null".equals(nadgridsId))
    484476                return new NullDatum(null, ellps);
    485             NTV2GridShiftFileWrapper nadgrids = Projections.getNTV2Grid(nadgridsId);
    486             if (nadgrids == null)
    487                 throw new ProjectionConfigurationException(tr("Grid shift file ''{0}'' for option +nadgrids not supported.", nadgridsId));
    488             return new NTV2Datum(nadgridsId, null, ellps, nadgrids);
     477            final String fNadgridsId = nadgridsId;
     478            return new NTV2Datum(fNadgridsId, null, ellps, Optional.ofNullable(Projections.getNTV2Grid(fNadgridsId)).orElseThrow(
     479                    () -> new ProjectionConfigurationException(tr("Grid shift file ''{0}'' for option +nadgrids not supported.", fNadgridsId))));
    489480        }
    490481
     
    627618        if (!parameters.containsKey(parameterName))
    628619            throw new ProjectionConfigurationException(tr("Unknown parameter ''{0}''", parameterName));
    629         String doubleStr = parameters.get(parameterName);
    630         if (doubleStr == null)
    631             throw new ProjectionConfigurationException(
    632                     tr("Expected number argument for parameter ''{0}''", parameterName));
    633         return parseDouble(doubleStr, parameterName);
     620        return parseDouble(Optional.ofNullable(parameters.get(parameterName)).orElseThrow(
     621                () -> new ProjectionConfigurationException(tr("Expected number argument for parameter ''{0}''", parameterName))),
     622                parameterName);
    634623    }
    635624
  • trunk/src/org/openstreetmap/josm/data/projection/datum/NTV2SubGrid.java

    r10680 r11553  
    274274
    275275    public int getSubGridCount() {
    276         return (subGrid == null) ? 0 : subGrid.length;
     276        return subGrid == null ? 0 : subGrid.length;
    277277    }
    278278
  • trunk/src/org/openstreetmap/josm/data/validation/Test.java

    r11023 r11553  
    99import java.util.List;
    1010import java.util.Objects;
     11import java.util.Optional;
    1112import java.util.function.Predicate;
    1213
     
    149150     */
    150151    public void startTest(ProgressMonitor progressMonitor) {
    151         if (progressMonitor == null) {
    152             this.progressMonitor = NullProgressMonitor.INSTANCE;
    153         } else {
    154             this.progressMonitor = progressMonitor;
    155         }
     152        this.progressMonitor = Optional.ofNullable(progressMonitor).orElse(NullProgressMonitor.INSTANCE);
    156153        String startMessage = tr("Running test {0}", name);
    157154        this.progressMonitor.beginTask(startMessage);
  • trunk/src/org/openstreetmap/josm/data/validation/util/MultipleNameVisitor.java

    r10137 r11553  
    55
    66import java.util.Collection;
     7import java.util.Optional;
    78
    89import javax.swing.Icon;
     
    4243        multipleClassname = null;
    4344        for (OsmPrimitive osm : data) {
    44             String name = osm.get("name");
    45             if (name == null) {
    46                 name = osm.get("ref");
    47             }
     45            String name = Optional.ofNullable(osm.get("name")).orElseGet(() -> osm.get("ref"));
    4846            if (name != null && !name.isEmpty() && multipleName.length() <= MULTIPLE_NAME_MAX_LENGTH) {
    4947                if (multipleName.length() > 0) {
  • trunk/src/org/openstreetmap/josm/gui/IconToggleButton.java

    r11386 r11553  
    44import java.beans.PropertyChangeEvent;
    55import java.beans.PropertyChangeListener;
     6import java.util.Optional;
    67
    78import javax.swing.Action;
     
    152153    @Override
    153154    public Icon getIcon() {
    154         Object o = getSafeActionValue(Action.LARGE_ICON_KEY);
    155         if (o == null)
    156             o = getSafeActionValue(Action.SMALL_ICON);
    157         return (Icon) o;
     155        return (Icon) Optional.ofNullable(getSafeActionValue(Action.LARGE_ICON_KEY)).orElseGet(() -> getSafeActionValue(Action.SMALL_ICON));
    158156    }
    159157
  • trunk/src/org/openstreetmap/josm/gui/MapMover.java

    r10670 r11553  
    1212import java.awt.event.MouseWheelEvent;
    1313import java.util.ArrayList;
     14import java.util.Optional;
    1415
    1516import javax.swing.AbstractAction;
     
    7374        public void actionPerformed(ActionEvent e) {
    7475            if (".".equals(action) || ",".equals(action)) {
    75                 Point mouse = nc.getMousePosition();
    76                 if (mouse == null)
    77                     mouse = new Point((int) nc.getBounds().getCenterX(), (int) nc.getBounds().getCenterY());
    78                 MouseWheelEvent we = new MouseWheelEvent(nc, e.getID(), e.getWhen(), e.getModifiers(), mouse.x, mouse.y, 0, false,
    79                         MouseWheelEvent.WHEEL_UNIT_SCROLL, 1, ",".equals(action) ? -1 : 1);
    80                 mouseWheelMoved(we);
     76                Point mouse = Optional.ofNullable(nc.getMousePosition()).orElseGet(
     77                    () -> new Point((int) nc.getBounds().getCenterX(), (int) nc.getBounds().getCenterY()));
     78                mouseWheelMoved(new MouseWheelEvent(nc, e.getID(), e.getWhen(), e.getModifiers(), mouse.x, mouse.y, 0, false,
     79                        MouseWheelEvent.WHEEL_UNIT_SCROLL, 1, ",".equals(action) ? -1 : 1));
    8180            } else {
    8281                EastNorth center = nc.getCenter();
  • trunk/src/org/openstreetmap/josm/gui/MapViewState.java

    r11470 r11553  
    1212import java.io.Serializable;
    1313import java.util.Objects;
     14import java.util.Optional;
    1415
    1516import javax.swing.JComponent;
     
    376377
    377378    private static EastNorth calculateDefaultCenter() {
    378         Bounds b = DownloadDialog.getSavedDownloadBounds();
    379         if (b == null) {
    380             b = Main.getProjection().getWorldBoundsLatLon();
    381         }
     379        Bounds b = Optional.ofNullable(DownloadDialog.getSavedDownloadBounds()).orElseGet(
     380                () -> Main.getProjection().getWorldBoundsLatLon());
    382381        return Main.getProjection().latlon2eastNorth(b.getCenter());
    383382    }
  • trunk/src/org/openstreetmap/josm/gui/conflict/tags/MultiValueResolutionDecision.java

    r9078 r11553  
    99import java.util.Collections;
    1010import java.util.List;
     11import java.util.Optional;
    1112
    1213import org.openstreetmap.josm.command.ChangePropertyCommand;
     
    122123     */
    123124    public void setNew(String value) {
    124         if (value == null) {
    125             value = "";
    126         }
    127         this.value = value;
     125        this.value = Optional.ofNullable(value).orElse("");
    128126        this.type = MultiValueDecisionType.KEEP_ONE;
    129 
    130127    }
    131128
  • trunk/src/org/openstreetmap/josm/gui/conflict/tags/RelationMemberConflictDecision.java

    r11452 r11553  
    66
    77import java.util.Objects;
     8import java.util.Optional;
    89
    910import org.openstreetmap.josm.data.osm.OsmPrimitive;
     
    5859
    5960    public void decide(RelationMemberConflictDecisionType decision) {
    60         if (decision == null) {
    61             decision = UNDECIDED;
    62         }
    63         this.decision = decision;
     61        this.decision = Optional.ofNullable(decision).orElse(UNDECIDED);
    6462    }
    6563
  • trunk/src/org/openstreetmap/josm/gui/dialogs/LatLonDialog.java

    r11072 r11553  
    1212import java.awt.event.WindowEvent;
    1313import java.util.Arrays;
     14import java.util.Optional;
    1415
    1516import javax.swing.BorderFactory;
     
    168169
    169170    public void setCoordinates(LatLon ll) {
    170         if (ll == null) {
    171             ll = LatLon.ZERO;
    172         }
    173         this.latLonCoordinates = ll;
    174         tfLatLon.setText(ll.latToString(CoordinateFormat.getDefaultFormat()) + ' ' + ll.lonToString(CoordinateFormat.getDefaultFormat()));
    175         EastNorth en = Main.getProjection().latlon2eastNorth(ll);
     171        latLonCoordinates = Optional.ofNullable(ll).orElse(LatLon.ZERO);
     172        tfLatLon.setText(latLonCoordinates.latToString(CoordinateFormat.getDefaultFormat()) + ' ' +
     173                         latLonCoordinates.lonToString(CoordinateFormat.getDefaultFormat()));
     174        EastNorth en = Main.getProjection().latlon2eastNorth(latLonCoordinates);
    176175        tfEastNorth.setText(Double.toString(en.east()) + ' ' + Double.toString(en.north()));
    177176        setOkEnabled(true);
  • trunk/src/org/openstreetmap/josm/gui/dialogs/properties/PropertiesCellRenderer.java

    r11552 r11553  
    1212import java.util.Map;
    1313import java.util.Objects;
     14import java.util.Optional;
    1415import java.util.concurrent.CopyOnWriteArrayList;
    1516
     
    4142
    4243    static {
    43         Color selectionBackground = UIManager.getColor("Table.selectionBackground");
    44         if (selectionBackground == null) {
    45             selectionBackground = Color.BLUE;
    46         }
    47         SELECTED_BG = new ColorProperty(marktr("Discardable key: selection Background"), selectionBackground).cached();
    48         Color background = UIManager.getColor("Table.background");
    49         if (background == null) {
    50             background = Color.WHITE;
    51         }
    52         NORMAL_BG = new ColorProperty(marktr("Discardable key: background"), background).cached();
     44        SELECTED_BG = new ColorProperty(marktr("Discardable key: selection Background"),
     45                Optional.ofNullable(UIManager.getColor("Table.selectionBackground")).orElse(Color.BLUE)).cached();
     46        NORMAL_BG = new ColorProperty(marktr("Discardable key: background"),
     47                Optional.ofNullable(UIManager.getColor("Table.background")).orElse(Color.WHITE)).cached();
    5348    }
    5449
  • trunk/src/org/openstreetmap/josm/gui/dialogs/properties/PropertiesDialog.java

    r11452 r11553  
    2828import java.util.Map;
    2929import java.util.Map.Entry;
     30import java.util.Optional;
    3031import java.util.Set;
    3132import java.util.TreeMap;
     
    556557
    557558        // Ignore parameter as we do not want to operate always on real selection here, especially in draw mode
    558         Collection<OsmPrimitive> newSel = Main.main.getInProgressSelection();
    559         if (newSel == null) {
    560             newSel = Collections.<OsmPrimitive>emptyList();
    561         }
    562 
     559        Collection<OsmPrimitive> newSel = Optional.ofNullable(Main.main.getInProgressSelection()).orElseGet(Collections::emptyList);
    563560        String selectedTag;
    564561        Relation selectedRelation = null;
     
    616613                if (ref instanceof Relation && !ref.isIncomplete() && !ref.isDeleted()) {
    617614                    Relation r = (Relation) ref;
    618                     MemberInfo mi = roles.get(r);
    619                     if (mi == null) {
    620                         mi = new MemberInfo(newSel);
    621                     }
     615                    MemberInfo mi = Optional.ofNullable(roles.get(r)).orElseGet(() -> new MemberInfo(newSel));
    622616                    roles.put(r, mi);
    623617                    int i = 1;
  • trunk/src/org/openstreetmap/josm/gui/dialogs/relation/ParentRelationLoadingTask.java

    r10616 r11553  
    77import java.util.ArrayList;
    88import java.util.List;
     9import java.util.Optional;
    910
    1011import javax.swing.JOptionPane;
     
    125126
    126127    protected void showLastException() {
    127         String msg = lastException.getMessage();
    128         if (msg == null) {
    129             msg = lastException.toString();
    130         }
    131128        JOptionPane.showMessageDialog(
    132129                Main.parent,
    133                 msg,
     130                Optional.ofNullable(lastException.getMessage()).orElseGet(lastException::toString),
    134131                tr("Error"),
    135132                JOptionPane.ERROR_MESSAGE
  • trunk/src/org/openstreetmap/josm/gui/dialogs/relation/RelationDialogManager.java

    r11461 r11553  
    1010import java.util.Map.Entry;
    1111import java.util.Objects;
     12import java.util.Optional;
    1213
    1314import org.openstreetmap.josm.Main;
     
    9293
    9394    /**
    94      * Register the relation editor for a relation managed by a
    95      * {@link OsmDataLayer}.
     95     * Register the relation editor for a relation managed by a {@link OsmDataLayer}.
    9696     *
    9797     * @param layer the layer
     
    100100     */
    101101    public void register(OsmDataLayer layer, Relation relation, RelationEditor editor) {
    102         if (relation == null) {
    103             relation = new Relation();
    104         }
    105         DialogContext context = new DialogContext(layer, relation);
    106         openDialogs.put(context, editor);
     102        openDialogs.put(new DialogContext(layer, Optional.ofNullable(relation).orElseGet(Relation::new)), editor);
    107103        editor.addWindowListener(this);
    108104    }
     
    110106    public void updateContext(OsmDataLayer layer, Relation relation, RelationEditor editor) {
    111107        // lookup the entry for editor and remove it
    112         //
    113108        for (Iterator<Entry<DialogContext, RelationEditor>> it = openDialogs.entrySet().iterator(); it.hasNext();) {
    114109            Entry<DialogContext, RelationEditor> entry = it.next();
     
    119114        }
    120115        // don't add a window listener. Editor is already known to the relation dialog manager
    121         //
    122         DialogContext context = new DialogContext(layer, relation);
    123         openDialogs.put(context, editor);
     116        openDialogs.put(new DialogContext(layer, relation), editor);
    124117    }
    125118
  • trunk/src/org/openstreetmap/josm/gui/help/ContextSensitiveHelpAction.java

    r10369 r11553  
    66
    77import java.awt.event.ActionEvent;
     8import java.util.Optional;
    89
    910import javax.swing.AbstractAction;
     
    2829     */
    2930    public void setHelpTopic(String relativeHelpTopic) {
    30         if (relativeHelpTopic == null)
    31             relativeHelpTopic = "/";
    32         this.helpTopic = relativeHelpTopic;
     31        helpTopic = Optional.ofNullable(relativeHelpTopic).orElse("/");
    3332    }
    3433
  • trunk/src/org/openstreetmap/josm/gui/history/HistoryBrowserModel.java

    r11397 r11553  
    309309            throw new IllegalArgumentException(
    310310                    tr("Failed to set reference. Reference ID {0} does not match history ID {1}.", reference.getId(), history.getId()));
    311         HistoryOsmPrimitive primitive = history.getByVersion(reference.getVersion());
    312         if (primitive == null)
     311        if (history.getByVersion(reference.getVersion()) == null)
    313312            throw new IllegalArgumentException(
    314313                    tr("Failed to set reference. Reference version {0} not available in history.", reference.getVersion()));
     
    340339            throw new IllegalArgumentException(
    341340                    tr("Failed to set reference. Reference ID {0} does not match history ID {1}.", current.getId(), history.getId()));
    342         HistoryOsmPrimitive primitive = history.getByVersion(current.getVersion());
    343         if (primitive == null)
     341        if (history.getByVersion(current.getVersion()) == null)
    344342            throw new IllegalArgumentException(
    345343                    tr("Failed to set current primitive. Current version {0} not available in history.", current.getVersion()));
     
    389387    /**
    390388     * Returns true if <code>primitive</code> is the latest primitive
    391      * representing the version currently edited in the current data
    392      * layer.
     389     * representing the version currently edited in the current data layer.
    393390     *
    394391     * @param primitive the primitive to check
     
    396393     */
    397394    public boolean isLatest(HistoryOsmPrimitive primitive) {
    398         if (primitive == null)
    399             return false;
    400         return primitive == latest;
     395        return primitive != null && primitive == latest;
    401396    }
    402397
  • trunk/src/org/openstreetmap/josm/gui/history/HistoryLoadTask.java

    r11087 r11553  
    135135        CheckParameterUtil.ensureParameterNotNull(primitives, "primitives");
    136136        for (OsmPrimitive primitive: primitives) {
    137             if (primitive == null) {
    138                 continue;
     137            if (primitive != null) {
     138                add(primitive);
    139139            }
    140             add(primitive);
    141140        }
    142141        return this;
  • trunk/src/org/openstreetmap/josm/gui/io/CloseChangesetTask.java

    r10611 r11553  
    88import java.util.Collection;
    99import java.util.List;
     10import java.util.Optional;
    1011
    1112import javax.swing.SwingUtilities;
     
    3839    public CloseChangesetTask(Collection<Changeset> changesets) {
    3940        super(tr("Closing changeset"), false /* don't ignore exceptions */);
    40         if (changesets == null) {
    41             changesets = new ArrayList<>();
    42         }
    43         this.changesets = changesets;
     41        this.changesets = Optional.ofNullable(changesets).orElseGet(ArrayList::new);
    4442        this.closedChangesets = new ArrayList<>();
    4543    }
  • trunk/src/org/openstreetmap/josm/gui/io/SaveLayerTask.java

    r10378 r11553  
    33
    44import static org.openstreetmap.josm.tools.I18n.tr;
     5
     6import java.util.Optional;
    57
    68import org.openstreetmap.josm.Main;
     
    3840    protected SaveLayerTask(SaveLayerInfo layerInfo, ProgressMonitor monitor) {
    3941        CheckParameterUtil.ensureParameterNotNull(layerInfo, "layerInfo");
    40         if (monitor == null) {
    41             monitor = NullProgressMonitor.INSTANCE;
    42         }
    4342        this.layerInfo = layerInfo;
    44         this.parentMonitor = monitor;
     43        this.parentMonitor = Optional.ofNullable(monitor).orElse(NullProgressMonitor.INSTANCE);
    4544    }
    4645
  • trunk/src/org/openstreetmap/josm/gui/io/TagSettingsPanel.java

    r10413 r11553  
    44import java.awt.BorderLayout;
    55import java.util.Map;
     6import java.util.Optional;
    67
    78import javax.swing.JPanel;
     
    125126            if (e.getSource() instanceof ChangesetCommentModel) {
    126127                String newValue = ((ChangesetCommentModel) e.getSource()).getComment();
    127                 String oldValue = getTagEditorValue(key);
    128                 if (oldValue == null) {
    129                     oldValue = "";
    130                 }
     128                String oldValue = Optional.ofNullable(getTagEditorValue(key)).orElse("");
    131129                if (!oldValue.equals(newValue)) {
    132130                    setProperty(key, newValue);
  • trunk/src/org/openstreetmap/josm/gui/io/UploadDialog.java

    r11452 r11553  
    2525import java.util.Map;
    2626import java.util.Map.Entry;
     27import java.util.Optional;
    2728import java.util.concurrent.TimeUnit;
    2829
     
    343344     */
    344345    public Changeset getChangeset() {
    345         Changeset cs = pnlChangesetManagement.getSelectedChangeset();
    346         if (cs == null) {
    347             cs = new Changeset();
    348         }
     346        Changeset cs = Optional.ofNullable(pnlChangesetManagement.getSelectedChangeset()).orElseGet(Changeset::new);
    349347        cs.setKeys(pnlTagSettings.getTags(false));
    350348        return cs;
  • trunk/src/org/openstreetmap/josm/gui/io/UploadLayerTask.java

    r11386 r11553  
    66import java.util.Collection;
    77import java.util.HashSet;
     8import java.util.Optional;
    89import java.util.Set;
    910
     
    6263        CheckParameterUtil.ensureParameterNotNull(layer, "layer");
    6364        CheckParameterUtil.ensureParameterNotNull(strategy, "strategy");
    64         if (monitor == null) {
    65             monitor = NullProgressMonitor.INSTANCE;
    66         }
    6765        this.layer = layer;
    68         this.monitor = monitor;
     66        this.monitor = Optional.ofNullable(monitor).orElse(NullProgressMonitor.INSTANCE);
    6967        this.changeset = changeset;
    7068        this.strategy = strategy;
  • trunk/src/org/openstreetmap/josm/gui/io/UploadNoteLayerTask.java

    r8624 r11553  
    33
    44import static org.openstreetmap.josm.tools.I18n.tr;
     5
     6import java.util.Optional;
    57
    68import org.openstreetmap.josm.actions.upload.UploadNotesTask;
     
    2931    public UploadNoteLayerTask(NoteLayer layer, ProgressMonitor monitor) {
    3032        CheckParameterUtil.ensureParameterNotNull(layer, "layer");
    31         if (monitor == null) {
    32             monitor = NullProgressMonitor.INSTANCE;
    33         }
    3433        this.layer = layer;
    35         this.monitor = monitor;
     34        this.monitor = Optional.ofNullable(monitor).orElse(NullProgressMonitor.INSTANCE);
    3635    }
    3736
  • trunk/src/org/openstreetmap/josm/gui/io/UploadedObjectsSummaryPanel.java

    r10378 r11553  
    99import java.util.ArrayList;
    1010import java.util.List;
     11import java.util.Optional;
    1112
    1213import javax.swing.AbstractListModel;
     
    174175
    175176        public void setPrimitives(List<OsmPrimitive> primitives) {
    176             if (primitives == null) {
    177                 this.primitives = new ArrayList<>();
    178             } else {
    179                 this.primitives = primitives;
    180             }
     177            this.primitives = Optional.ofNullable(primitives).orElseGet(ArrayList::new);
    181178            fireContentsChanged(this, 0, getSize());
    182179        }
  • trunk/src/org/openstreetmap/josm/gui/layer/Layer.java

    r10972 r11553  
    1111import java.io.File;
    1212import java.util.List;
     13import java.util.Optional;
    1314
    1415import javax.swing.AbstractAction;
     
    301302            removeColorPropertyListener();
    302303        }
    303         if (name == null) {
    304             name = "";
    305         }
    306 
    307304        String oldValue = this.name;
    308         this.name = name;
     305        this.name = Optional.ofNullable(name).orElse("");
    309306        if (!this.name.equals(oldValue)) {
    310307            propertyChangeSupport.firePropertyChange(NAME_PROP, oldValue, this.name);
  • trunk/src/org/openstreetmap/josm/gui/layer/geoimage/CorrelateGpxWithImages.java

    r11457 r11553  
    3737import java.util.Locale;
    3838import java.util.Objects;
     39import java.util.Optional;
    3940import java.util.TimeZone;
    4041import java.util.concurrent.TimeUnit;
     
    581582        JPanel panelTf = new JPanel(new GridBagLayout());
    582583
    583         String prefTimezone = Main.pref.get("geoimage.timezone", "0:00");
    584         if (prefTimezone == null) {
    585             prefTimezone = "0:00";
    586         }
    587584        try {
    588             timezone = Timezone.parseTimezone(prefTimezone);
     585            timezone = Timezone.parseTimezone(Optional.ofNullable(Main.pref.get("geoimage.timezone", "0:00")).orElse("0:00"));
    589586        } catch (ParseException e) {
    590587            timezone = Timezone.ZERO;
  • trunk/src/org/openstreetmap/josm/gui/layer/imagery/ColorfulImageProcessor.java

    r10965 r11553  
    1111import java.awt.image.DataBuffer;
    1212import java.awt.image.DataBufferByte;
     13import java.util.Optional;
    1314
    1415import org.openstreetmap.josm.Main;
     
    8283            }
    8384
    84             BufferedImage dest = dst;
    85             if (dest == null) {
    86                 dest = createCompatibleDestImage(src, null);
    87             }
     85            BufferedImage dest = Optional.ofNullable(dst).orElseGet(() -> createCompatibleDestImage(src, null));
    8886            DataBuffer srcBuffer = src.getRaster().getDataBuffer();
    8987            DataBuffer destBuffer = dest.getRaster().getDataBuffer();
  • trunk/src/org/openstreetmap/josm/gui/layer/markerlayer/Marker.java

    r10627 r11553  
    2323import java.util.List;
    2424import java.util.Map;
     25import java.util.Optional;
    2526import java.util.TimeZone;
    2627
     
    196197
    197198            URL url = uriToUrl(uri, relativePath);
    198 
    199199            String urlStr = url == null ? "" : url.toString();
    200             String symbolName = wpt.getString("symbol");
    201             if (symbolName == null) {
    202                 symbolName = wpt.getString(GpxConstants.PT_SYM);
    203             }
     200            String symbolName = Optional.ofNullable(wpt.getString("symbol")).orElseGet(() -> wpt.getString(GpxConstants.PT_SYM));
    204201            // text marker is returned in every case, see #10208
    205202            final Marker marker = new Marker(wpt.getCoor(), wpt, symbolName, parentLayer, time, offset);
  • trunk/src/org/openstreetmap/josm/gui/mappaint/StyleCache.java

    r11212 r11553  
    33
    44import java.util.Arrays;
     5import java.util.Optional;
    56
    67import org.openstreetmap.josm.data.osm.Storage;
     
    4445
    4546        int idx = getIndex(selected);
    46         DividedScale<StyleElementList> ds = s.states[idx];
    47         if (ds == null) {
    48             ds = new DividedScale<>();
    49         }
    50         s.states[idx] = ds.put(o, r);
     47        s.states[idx] = Optional.ofNullable(s.states[idx]).orElseGet(DividedScale::new).put(o, r);
    5148        return s.intern();
    5249    }
  • trunk/src/org/openstreetmap/josm/gui/mappaint/styleelement/LabelCompositionStrategy.java

    r10599 r11553  
    163163
    164164        private static List<String> buildNameTags(List<String> nameTags) {
    165             if (nameTags == null) {
    166                 nameTags = Collections.emptyList();
    167             }
    168165            List<String> result = new ArrayList<>();
    169             for (String tag: nameTags) {
    170                 if (tag == null) {
    171                     continue;
    172                 }
    173                 tag = tag.trim();
    174                 if (tag.isEmpty()) {
    175                     continue;
    176                 }
    177                 result.add(tag);
     166            if (nameTags != null) {
     167                for (String tag: nameTags) {
     168                    if (tag == null) {
     169                        continue;
     170                    }
     171                    tag = tag.trim();
     172                    if (tag.isEmpty()) {
     173                        continue;
     174                    }
     175                    result.add(tag);
     176                }
    178177            }
    179178            return result;
  • trunk/src/org/openstreetmap/josm/gui/mappaint/styleelement/LineElement.java

    r11452 r11553  
    66import java.util.Arrays;
    77import java.util.Objects;
     8import java.util.Optional;
    89
    910import org.openstreetmap.josm.Main;
     
    357358                if (casingWidth == null)
    358359                    return null;
    359                 width = getWidth(c, WIDTH, getWidth(cDef, WIDTH, null));
    360                 if (width == null) {
    361                     width = 0f;
    362                 }
    363                 width += 2 * casingWidth;
     360                width = Optional.ofNullable(getWidth(c, WIDTH, getWidth(cDef, WIDTH, null))).orElse(0f) + 2 * casingWidth;
    364361                break;
    365362            case LEFT_CASING:
     
    378375
    379376            /* if we have a "width" tag, try use it */
    380             String widthTag = env.osm.get("width");
    381             if (widthTag == null) {
    382                 widthTag = env.osm.get("est_width");
    383             }
     377            String widthTag = Optional.ofNullable(env.osm.get("width")).orElseGet(() -> env.osm.get("est_width"));
    384378            if (widthTag != null) {
    385379                try {
  • trunk/src/org/openstreetmap/josm/gui/mappaint/styleelement/NodeElement.java

    r10875 r11553  
    167167            sizeOnDefault = null;
    168168        }
    169         Float size = getWidth(c, "symbol-size", sizeOnDefault);
    170 
    171         if (size == null) {
    172             size = 10f;
    173         }
    174 
     169        Float size = Optional.ofNullable(getWidth(c, "symbol-size", sizeOnDefault)).orElse(10f);
    175170        if (size <= 0)
    176171            return null;
  • trunk/src/org/openstreetmap/josm/gui/preferences/ToolbarPreferences.java

    r11344 r11553  
    2727import java.util.List;
    2828import java.util.Map;
     29import java.util.Optional;
    2930import java.util.concurrent.ConcurrentHashMap;
    3031
     
    160161            if (ico != null)
    161162                return ico;
    162             Object o = action.getValue(Action.LARGE_ICON_KEY);
    163             if (o == null)
    164                 o = action.getValue(Action.SMALL_ICON);
    165             return (Icon) o;
     163            return (Icon) Optional.ofNullable(action.getValue(Action.LARGE_ICON_KEY)).orElseGet(() -> action.getValue(Action.SMALL_ICON));
    166164        }
    167165
     
    11931191        }
    11941192
    1195         String tt = action.getDisplayTooltip();
    1196         if (tt == null) {
    1197             tt = "";
    1198         }
     1193        String tt = Optional.ofNullable(action.getDisplayTooltip()).orElse("");
    11991194
    12001195        if (sc == null || paramCode != 0) {
    1201             String name = (String) action.getAction().getValue("toolbar");
    1202             if (name == null) {
    1203                 name = action.getDisplayName();
    1204             }
     1196            String name = Optional.ofNullable((String) action.getAction().getValue("toolbar")).orElseGet(action::getDisplayName);
    12051197            if (paramCode != 0) {
    12061198                name = name+paramCode;
  • trunk/src/org/openstreetmap/josm/gui/preferences/advanced/PrefEntry.java

    r9906 r11553  
    113113        if (this == obj)
    114114            return true;
    115         if (obj == null)
    116             return false;
    117         if (getClass() != obj.getClass())
     115        if (obj == null || getClass() != obj.getClass())
    118116            return false;
    119117        PrefEntry other = (PrefEntry) obj;
  • trunk/src/org/openstreetmap/josm/gui/preferences/plugin/PluginUpdatePolicyPanel.java

    r11489 r11553  
    1111import java.util.Locale;
    1212import java.util.Map;
     13import java.util.Optional;
    1314
    1415import javax.swing.ButtonGroup;
     
    173174     */
    174175    public final void initFromPreferences() {
    175         String pref = Main.pref.get("pluginmanager.version-based-update.policy", "ask");
    176         Policy p = Policy.fromPreferenceValue(pref);
    177         if (p == null) {
    178             p = Policy.ASK;
    179         }
    180         rbVersionBasedUpatePolicy.get(p).setSelected(true);
    181 
    182         pref = Main.pref.get("pluginmanager.time-based-update.policy", "ask");
    183         p = Policy.fromPreferenceValue(pref);
    184         if (p == null) {
    185             p = Policy.ASK;
    186         }
    187         rbTimeBasedUpatePolicy.get(p).setSelected(true);
    188 
    189         pref = Main.pref.get("pluginmanager.warntime", null);
     176        rbVersionBasedUpatePolicy.get(Optional.ofNullable(Policy.fromPreferenceValue(
     177                Main.pref.get("pluginmanager.version-based-update.policy", "ask"))).orElse(Policy.ASK)).setSelected(true);
     178        rbTimeBasedUpatePolicy.get(Optional.ofNullable(Policy.fromPreferenceValue(
     179                Main.pref.get("pluginmanager.time-based-update.policy", "ask"))).orElse(Policy.ASK)).setSelected(true);
     180
     181        String pref = Main.pref.get("pluginmanager.warntime", null);
    190182        int days = 0;
    191183        if (pref != null) {
    192184            // remove legacy preference
    193185            Main.pref.put("pluginmanager.warntime", null);
    194             pref = pref.trim();
    195186            try {
    196                 days = Integer.parseInt(pref);
     187                days = Integer.parseInt(pref.trim());
    197188            } catch (NumberFormatException e) {
    198189                // ignore - load from preference pluginmanager.time-based-update.interval
  • trunk/src/org/openstreetmap/josm/gui/preferences/projection/AbstractProjectionChoice.java

    r7937 r11553  
    11// License: GPL. For details, see LICENSE file.
    22package org.openstreetmap.josm.gui.preferences.projection;
     3
     4import java.util.Optional;
    35
    46import org.openstreetmap.josm.data.projection.CustomProjection;
     
    6062    public Projection getProjection() {
    6163        String code = getCurrentCode();
    62         String pref = Projections.getInit(code);
    63         if (pref == null)
    64             throw new AssertionError("Error: Unknown projection code");
    65         return new CustomProjection(getProjectionName(), code, pref, getCacheDir());
     64        return new CustomProjection(getProjectionName(), code, Optional.ofNullable(Projections.getInit(code))
     65                .orElseThrow(() -> new AssertionError("Error: Unknown projection code: " + code)), getCacheDir());
    6666    }
    6767}
  • trunk/src/org/openstreetmap/josm/gui/preferences/server/ProxyPreferencesPanel.java

    r11489 r11553  
    1818import java.util.Locale;
    1919import java.util.Map;
     20import java.util.Optional;
    2021
    2122import javax.swing.BorderFactory;
     
    322323     */
    323324    public final void initFromPreferences() {
    324         String policy = Main.pref.get(PROXY_POLICY, null);
    325         ProxyPolicy pp = ProxyPolicy.fromName(policy);
    326         if (pp == null) {
    327             pp = ProxyPolicy.NO_PROXY;
    328         }
     325        ProxyPolicy pp = Optional.ofNullable(ProxyPolicy.fromName(Main.pref.get(PROXY_POLICY, null))).orElse(ProxyPolicy.NO_PROXY);
    329326        rbProxyPolicy.get(pp).setSelected(true);
    330327        String value = Main.pref.get("proxy.host", null);
     
    419416            }
    420417        }
    421         if (policy == null) {
    422             policy = ProxyPolicy.NO_PROXY;
    423         }
    424         Main.pref.put(PROXY_POLICY, policy.getName());
     418        Main.pref.put(PROXY_POLICY, Optional.ofNullable(policy).orElse(ProxyPolicy.NO_PROXY).getName());
    425419        Main.pref.put(PROXY_HTTP_HOST, tfProxyHttpHost.getText());
    426420        Main.pref.put(PROXY_HTTP_PORT, tfProxyHttpPort.getText());
  • trunk/src/org/openstreetmap/josm/gui/tagging/presets/items/ComboMultiSelect.java

    r11452 r11553  
    508508    public void addCommands(List<Tag> changedTags) {
    509509        Object obj = getSelectedItem();
    510         String display = (obj == null) ? null : obj.toString();
     510        String display = obj == null ? getDisplayIfNull() : obj.toString();
    511511        String value = null;
    512         if (display == null) {
    513             display = getDisplayIfNull();
    514         }
    515512
    516513        if (display != null) {
  • trunk/src/org/openstreetmap/josm/gui/tagging/presets/items/Link.java

    r9665 r11553  
    2626    public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
    2727        initializeLocaleText(tr("More information about this feature"));
    28         String url = locale_href;
    29         if (url == null) {
    30             url = href;
    31         }
     28        String url = java.util.Optional.ofNullable(locale_href).orElse(href);
    3229        if (url != null) {
    3330            p.add(new UrlLabel(url, locale_text, 2), GBC.eol().insets(0, 10, 0, 0).fill(GBC.HORIZONTAL));
  • trunk/src/org/openstreetmap/josm/gui/util/CursorManager.java

    r9665 r11553  
    66import java.util.Iterator;
    77import java.util.LinkedHashMap;
     8import java.util.Objects;
    89import java.util.concurrent.CopyOnWriteArrayList;
    910
     
    5051     */
    5152    public synchronized void setNewCursor(Cursor cursor, Object reference) {
    52         if (reference == null) {
    53             throw new NullPointerException("Cannot register a cursor that can never be removed.");
    54         }
     53        Objects.requireNonNull(reference, "Cannot register a cursor that can never be removed.");
    5554        // re-insert to allow overriding.
    5655        cursors.remove(reference);
  • trunk/src/org/openstreetmap/josm/gui/widgets/HtmlPanel.java

    r11544 r11553  
    55import java.awt.Font;
    66import java.text.MessageFormat;
     7import java.util.Optional;
    78
    89import javax.swing.JEditorPane;
     
    8586     */
    8687    public final void setText(String text) {
    87         if (text == null) {
    88             text = "";
    89         }
    90         jepMessage.setText(text);
     88        jepMessage.setText(Optional.ofNullable(text).orElse(""));
    9189    }
    9290}
  • trunk/src/org/openstreetmap/josm/io/DiffResultProcessor.java

    r10818 r11553  
    1212import java.util.HashSet;
    1313import java.util.Map;
     14import java.util.Optional;
    1415import java.util.Set;
    1516
     
    6162     */
    6263    public DiffResultProcessor(Collection<? extends OsmPrimitive> primitives) {
    63         if (primitives == null) {
    64             primitives = Collections.emptyList();
    65         }
    66         this.primitives = primitives;
     64        this.primitives = Optional.ofNullable(primitives).orElseGet(Collections::emptyList);
    6765        this.processed = new HashSet<>();
    6866    }
  • trunk/src/org/openstreetmap/josm/io/GpxExporter.java

    r11035 r11553  
    1313import java.text.MessageFormat;
    1414import java.time.Year;
     15import java.util.Optional;
    1516
    1617import javax.swing.JButton;
     
    223224        if (enable) {
    224225            if (copyrightYear.getText().isEmpty()) {
    225                 String sCopyrightYear = data.getString(META_COPYRIGHT_YEAR);
    226                 if (sCopyrightYear == null) {
    227                     sCopyrightYear = Year.now().toString();
    228                 }
    229                 copyrightYear.setText(sCopyrightYear);
     226                copyrightYear.setText(Optional.ofNullable(data.getString(META_COPYRIGHT_YEAR)).orElseGet(
     227                        () -> Year.now().toString()));
    230228            }
    231229            if (copyright.getText().isEmpty()) {
    232                 String sCopyright = data.getString(META_COPYRIGHT_LICENSE);
    233                 if (sCopyright == null) {
    234                     sCopyright = Main.pref.get("lastCopyright", "https://creativecommons.org/licenses/by-sa/2.5");
    235                 }
    236                 copyright.setText(sCopyright);
     230                copyright.setText(Optional.ofNullable(data.getString(META_COPYRIGHT_LICENSE)).orElseGet(
     231                        () -> Main.pref.get("lastCopyright", "https://creativecommons.org/licenses/by-sa/2.5")));
    237232                copyright.setCaretPosition(0);
    238233            }
     
    282277            emailLabel.setEnabled(b);
    283278            if (b) {
    284                 String sAuthorName = data.getString(META_AUTHOR_NAME);
    285                 if (sAuthorName == null) {
    286                     sAuthorName = Main.pref.get("lastAuthorName");
    287                 }
    288                 authorName.setText(sAuthorName);
    289                 String sEmail = data.getString(META_AUTHOR_EMAIL);
    290                 if (sEmail == null) {
    291                     sEmail = Main.pref.get("lastAuthorEmail");
    292                 }
    293                 email.setText(sEmail);
     279                authorName.setText(Optional.ofNullable(data.getString(META_AUTHOR_NAME)).orElseGet(() -> Main.pref.get("lastAuthorName")));
     280                email.setText(Optional.ofNullable(data.getString(META_AUTHOR_EMAIL)).orElseGet(() -> Main.pref.get("lastAuthorEmail")));
    294281            } else {
    295282                authorName.setText("");
  • trunk/src/org/openstreetmap/josm/io/NmeaReader.java

    r11374 r11553  
    1313import java.util.Collections;
    1414import java.util.Date;
     15import java.util.Optional;
    1516
    1617import org.openstreetmap.josm.Main;
     
    112113
    113114    private Date readTime(String p) {
    114         Date d = rmcTimeFmt.parse(p, new ParsePosition(0));
    115         if (d == null) {
    116             d = rmcTimeFmtStd.parse(p, new ParsePosition(0));
    117         }
     115        Date d = Optional.ofNullable(rmcTimeFmt.parse(p, new ParsePosition(0)))
     116                .orElseGet(() -> rmcTimeFmtStd.parse(p, new ParsePosition(0)));
    118117        if (d == null)
    119118            throw new JosmRuntimeException("Date is malformed");
  • trunk/src/org/openstreetmap/josm/io/NoteReader.java

    r11453 r11553  
    1010import java.util.List;
    1111import java.util.Locale;
     12import java.util.Optional;
    1213
    1314import javax.xml.parsers.ParserConfigurationException;
     
    110111                break;
    111112            case "comment":
    112                 String uidStr = attrs.getValue("uid");
    113                 if (uidStr == null) {
    114                     commentUid = 0;
    115                 } else {
    116                     commentUid = Long.parseLong(uidStr);
    117                 }
     113                commentUid = Long.parseLong(Optional.ofNullable(attrs.getValue("uid")).orElse("0"));
    118114                commentUsername = attrs.getValue("user");
    119115                noteAction = Action.valueOf(attrs.getValue("action").toUpperCase(Locale.ENGLISH));
    120116                commentCreateDate = DateUtils.fromString(attrs.getValue("timestamp"));
    121                 String isNew = attrs.getValue("is_new");
    122                 if (isNew == null) {
    123                     commentIsNew = false;
    124                 } else {
    125                     commentIsNew = Boolean.parseBoolean(isNew);
    126                 }
     117                commentIsNew = Boolean.parseBoolean(Optional.ofNullable(attrs.getValue("is_new")).orElse("false"));
    127118                break;
    128119            default: // Do nothing
  • trunk/src/org/openstreetmap/josm/io/ProgressInputStream.java

    r9227 r11553  
    77import java.io.InputStream;
    88import java.net.URLConnection;
     9import java.util.Optional;
    910
    1011import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
     
    3132    public ProgressInputStream(InputStream in, long size, ProgressMonitor progressMonitor) {
    3233        CheckParameterUtil.ensureParameterNotNull(in, "in");
    33         if (progressMonitor == null) {
    34             progressMonitor = NullProgressMonitor.INSTANCE;
    35         }
    36         this.updater = new StreamProgressUpdater(size, progressMonitor, tr("Downloading data..."));
     34        this.updater = new StreamProgressUpdater(size,
     35                Optional.ofNullable(progressMonitor).orElse(NullProgressMonitor.INSTANCE), tr("Downloading data..."));
    3736        this.in = in;
    3837    }
  • trunk/src/org/openstreetmap/josm/io/StreamProgressUpdater.java

    r10161 r11553  
    33
    44import java.util.Locale;
     5import java.util.Optional;
    56
    67import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
     
    1718
    1819    StreamProgressUpdater(long size, ProgressMonitor progressMonitor, String taskTitle) {
    19         if (progressMonitor == null) {
    20             progressMonitor = NullProgressMonitor.INSTANCE;
    21         }
    2220        this.size = size;
    23         this.progressMonitor = progressMonitor;
     21        this.progressMonitor = Optional.ofNullable(progressMonitor).orElse(NullProgressMonitor.INSTANCE);
    2422        this.taskTitle = taskTitle;
    2523        initProgressMonitor();
  • trunk/src/org/openstreetmap/josm/io/UTFInputStreamReader.java

    r10182 r11553  
    77import java.io.PushbackInputStream;
    88import java.io.UnsupportedEncodingException;
     9import java.util.Optional;
    910
    1011/**
     
    6768            pushbackStream.unread(bom, 0, 0);
    6869        }
    69 
    70         if (encoding == null) {
    71             encoding = "UTF-8";
    72         }
    73         return new UTFInputStreamReader(pushbackStream, encoding);
     70        return new UTFInputStreamReader(pushbackStream, Optional.ofNullable(encoding).orElse("UTF-8"));
    7471    }
    7572}
  • trunk/src/org/openstreetmap/josm/io/XmlStreamParsingException.java

    r10235 r11553  
    33
    44import static org.openstreetmap.josm.tools.I18n.tr;
     5
     6import java.util.Optional;
    57
    68import javax.xml.stream.Location;
     
    3739    @Override
    3840    public String getMessage() {
    39         String msg = super.getMessage();
    40         if (msg == null) {
    41             msg = getClass().getName();
    42         }
     41        String msg = Optional.ofNullable(super.getMessage()).orElseGet(() -> getClass().getName());
    4342        if (getLocation() == null)
    4443            return msg;
  • trunk/src/org/openstreetmap/josm/plugins/PluginInformation.java

    r10627 r11553  
    1818import java.util.Locale;
    1919import java.util.Map;
     20import java.util.Optional;
    2021import java.util.TreeMap;
    2122import java.util.jar.Attributes;
     
    199200        Attributes attr = manifest.getMainAttributes();
    200201        className = attr.getValue("Plugin-Class");
    201         String s = attr.getValue(lang+"Plugin-Link");
    202         if (s == null) {
    203             s = attr.getValue("Plugin-Link");
    204         }
     202        String s = Optional.ofNullable(attr.getValue(lang+"Plugin-Link")).orElseGet(() -> attr.getValue("Plugin-Link"));
    205203        if (s != null && !Utils.isValidUrl(s)) {
    206204            Main.info(tr("Invalid URL ''{0}'' in plugin {1}", s, name));
  • trunk/src/org/openstreetmap/josm/plugins/ReadRemotePluginInformationTask.java

    r10952 r11553  
    2222import java.util.LinkedList;
    2323import java.util.List;
     24import java.util.Optional;
    2425import java.util.Set;
    2526
     
    5455
    5556    protected final void init(Collection<String> sites, boolean displayErrMsg) {
    56         this.sites = sites;
    57         if (sites == null) {
    58             this.sites = Collections.emptySet();
    59         }
     57        this.sites = Optional.ofNullable(sites).orElseGet(Collections::emptySet);
    6058        this.availablePlugins = new LinkedList<>();
    6159        this.displayErrMsg = displayErrMsg;
  • trunk/src/org/openstreetmap/josm/tools/ExceptionUtil.java

    r11397 r11553  
    1515import java.util.Collection;
    1616import java.util.Date;
     17import java.util.Optional;
    1718import java.util.TreeSet;
    1819import java.util.regex.Matcher;
     
    362363    public static String explainGenericOsmApiException(OsmApiException e) {
    363364        Main.error(e);
    364         String errMsg = e.getErrorHeader();
    365         if (errMsg == null) {
    366             errMsg = e.getErrorBody();
    367         }
    368         if (errMsg == null) {
    369             errMsg = tr("no error message available");
    370         }
    371365        return tr("<html>"
    372366                + "Communication with the OSM server ''{0}''failed. The server replied<br>"
     
    377371                getUrlFromException(e),
    378372                e.getResponseCode(),
    379                 errMsg
     373                Optional.ofNullable(Optional.ofNullable(e.getErrorHeader()).orElseGet(e::getErrorBody))
     374                    .orElse(tr("no error message available"))
    380375        );
    381376    }
  • trunk/src/org/openstreetmap/josm/tools/HttpClient.java

    r11535 r11553  
    1919import java.util.Map;
    2020import java.util.Map.Entry;
     21import java.util.Optional;
    2122import java.util.Scanner;
    2223import java.util.TreeMap;
     
    148149                if (redirectLocation == null) {
    149150                    /* I18n: argument is HTTP response code */
    150                     String msg = tr("Unexpected response from HTTP server. Got {0} response without ''Location'' header." +
    151                             " Can''t redirect. Aborting.", connection.getResponseCode());
    152                     throw new IOException(msg);
     151                    throw new IOException(tr("Unexpected response from HTTP server. Got {0} response without ''Location'' header." +
     152                            " Can''t redirect. Aborting.", connection.getResponseCode()));
    153153                } else if (maxRedirects > 0) {
    154154                    url = new URL(url, redirectLocation);
     
    284284            } catch (IOException ioe) {
    285285                Main.debug(ioe);
    286                 in = connection.getErrorStream();
    287                 if (in == null) {
    288                     in = new ByteArrayInputStream(new byte[]{});
    289                 }
     286                in = Optional.ofNullable(connection.getErrorStream()).orElseGet(() -> new ByteArrayInputStream(new byte[]{}));
    290287            }
    291288            in = new ProgressInputStream(in, getContentLength(), monitor);
  • trunk/src/org/openstreetmap/josm/tools/Shortcut.java

    r11454 r11553  
    384384
    385385    private static int getGroupModifier(int group) {
    386         Integer m = groups.get(group);
    387         if (m == null)
    388             m = -1;
    389         return m;
     386        return Optional.ofNullable(groups.get(group)).orElse(-1);
    390387    }
    391388
Note: See TracChangeset for help on using the changeset viewer.