Ignore:
Timestamp:
2015-06-20T14:36:00+02:00 (10 years ago)
Author:
Don-vip
Message:

fix many checkstyle violations

Location:
trunk/src/org/openstreetmap/josm/data
Files:
29 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/org/openstreetmap/josm/data/Bounds.java

    r8443 r8509  
    176176        String[] components = asString.split(separator);
    177177        if (components.length != 4)
    178             throw new IllegalArgumentException(MessageFormat.format("Exactly four doubles expected in string, got {0}: {1}", components.length, asString));
     178            throw new IllegalArgumentException(
     179                    MessageFormat.format("Exactly four doubles expected in string, got {0}: {1}", components.length, asString));
    179180        double[] values = new double[4];
    180181        for (int i=0; i<4; i++) {
  • trunk/src/org/openstreetmap/josm/data/CustomConfigurator.java

    r8470 r8509  
    180180        if (!opts.isEmpty()) {
    181181            String[] options = opts.split(";");
    182             answer = JOptionPane.showOptionDialog(Main.parent, text, "Question", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, 0);
     182            answer = JOptionPane.showOptionDialog(Main.parent, text, "Question",
     183                    JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, 0);
    183184        } else {
    184             answer = JOptionPane.showOptionDialog(Main.parent, text, "Question", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, 2);
     185            answer = JOptionPane.showOptionDialog(Main.parent, text, "Question",
     186                    JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, 2);
    185187        }
    186188        if (answer==null) return -1; else return answer;
     
    229231     * Export specified preferences keys to configuration file
    230232     * @param filename - name of file
    231      * @param append - will the preferences be appended to existing ones when file is imported later. Elsewhere preferences from file will replace existing keys.
     233     * @param append - will the preferences be appended to existing ones when file is imported later.
     234     * Elsewhere preferences from file will replace existing keys.
    232235     * @param keys - collection of preferences key names to save
    233236     */
     
    10421045     * @throws ScriptException if the evaluation fails
    10431046     */
    1044     public static void loadPrefsToJS(ScriptEngine engine, Preferences tmpPref, String whereToPutInJS, boolean includeDefaults) throws ScriptException {
     1047    public static void loadPrefsToJS(ScriptEngine engine, Preferences tmpPref, String whereToPutInJS, boolean includeDefaults)
     1048            throws ScriptException {
    10451049        Map<String, String> stringMap =  new TreeMap<>();
    10461050        Map<String, List<String>> listMap = new TreeMap<>();
  • trunk/src/org/openstreetmap/josm/data/Preferences.java

    r8471 r8509  
    871871        if (prefDir.exists()) {
    872872            if(!prefDir.isDirectory()) {
    873                 Main.warn(tr("Failed to initialize preferences. Preference directory ''{0}'' is not a directory.", prefDir.getAbsoluteFile()));
     873                Main.warn(tr("Failed to initialize preferences. Preference directory ''{0}'' is not a directory.",
     874                        prefDir.getAbsoluteFile()));
    874875                JOptionPane.showMessageDialog(
    875876                        Main.parent,
    876                         tr("<html>Failed to initialize preferences.<br>Preference directory ''{0}'' is not a directory.</html>", prefDir.getAbsoluteFile()),
     877                        tr("<html>Failed to initialize preferences.<br>Preference directory ''{0}'' is not a directory.</html>",
     878                                prefDir.getAbsoluteFile()),
    877879                        tr("Error"),
    878880                        JOptionPane.ERROR_MESSAGE
     
    882884        } else {
    883885            if (!prefDir.mkdirs()) {
    884                 Main.warn(tr("Failed to initialize preferences. Failed to create missing preference directory: {0}", prefDir.getAbsoluteFile()));
     886                Main.warn(tr("Failed to initialize preferences. Failed to create missing preference directory: {0}",
     887                        prefDir.getAbsoluteFile()));
    885888                JOptionPane.showMessageDialog(
    886889                        Main.parent,
    887                         tr("<html>Failed to initialize preferences.<br>Failed to create missing preference directory: {0}</html>",prefDir.getAbsoluteFile()),
     890                        tr("<html>Failed to initialize preferences.<br>Failed to create missing preference directory: {0}</html>",
     891                                prefDir.getAbsoluteFile()),
    888892                        tr("Error"),
    889893                        JOptionPane.ERROR_MESSAGE
     
    908912            JOptionPane.showMessageDialog(
    909913                    Main.parent,
    910                     tr("<html>Failed to initialize preferences.<br>Failed to reset preference file to default: {0}</html>",getPreferenceFile().getAbsoluteFile()),
     914                    tr("<html>Failed to initialize preferences.<br>Failed to reset preference file to default: {0}</html>",
     915                            getPreferenceFile().getAbsoluteFile()),
    911916                    tr("Error"),
    912917                    JOptionPane.ERROR_MESSAGE
     
    921926            JOptionPane.showMessageDialog(
    922927                    Main.parent,
    923                     tr("<html>Preferences file had errors.<br> Making backup of old one to <br>{0}<br> and creating a new default preference file.</html>", backupFile.getAbsoluteFile()),
     928                    tr("<html>Preferences file had errors.<br> Making backup of old one to <br>{0}<br> and creating a new default preference file.</html>",
     929                            backupFile.getAbsoluteFile()),
    924930                    tr("Error"),
    925931                    JOptionPane.ERROR_MESSAGE
     
    16461652
    16471653    protected void throwException(String msg) {
    1648         throw new RuntimeException(msg + tr(" (at line {0}, column {1})", parser.getLocation().getLineNumber(), parser.getLocation().getColumnNumber()));
     1654        throw new RuntimeException(msg + tr(" (at line {0}, column {1})",
     1655                parser.getLocation().getLineNumber(), parser.getLocation().getColumnNumber()));
    16491656    }
    16501657
     
    17111718                b.append("    <map>\n");
    17121719                for (Entry<String, String> e : struct.entrySet()) {
    1713                     b.append("      <tag key='").append(XmlWriter.encode(e.getKey())).append("' value='").append(XmlWriter.encode(e.getValue())).append("'/>\n");
     1720                    b.append("      <tag key='").append(XmlWriter.encode(e.getKey()))
     1721                     .append("' value='").append(XmlWriter.encode(e.getValue())).append("'/>\n");
    17141722                }
    17151723                b.append("    </map>\n");
  • trunk/src/org/openstreetmap/josm/data/cache/JCSCacheManager.java

    r8487 r8509  
    7373        jcsLog.setLevel(Level.INFO);
    7474        jcsLog.setUseParentHandlers(false);
    75         //Logger.getLogger("org.apache.common").setUseParentHandlers(false);
    76         // we need a separate handler from Main's, as we  downgrade LEVEL.INFO to DEBUG level
     75        // we need a separate handler from Main's, as we downgrade LEVEL.INFO to DEBUG level
    7776        jcsLog.addHandler(new Handler() {
    7877            @Override
     
    10099        });
    101100
    102 
    103         CompositeCacheManager cm  = CompositeCacheManager.getUnconfiguredInstance();
    104101        // this could be moved to external file
    105102        Properties props = new Properties();
    106103        // these are default common to all cache regions
    107104        // use of auxiliary cache and sizing of the caches is done with giving proper geCache(...) params
    108         props.setProperty("jcs.default.cacheattributes",                            org.apache.commons.jcs.engine.CompositeCacheAttributes.class.getCanonicalName());
    109         props.setProperty("jcs.default.cacheattributes.MaxObjects",                 DEFAULT_MAX_OBJECTS_IN_MEMORY.get().toString());
    110         props.setProperty("jcs.default.cacheattributes.UseMemoryShrinker",          "true");
    111         props.setProperty("jcs.default.cacheattributes.DiskUsagePatternName",       "UPDATE"); // store elements on disk on put
    112         props.setProperty("jcs.default.elementattributes",                          CacheEntryAttributes.class.getCanonicalName());
    113         props.setProperty("jcs.default.elementattributes.IsEternal",                "false");
    114         props.setProperty("jcs.default.elementattributes.MaxLife",                  Long.toString(maxObjectTTL));
    115         props.setProperty("jcs.default.elementattributes.IdleTime",                 Long.toString(maxObjectTTL));
    116         props.setProperty("jcs.default.elementattributes.IsSpool",                  "true");
     105        props.setProperty("jcs.default.cacheattributes",                      CompositeCacheAttributes.class.getCanonicalName());
     106        props.setProperty("jcs.default.cacheattributes.MaxObjects",           DEFAULT_MAX_OBJECTS_IN_MEMORY.get().toString());
     107        props.setProperty("jcs.default.cacheattributes.UseMemoryShrinker",    "true");
     108        props.setProperty("jcs.default.cacheattributes.DiskUsagePatternName", "UPDATE"); // store elements on disk on put
     109        props.setProperty("jcs.default.elementattributes",                    CacheEntryAttributes.class.getCanonicalName());
     110        props.setProperty("jcs.default.elementattributes.IsEternal",          "false");
     111        props.setProperty("jcs.default.elementattributes.MaxLife",            Long.toString(maxObjectTTL));
     112        props.setProperty("jcs.default.elementattributes.IdleTime",           Long.toString(maxObjectTTL));
     113        props.setProperty("jcs.default.elementattributes.IsSpool",            "true");
     114        CompositeCacheManager cm = CompositeCacheManager.getUnconfiguredInstance();
    117115        cm.configure(props);
    118116        cacheManager = cm;
    119 
    120117    }
    121118
  • trunk/src/org/openstreetmap/josm/data/cache/JCSCachedTileLoaderJob.java

    r8485 r8509  
    288288            expires = Math.min(expires, attributes.getCreateTime() + EXPIRE_TIME_SERVER_LIMIT);
    289289            if (now > expires) {
    290                 log.log(Level.FINE, "JCS - Object {0} has expired -> valid to {1}, now is: {2}", new Object[]{getUrl(), Long.toString(expires), Long.toString(now)});
     290                log.log(Level.FINE, "JCS - Object {0} has expired -> valid to {1}, now is: {2}",
     291                        new Object[]{getUrl(), Long.toString(expires), Long.toString(now)});
    291292                return false;
    292293            }
  • trunk/src/org/openstreetmap/josm/data/imagery/Shape.java

    r8415 r8509  
    2727        String[] components = asString.split(separator);
    2828        if (components.length % 2 != 0)
    29             throw new IllegalArgumentException(MessageFormat.format("Even number of doubles expected in string, got {0}: {1}", components.length, asString));
     29            throw new IllegalArgumentException(MessageFormat.format("Even number of doubles expected in string, got {0}: {1}",
     30                    components.length, asString));
    3031        for (int i=0; i<components.length; i+=2) {
    3132            addPoint(components[i], components[i+1]);
  • trunk/src/org/openstreetmap/josm/data/imagery/TMSCachedTileLoader.java

    r8459 r8509  
    8080     * @throws IOException      when cache initialization fails
    8181     */
    82     public TMSCachedTileLoader(TileLoaderListener listener, String name, int connectTimeout, int readTimeout, Map<String, String> headers, String cacheDir) throws IOException {
     82    public TMSCachedTileLoader(TileLoaderListener listener, String name, int connectTimeout, int readTimeout,
     83            Map<String, String> headers, String cacheDir) throws IOException {
    8384        this.cache = JCSCacheManager.getCache(name,
    8485                200, // use fairly small memory cache, as cached objects are quite big, as they contain BufferedImages
  • trunk/src/org/openstreetmap/josm/data/imagery/WmsCache.java

    r8470 r8509  
    9898    private int totalFileSize;
    9999    private boolean totalFileSizeDirty; // Some file was missing - size needs to be recalculated
    100     // No need for hashCode/equals on CacheEntry, object identity is enough. Comparing by values can lead to error - CacheEntry for wrong projection could be found
     100    // No need for hashCode/equals on CacheEntry, object identity is enough.
     101    // Comparing by values can lead to error - CacheEntry for wrong projection could be found
    101102    private Map<CacheEntry, SoftReference<BufferedImage>> memoryCache = new HashMap<>();
    102103    private Set<ProjectionBounds> areaToCache;
     
    458459    }
    459460
    460     private String generateFileName(ProjectionEntries projectionEntries, double pixelPerDegree, Projection projection, double east, double north, String mimeType) {
     461    private String generateFileName(ProjectionEntries projectionEntries, double pixelPerDegree, Projection projection,
     462            double east, double north, String mimeType) {
    461463        LatLon ll1 = projection.eastNorth2latlon(new EastNorth(east, north));
    462464        LatLon ll2 = projection.eastNorth2latlon(new EastNorth(east + 100 / pixelPerDegree, north));
     
    490492        FILENAME_LOOP:
    491493            while (true) {
    492                 String result = String.format("%s_%." + precisionLat + "f_%." + precisionLon +"f%s.%s", zoom, ll1.lat(), ll1.lon(), counter==0?"":"_" + counter, extension);
     494                String result = String.format("%s_%." + precisionLat + "f_%." + precisionLon +"f%s.%s",
     495                        zoom, ll1.lat(), ll1.lon(), counter==0?"":"_" + counter, extension);
    493496                for (CacheEntry entry: projectionEntries.entries) {
    494497                    if (entry.filename.equals(result)) {
     
    511514     * @throws IOException if any I/O error occurs
    512515     */
    513     public synchronized void saveToCache(BufferedImage img, InputStream imageData, Projection projection, double pixelPerDegree, double east, double north)
    514             throws IOException {
     516    public synchronized void saveToCache(BufferedImage img, InputStream imageData, Projection projection, double pixelPerDegree,
     517            double east, double north) throws IOException {
    515518        ProjectionEntries projectionEntries = getProjectionEntries(projection);
    516519        CacheEntry entry = findEntry(projectionEntries, pixelPerDegree, east, north);
  • trunk/src/org/openstreetmap/josm/data/osm/DataSetMerger.java

    r8444 r8509  
    268268            OsmPrimitive targetMember = getMergeTarget(sourceMember.getMember());
    269269            if (targetMember == null)
    270                 throw new IllegalStateException(tr("Missing merge target of type {0} with id {1}", sourceMember.getType(), sourceMember.getUniqueId()));
     270                throw new IllegalStateException(tr("Missing merge target of type {0} with id {1}",
     271                        sourceMember.getType(), sourceMember.getUniqueId()));
    271272            RelationMember newMember = new RelationMember(sourceMember.getRole(), targetMember);
    272273            newMembers.add(newMember);
     
    312313            // take. We take target.
    313314            //
    314         } else if (!target.isModified() && !source.isModified() && target.isVisible() != source.isVisible() && target.getVersion() == source.getVersion())
     315        } else if (!target.isModified() && !source.isModified() && target.isVisible() != source.isVisible()
     316                && target.getVersion() == source.getVersion())
    315317            // Same version, but different "visible" attribute and neither of them are modified.
    316318            // It indicates a serious problem in datasets.
  • trunk/src/org/openstreetmap/josm/data/osm/MultipolygonBuilder.java

    r8449 r8509  
    369369        }
    370370
    371         private static List<PolygonLevel> processOuterWay(int level, List<JoinedPolygon> boundaryWays, final List<PolygonLevel> result, JoinedPolygon outerWay) {
     371        private static List<PolygonLevel> processOuterWay(int level, List<JoinedPolygon> boundaryWays,
     372                final List<PolygonLevel> result, JoinedPolygon outerWay) {
    372373            Pair<Boolean, List<JoinedPolygon>> p = findInnerWaysCandidates(outerWay, boundaryWays);
    373374            if (p == null) {
  • trunk/src/org/openstreetmap/josm/data/osm/Node.java

    r8444 r8509  
    164164     * Constructs an identical clone of the argument.
    165165     * @param clone The node to clone
    166      * @param clearMetadata If {@code true}, clears the OSM id and other metadata as defined by {@link #clearOsmMetadata}. If {@code false}, does nothing
     166     * @param clearMetadata If {@code true}, clears the OSM id and other metadata as defined by {@link #clearOsmMetadata}.
     167     * If {@code false}, does nothing
    167168     */
    168169    public Node(Node clone, boolean clearMetadata) {
  • trunk/src/org/openstreetmap/josm/data/osm/OsmPrimitive.java

    r8470 r8509  
    345345    protected void writeUnlock(boolean locked) {
    346346        if (locked) {
    347             // It shouldn't be possible for dataset to become null because method calling setDataset would need write lock which is owned by this thread
     347            // It shouldn't be possible for dataset to become null because
     348            // method calling setDataset would need write lock which is owned by this thread
    348349            dataSet.endUpdate();
    349350        }
     
    11411142            CheckParameterUtil.ensureParameterNotNull(other, "other");
    11421143            if (other.isNew() ^ isNew())
    1143                 throw new DataIntegrityProblemException(tr("Cannot merge because either of the participating primitives is new and the other is not"));
     1144                throw new DataIntegrityProblemException(
     1145                        tr("Cannot merge because either of the participating primitives is new and the other is not"));
    11441146            if (!other.isNew() && other.getId() != id)
    1145                 throw new DataIntegrityProblemException(tr("Cannot merge primitives with different ids. This id is {0}, the other is {1}", id, other.getId()));
     1147                throw new DataIntegrityProblemException(
     1148                        tr("Cannot merge primitives with different ids. This id is {0}, the other is {1}", id, other.getId()));
    11461149
    11471150            setKeys(other.getKeys());
  • trunk/src/org/openstreetmap/josm/data/osm/Relation.java

    r8470 r8509  
    187187     * Constructs an identical clone of the argument.
    188188     * @param clone The relation to clone
    189      * @param clearMetadata If {@code true}, clears the OSM id and other metadata as defined by {@link #clearOsmMetadata}. If {@code false}, does nothing
     189     * @param clearMetadata If {@code true}, clears the OSM id and other metadata as defined by {@link #clearOsmMetadata}.
     190     * If {@code false}, does nothing
    190191     */
    191192    public Relation(Relation clone, boolean clearMetadata) {
     
    490491            for (RelationMember rm: members) {
    491492                if (rm.getMember().getDataSet() != dataSet)
    492                     throw new DataIntegrityProblemException(String.format("Relation member must be part of the same dataset as relation(%s, %s)", getPrimitiveId(), rm.getMember().getPrimitiveId()));
     493                    throw new DataIntegrityProblemException(
     494                            String.format("Relation member must be part of the same dataset as relation(%s, %s)",
     495                                    getPrimitiveId(), rm.getMember().getPrimitiveId()));
    493496            }
    494497            if (Main.pref.getBoolean("debug.checkDeleteReferenced", true)) {
  • trunk/src/org/openstreetmap/josm/data/osm/Way.java

    r8460 r8509  
    187187     * Replies the ordered {@link List} of chunks of this way. Each chunk is replied as a {@link Pair} of {@link Node nodes}.
    188188     * @param sort If true, the nodes of each pair are sorted as defined by {@link Pair#sort}.
    189      *             If false, Pair.a and Pair.b are in the way order (i.e for a given Pair(n), Pair(n-1).b == Pair(n).a, Pair(n).b == Pair(n+1).a, etc.)
     189     *             If false, Pair.a and Pair.b are in the way order
     190     *             (i.e for a given Pair(n), Pair(n-1).b == Pair(n).a, Pair(n).b == Pair(n+1).a, etc.)
    190191     * @return The ordered list of chunks of this way.
    191192     * @since 3348
     
    234235     * Contructs a new {@code Way} from an existing {@code Way}.
    235236     * @param original The original {@code Way} to be identically cloned. Must not be null
    236      * @param clearMetadata If {@code true}, clears the OSM id and other metadata as defined by {@link #clearOsmMetadata}. If {@code false}, does nothing
     237     * @param clearMetadata If {@code true}, clears the OSM id and other metadata as defined by {@link #clearOsmMetadata}.
     238     * If {@code false}, does nothing
    237239     * @since 2410
    238240     */
     
    597599                if (n.isDeleted())
    598600                    throw new DataIntegrityProblemException("Deleted node referenced: " + toString(),
    599                             "<html>" + tr("Deleted node referenced by {0}", DefaultNameFormatter.getInstance().formatAsHtmlUnorderedList(this)) + "</html>");
     601                            "<html>" + tr("Deleted node referenced by {0}",
     602                                    DefaultNameFormatter.getInstance().formatAsHtmlUnorderedList(this)) + "</html>");
    600603            }
    601604            if (Main.pref.getBoolean("debug.checkNullCoor", true)) {
  • trunk/src/org/openstreetmap/josm/data/osm/event/DatasetEventManager.java

    r8285 r8509  
    2929    private static final DatasetEventManager instance = new DatasetEventManager();
    3030
    31     public enum FireMode {
    32         /**
    33          * Fire in calling thread immediately.
    34          */
    35         IMMEDIATELY,
    36         /**
    37          * Fire in event dispatch thread.
    38          */
    39         IN_EDT,
    40         /**
    41          * Fire in event dispatch thread. If more than one event arrived when event queue is checked, merged them to
    42          * one event
    43          */
    44         IN_EDT_CONSOLIDATED}
    45 
    46     private static class ListenerInfo {
    47         private final DataSetListener listener;
    48         private final boolean consolidate;
    49 
    50         public ListenerInfo(DataSetListener listener, boolean consolidate) {
    51             this.listener = listener;
    52             this.consolidate = consolidate;
    53         }
    54 
    55         @Override
    56         public int hashCode() {
    57             return listener.hashCode();
    58         }
    59 
    60         @Override
    61         public boolean equals(Object o) {
    62             return o instanceof ListenerInfo && ((ListenerInfo)o).listener == listener;
    63         }
    64     }
    65 
    66     public static DatasetEventManager getInstance() {
    67         return instance;
    68     }
    69 
    70     private final Queue<AbstractDatasetChangedEvent> eventsInEDT = new LinkedBlockingQueue<>();
    71     private final CopyOnWriteArrayList<ListenerInfo> inEDTListeners = new CopyOnWriteArrayList<>();
    72     private final CopyOnWriteArrayList<ListenerInfo> normalListeners = new CopyOnWriteArrayList<>();
    73     private final DataSetListener myListener = new DataSetListenerAdapter(this);
    74 
    75     /**
    76      * Constructs a new {@code DatasetEventManager}.
    77      */
    78     public DatasetEventManager() {
    79         MapView.addEditLayerChangeListener(this);
    80     }
    81 
    82     /**
    83      * Register listener, that will receive events from currently active dataset
    84      * @param listener the listener to be registered
    85      * @param fireMode If {@link FireMode#IN_EDT} or {@link FireMode#IN_EDT_CONSOLIDATED},
    86      * listener will be notified in event dispatch thread instead of thread that caused
    87      * the dataset change
    88      */
    89     public void addDatasetListener(DataSetListener listener, FireMode fireMode) {
    90         if (fireMode == FireMode.IN_EDT || fireMode == FireMode.IN_EDT_CONSOLIDATED) {
    91             inEDTListeners.addIfAbsent(new ListenerInfo(listener, fireMode == FireMode.IN_EDT_CONSOLIDATED));
    92         } else {
    93             normalListeners.addIfAbsent(new ListenerInfo(listener, false));
    94         }
    95     }
    96 
    97     public void removeDatasetListener(DataSetListener listener) {
    98         ListenerInfo searchListener = new ListenerInfo(listener, false);
    99         inEDTListeners.remove(searchListener);
    100         normalListeners.remove(searchListener);
    101     }
    102 
    103     @Override
    104     public void editLayerChanged(OsmDataLayer oldLayer, OsmDataLayer newLayer) {
    105         if (oldLayer != null) {
    106             oldLayer.data.removeDataSetListener(myListener);
    107         }
    108 
    109         if (newLayer != null) {
    110             newLayer.data.addDataSetListener(myListener);
    111             processDatasetEvent(new DataChangedEvent(newLayer.data));
    112         } else {
    113             processDatasetEvent(new DataChangedEvent(null));
    114         }
    115     }
    116 
    117     private void fireEvents(List<ListenerInfo> listeners, AbstractDatasetChangedEvent event) {
    118         for (ListenerInfo listener: listeners) {
    119             if (!listener.consolidate) {
    120                 event.fire(listener.listener);
    121             }
    122         }
    123     }
    124 
    125     private void fireConsolidatedEvents(List<ListenerInfo> listeners, AbstractDatasetChangedEvent event) {
    126         for (ListenerInfo listener: listeners) {
    127             if (listener.consolidate) {
    128                 event.fire(listener.listener);
    129             }
    130         }
    131     }
    132 
    133     @Override
    134     public void processDatasetEvent(AbstractDatasetChangedEvent event) {
    135         fireEvents(normalListeners, event);
    136         eventsInEDT.add(event);
    137         SwingUtilities.invokeLater(edtRunnable);
    138     }
    139 
    140     private final Runnable edtRunnable = new Runnable() {
     31    private final class EdtRunnable implements Runnable {
    14132        @Override
    14233        public void run() {
    14334            while (!eventsInEDT.isEmpty()) {
    144                 List<AbstractDatasetChangedEvent> events = new ArrayList<>();
    145                 events.addAll(eventsInEDT);
     35                List<AbstractDatasetChangedEvent> events = new ArrayList<>(eventsInEDT);
    14636
    14737                DataSet dataSet = null;
     
    19282                            consolidatedEvent = new DataChangedEvent(dataSet, new ArrayList<>(Arrays.asList(consolidatedEvent)));
    19383                        }
    194 
    19584                    }
    19685                }
     
    20089            }
    20190        }
    202     };
     91    }
     92
     93    public enum FireMode {
     94        /**
     95         * Fire in calling thread immediately.
     96         */
     97        IMMEDIATELY,
     98        /**
     99         * Fire in event dispatch thread.
     100         */
     101        IN_EDT,
     102        /**
     103         * Fire in event dispatch thread. If more than one event arrived when event queue is checked, merged them to
     104         * one event
     105         */
     106        IN_EDT_CONSOLIDATED}
     107
     108    private static class ListenerInfo {
     109        private final DataSetListener listener;
     110        private final boolean consolidate;
     111
     112        public ListenerInfo(DataSetListener listener, boolean consolidate) {
     113            this.listener = listener;
     114            this.consolidate = consolidate;
     115        }
     116
     117        @Override
     118        public int hashCode() {
     119            return listener.hashCode();
     120        }
     121
     122        @Override
     123        public boolean equals(Object o) {
     124            return o instanceof ListenerInfo && ((ListenerInfo)o).listener == listener;
     125        }
     126    }
     127
     128    public static DatasetEventManager getInstance() {
     129        return instance;
     130    }
     131
     132    private final Queue<AbstractDatasetChangedEvent> eventsInEDT = new LinkedBlockingQueue<>();
     133    private final CopyOnWriteArrayList<ListenerInfo> inEDTListeners = new CopyOnWriteArrayList<>();
     134    private final CopyOnWriteArrayList<ListenerInfo> normalListeners = new CopyOnWriteArrayList<>();
     135    private final DataSetListener myListener = new DataSetListenerAdapter(this);
     136    private final Runnable edtRunnable = new EdtRunnable();
     137
     138    /**
     139     * Constructs a new {@code DatasetEventManager}.
     140     */
     141    public DatasetEventManager() {
     142        MapView.addEditLayerChangeListener(this);
     143    }
     144
     145    /**
     146     * Register listener, that will receive events from currently active dataset
     147     * @param listener the listener to be registered
     148     * @param fireMode If {@link FireMode#IN_EDT} or {@link FireMode#IN_EDT_CONSOLIDATED},
     149     * listener will be notified in event dispatch thread instead of thread that caused
     150     * the dataset change
     151     */
     152    public void addDatasetListener(DataSetListener listener, FireMode fireMode) {
     153        if (fireMode == FireMode.IN_EDT || fireMode == FireMode.IN_EDT_CONSOLIDATED) {
     154            inEDTListeners.addIfAbsent(new ListenerInfo(listener, fireMode == FireMode.IN_EDT_CONSOLIDATED));
     155        } else {
     156            normalListeners.addIfAbsent(new ListenerInfo(listener, false));
     157        }
     158    }
     159
     160    public void removeDatasetListener(DataSetListener listener) {
     161        ListenerInfo searchListener = new ListenerInfo(listener, false);
     162        inEDTListeners.remove(searchListener);
     163        normalListeners.remove(searchListener);
     164    }
     165
     166    @Override
     167    public void editLayerChanged(OsmDataLayer oldLayer, OsmDataLayer newLayer) {
     168        if (oldLayer != null) {
     169            oldLayer.data.removeDataSetListener(myListener);
     170        }
     171
     172        if (newLayer != null) {
     173            newLayer.data.addDataSetListener(myListener);
     174            processDatasetEvent(new DataChangedEvent(newLayer.data));
     175        } else {
     176            processDatasetEvent(new DataChangedEvent(null));
     177        }
     178    }
     179
     180    private void fireEvents(List<ListenerInfo> listeners, AbstractDatasetChangedEvent event) {
     181        for (ListenerInfo listener: listeners) {
     182            if (!listener.consolidate) {
     183                event.fire(listener.listener);
     184            }
     185        }
     186    }
     187
     188    private void fireConsolidatedEvents(List<ListenerInfo> listeners, AbstractDatasetChangedEvent event) {
     189        for (ListenerInfo listener: listeners) {
     190            if (listener.consolidate) {
     191                event.fire(listener.listener);
     192            }
     193        }
     194    }
     195
     196    @Override
     197    public void processDatasetEvent(AbstractDatasetChangedEvent event) {
     198        fireEvents(normalListeners, event);
     199        eventsInEDT.add(event);
     200        SwingUtilities.invokeLater(edtRunnable);
     201    }
    203202}
  • trunk/src/org/openstreetmap/josm/data/osm/history/HistoryNode.java

    r8291 r8509  
    5050     * @since 5440
    5151     */
    52     public HistoryNode(long id, long version, boolean visible, User user, long changesetId, Date timestamp, LatLon coords, boolean checkHistoricParams) {
     52    public HistoryNode(long id, long version, boolean visible, User user, long changesetId, Date timestamp, LatLon coords,
     53            boolean checkHistoricParams) {
    5354        super(id, version, visible, user, changesetId, timestamp, checkHistoricParams);
    5455        setCoords(coords);
  • trunk/src/org/openstreetmap/josm/data/osm/visitor/paint/LineClip.java

    r8444 r8509  
    3838            return false;
    3939        }
    40         return cohenSutherland(p1.x, p1.y, p2.x, p2.y, clipBounds.x , clipBounds.y, clipBounds.x + clipBounds.width, clipBounds.y + clipBounds.height);
     40        return cohenSutherland(p1.x, p1.y, p2.x, p2.y, clipBounds.x , clipBounds.y,
     41                clipBounds.x + clipBounds.width, clipBounds.y + clipBounds.height);
    4142    }
    4243
  • trunk/src/org/openstreetmap/josm/data/osm/visitor/paint/MapRendererFactory.java

    r8444 r8509  
    128128            activateDefault();
    129129        } else if (!AbstractMapRenderer.class.isAssignableFrom(c)) {
    130             Main.error(tr("Can''t activate map renderer class ''{0}'', because it isn''t a subclass of ''{1}''.", rendererClassName, AbstractMapRenderer.class.getName()));
     130            Main.error(tr("Can''t activate map renderer class ''{0}'', because it isn''t a subclass of ''{1}''.",
     131                    rendererClassName, AbstractMapRenderer.class.getName()));
    131132            Main.error(tr("Activating the standard map renderer instead."));
    132133            activateDefault();
     
    260261     * @see AbstractMapRenderer#AbstractMapRenderer(Graphics2D, NavigatableComponent, boolean)
    261262     */
    262     public AbstractMapRenderer createActiveRenderer(Graphics2D g, NavigatableComponent viewport, boolean isInactiveMode) throws MapRendererFactoryException{
     263    public AbstractMapRenderer createActiveRenderer(Graphics2D g, NavigatableComponent viewport, boolean isInactiveMode)
     264            throws MapRendererFactoryException{
    263265        try {
    264266            Constructor<?> c = activeRenderer.getConstructor(new Class<?>[]{Graphics2D.class, NavigatableComponent.class, boolean.class});
  • trunk/src/org/openstreetmap/josm/data/osm/visitor/paint/StyledMapRenderer.java

    r8470 r8509  
    10861086        long dx, dy;
    10871087
    1088         // find half segments that are long enough to draw text on
    1089         // (don't draw text over the cross hair in the center of each segment)
     1088        // find half segments that are long enough to draw text on (don't draw text over the cross hair in the center of each segment)
    10901089        List<Double> longHalfSegmentStart = new ArrayList<>(); // start point of half segment (as length along the way)
    10911090        List<Double> longHalfSegmentEnd = new ArrayList<>(); // end point of half segment (as length along the way)
     
    11391138        if (!longHalfSegmentStart.isEmpty()) {
    11401139            if (way.getNodesCount() == 2) {
    1141                 // For 2 node ways, the two half segments are exactly
    1142                 // the same size and distance from the center.
     1140                // For 2 node ways, the two half segments are exactly the same size and distance from the center.
    11431141                // Prefer the first one for consistency.
    11441142                longHalfsegmentQuality.set(0, longHalfsegmentQuality.get(0) + 0.5);
     
    12141212            }
    12151213        }
    1216         // only works for text that is completely left-to-right or completely
    1217         // right-to-left, not bi-directional text
     1214        // only works for text that is completely left-to-right or completely right-to-left, not bi-directional text
    12181215        GlyphVector gv = text.font.layoutGlyphVector(frc, chars, 0, chars.length, dirFlag);
    12191216
  • trunk/src/org/openstreetmap/josm/data/projection/CustomProjection.java

    r8415 r8509  
    125125    /**
    126126     * Constructs a new {@code CustomProjection} with given parameters.
    127      * @param pref String containing projection parameters (ex: "+proj=tmerc +lon_0=-3 +k_0=0.9996 +x_0=500000 +ellps=WGS84 +datum=WGS84 +bounds=-8,-5,2,85")
     127     * @param pref String containing projection parameters
     128     * (ex: "+proj=tmerc +lon_0=-3 +k_0=0.9996 +x_0=500000 +ellps=WGS84 +datum=WGS84 +bounds=-8,-5,2,85")
    128129     */
    129130    public CustomProjection(String pref) {
  • trunk/src/org/openstreetmap/josm/data/projection/datum/SevenParameterDatum.java

    r8444 r8509  
    3333     * @param s scale change in parts per million
    3434     */
    35     public SevenParameterDatum(String name, String proj4Id, Ellipsoid ellps, double dx, double dy, double dz, double rx, double ry, double rz, double s) {
     35    public SevenParameterDatum(String name, String proj4Id, Ellipsoid ellps, double dx, double dy, double dz,
     36            double rx, double ry, double rz, double s) {
    3637        super(name, proj4Id, ellps);
    3738        this.dx = dx;
  • trunk/src/org/openstreetmap/josm/data/projection/proj/SwissObliqueMercator.java

    r8444 r8509  
    2323 * Projection for the SwissGrid CH1903 / L03, see <a href="https://en.wikipedia.org/wiki/Swiss_coordinate_system">Wikipedia article</a>.<br>
    2424 *
    25  * Calculations were originally based on <a href="http://www.swisstopo.admin.ch/internet/swisstopo/en/home/topics/survey/sys/refsys/switzerland.parsysrelated1.37696.downloadList.12749.DownloadFile.tmp/ch1903wgs84en.pdf">
     25 * Calculations were originally based on
     26 * <a href="http://www.swisstopo.admin.ch/internet/swisstopo/en/home/topics/survey/sys/refsys/switzerland.parsysrelated1.37696.downloadList.12749.DownloadFile.tmp/ch1903wgs84en.pdf">
    2627 * simple formula</a>.<br>
    2728 *
    28  * August 2010 update to <a href="http://www.swisstopo.admin.ch/internet/swisstopo/en/home/topics/survey/sys/refsys/switzerland.parsysrelated1.37696.downloadList.97912.DownloadFile.tmp/swissprojectionen.pdf">
     29 * August 2010 update to
     30 * <a href="http://www.swisstopo.admin.ch/internet/swisstopo/en/home/topics/survey/sys/refsys/switzerland.parsysrelated1.37696.downloadList.97912.DownloadFile.tmp/swissprojectionen.pdf">
    2931 * this formula (rigorous formulas)</a>.
    3032 */
  • trunk/src/org/openstreetmap/josm/data/validation/routines/UrlValidator.java

    r8461 r8509  
    6464 *  </pre>
    6565 *
     66 * @version $Revision: 1640269 $ $Date: 2014-11-18 02:28:56 UTC (Tue, 18 Nov 2014) $
    6667 * @see
    6768 * <a href="http://www.ietf.org/rfc/rfc2396.txt">
     
    6970 * </a>
    7071 *
    71  * @version $Revision: 1640269 $ $Date: 2014-11-18 02:28:56 UTC (Tue, 18 Nov 2014) $
    7272 * @since Validator 1.4
    7373 */
  • trunk/src/org/openstreetmap/josm/data/validation/tests/ConditionalKeys.java

    r8285 r8509  
    102102            // <restriction-value> @ <condition>[;<restriction-value> @ <condition>]
    103103            final List<ConditionalValue> r = new ArrayList<>();
    104             final Pattern part = Pattern.compile("([^@\\p{Space}][^@]*?)" + "\\s*@\\s*" + "(\\([^)\\p{Space}][^)]+?\\)|[^();\\p{Space}][^();]*?)\\s*");
     104            final Pattern part = Pattern.compile("([^@\\p{Space}][^@]*?)"
     105                    + "\\s*@\\s*" + "(\\([^)\\p{Space}][^)]+?\\)|[^();\\p{Space}][^();]*?)\\s*");
    105106            final Matcher m = Pattern.compile("(" + part + ")(;\\s*" + part + ")*").matcher(value);
    106107            if (!m.matches()) {
  • trunk/src/org/openstreetmap/josm/data/validation/tests/Highways.java

    r8454 r8509  
    102102    public void visit(Way w) {
    103103        if (w.isUsable()) {
    104             if (w.hasKey("highway") && CLASSIFIED_HIGHWAYS.contains(w.get("highway")) && w.hasKey("junction") && "roundabout".equals(w.get("junction"))) {
     104            if (w.hasKey("highway") && CLASSIFIED_HIGHWAYS.contains(w.get("highway"))
     105                    && w.hasKey("junction") && "roundabout".equals(w.get("junction"))) {
    105106                testWrongRoundabout(w);
    106107            }
     
    248249            String context = value.substring(index+1);
    249250            if (!KNOWN_SOURCE_MAXSPEED_CONTEXTS.contains(context)) {
    250                 errors.add(new TestError(this, Severity.WARNING, tr("Unknown source:maxspeed context: {0}", context), SOURCE_MAXSPEED_UNKNOWN_CONTEXT, p));
     251                errors.add(new TestError(this, Severity.WARNING,
     252                        tr("Unknown source:maxspeed context: {0}", context), SOURCE_MAXSPEED_UNKNOWN_CONTEXT, p));
    251253            }
    252254            // TODO: Check coherence of context against maxspeed
  • trunk/src/org/openstreetmap/josm/data/validation/tests/MapCSSTagChecker.java

    r8465 r8509  
    148148    abstract static class FixCommand {
    149149        /**
    150          * Creates the fixing {@link Command} for the given primitive. The {@code matchingSelector} is used to
    151          * evaluate placeholders (cf. {@link org.openstreetmap.josm.data.validation.tests.MapCSSTagChecker.TagCheck#insertArguments(Selector, String, OsmPrimitive)}).
     150         * Creates the fixing {@link Command} for the given primitive. The {@code matchingSelector} is used to evaluate placeholders
     151         * (cf. {@link org.openstreetmap.josm.data.validation.tests.MapCSSTagChecker.TagCheck#insertArguments(Selector, String, OsmPrimitive)}).
    152152         */
    153153        abstract Command createCommand(final OsmPrimitive p, final Selector matchingSelector);
    154154
    155155        private static void checkObject(final Object obj) {
    156             CheckParameterUtil.ensureThat(obj instanceof Expression || obj instanceof String, "instance of Exception or String expected, but got " + obj);
     156            CheckParameterUtil.ensureThat(obj instanceof Expression || obj instanceof String,
     157                    "instance of Exception or String expected, but got " + obj);
    157158        }
    158159
  • trunk/src/org/openstreetmap/josm/data/validation/tests/MultipolygonTest.java

    r8382 r8509  
    198198                        addError(r, new TestError(this, Severity.WARNING,
    199199                                trn("Multipolygon relation should be tagged with area tags and not the outer way",
    200                                         "Multipolygon relation should be tagged with area tags and not the outer ways", polygon.getOuterWays().size()),
     200                                        "Multipolygon relation should be tagged with area tags and not the outer ways",
     201                                        polygon.getOuterWays().size()),
    201202                           NO_STYLE_POLYGON, r));
    202203                    }
     
    211212                            l.add(r);
    212213                            l.add(wInner);
    213                             addError(r, new TestError(this, Severity.OTHER, tr("With the currently used mappaint style the style for inner way equals the multipolygon style"),
     214                            addError(r, new TestError(this, Severity.OTHER,
     215                                    tr("With the currently used mappaint style the style for inner way equals the multipolygon style"),
    214216                                    INNER_STYLE_MISMATCH, l, Collections.singletonList(wInner)));
    215217                        }
     
    263265                    highlights.add(pdInner.getNodes());
    264266                    if (outside) {
    265                         addError(r, new TestError(this, Severity.WARNING, tr("Multipolygon inner way is outside"), INNER_WAY_OUTSIDE, Collections.singletonList(r), highlights));
     267                        addError(r, new TestError(this, Severity.WARNING, tr("Multipolygon inner way is outside"),
     268                                INNER_WAY_OUTSIDE, Collections.singletonList(r), highlights));
    266269                    } else {
    267270                        highlights.add(outerWay.getNodes());
    268                         addError(r, new TestError(this, Severity.WARNING, tr("Intersection between multipolygon ways"), CROSSING_WAYS, Collections.singletonList(r), highlights));
     271                        addError(r, new TestError(this, Severity.WARNING, tr("Intersection between multipolygon ways"),
     272                                CROSSING_WAYS, Collections.singletonList(r), highlights));
    269273                    }
    270274                }
     
    277281            if (rm.isWay()) {
    278282                if (!(rm.hasRole("inner", "outer") || !rm.hasRole())) {
    279                     addError(r, new TestError(this, Severity.WARNING, tr("No useful role for multipolygon member"), WRONG_MEMBER_ROLE, rm.getMember()));
     283                    addError(r, new TestError(this, Severity.WARNING, tr("No useful role for multipolygon member"),
     284                            WRONG_MEMBER_ROLE, rm.getMember()));
    280285                }
    281286            } else {
  • trunk/src/org/openstreetmap/josm/data/validation/tests/UnconnectedWays.java

    r8378 r8509  
    442442    public void visit(Way w) {
    443443        if (w.getNodesCount() > 0 // do not consider empty ways
    444                 && !w.hasKey("addr:interpolation") // ignore addr:interpolation ways as they are not physical features and most of the time very near the associated highway, which is perfectly normal, see #9332
     444                && !w.hasKey("addr:interpolation") // ignore addr:interpolation ways as they are not physical features and most of
     445                                                   // the time very near the associated highway, which is perfectly normal, see #9332
    445446                && !w.hasTag("highway", "platform") && !w.hasTag("railway", "platform") // similarly for public transport platforms
    446447                ) {
  • trunk/src/org/openstreetmap/josm/data/validation/util/NameVisitor.java

    r8378 r8509  
    1919 * @author imi
    2020 */
    21 //TODO This class used to be in JOSM but it was removed. MultipleNameVisitor depends on it so I copied it here, but MultipleNameVisitor should be refactored instead of using this class
     21//TODO This class used to be in JOSM but it was removed. MultipleNameVisitor depends on it so I copied it here,
     22// but MultipleNameVisitor should be refactored instead of using this class
    2223public class NameVisitor extends AbstractVisitor {
    2324
Note: See TracChangeset for help on using the changeset viewer.