summaryrefslogtreecommitdiff
path: root/src/javax/jmdns/impl/DNSCache.java
blob: ed26f0d5f691083ae71941bc64500940977fb4a0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
// Copyright 2003-2005 Arthur van Hoff Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL

package javax.jmdns.impl;

import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.jmdns.impl.constants.DNSRecordClass;
import javax.jmdns.impl.constants.DNSRecordType;

/**
 * A table of DNS entries. This is a map table which can handle multiple entries with the same name.
 * <p/>
 * Storing multiple entries with the same name is implemented using a linked list. This is hidden from the user and can change in later implementation.
 * <p/>
 * Here's how to iterate over all entries:
 *
 * <pre>
 *       for (Iterator i=dnscache.allValues().iterator(); i.hasNext(); ) {
 *             DNSEntry entry = i.next();
 *             ...do something with entry...
 *       }
 * </pre>
 * <p/>
 * And here's how to iterate over all entries having a given name:
 *
 * <pre>
 *       for (Iterator i=dnscache.getDNSEntryList(name).iterator(); i.hasNext(); ) {
 *             DNSEntry entry = i.next();
 *           ...do something with entry...
 *       }
 * </pre>
 *
 * @author Arthur van Hoff, Werner Randelshofer, Rick Blair, Pierre Frisch
 */
public class DNSCache extends AbstractMap<String, List<? extends DNSEntry>> {

    // private static Logger logger = Logger.getLogger(DNSCache.class.getName());

    private transient Set<Map.Entry<String, List<? extends DNSEntry>>> _entrySet  = null;

    /**
     *
     */
    public static final DNSCache                                       EmptyCache = new _EmptyCache();

    static final class _EmptyCache extends DNSCache {

        /**
         * {@inheritDoc}
         */
        @Override
        public int size() {
            return 0;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean isEmpty() {
            return true;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean containsKey(Object key) {
            return false;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean containsValue(Object value) {
            return false;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public List<DNSEntry> get(Object key) {
            return null;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public Set<String> keySet() {
            return Collections.emptySet();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public Collection<List<? extends DNSEntry>> values() {
            return Collections.emptySet();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public Set<Map.Entry<String, List<? extends DNSEntry>>> entrySet() {
            return Collections.emptySet();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean equals(Object o) {
            return (o instanceof Map) && ((Map<?, ?>) o).size() == 0;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public List<? extends DNSEntry> put(String key, List<? extends DNSEntry> value) {
            return null;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public int hashCode() {
            return 0;
        }

    }

    /**
     *
     */
    protected static class _CacheEntry extends Object implements Map.Entry<String, List<? extends DNSEntry>> {

        private List<? extends DNSEntry> _value;

        private String                   _key;

        /**
         * @param key
         * @param value
         */
        protected _CacheEntry(String key, List<? extends DNSEntry> value) {
            super();
            _key = (key != null ? key.trim().toLowerCase() : null);
            _value = value;
        }

        /**
         * @param entry
         */
        protected _CacheEntry(Map.Entry<String, List<? extends DNSEntry>> entry) {
            super();
            if (entry instanceof _CacheEntry) {
                _key = ((_CacheEntry) entry).getKey();
                _value = ((_CacheEntry) entry).getValue();
            }
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public String getKey() {
            return (_key != null ? _key : "");
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public List<? extends DNSEntry> getValue() {
            return _value;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public List<? extends DNSEntry> setValue(List<? extends DNSEntry> value) {
            List<? extends DNSEntry> oldValue = _value;
            _value = value;
            return oldValue;
        }

        /**
         * Returns <tt>true</tt> if this list contains no elements.
         *
         * @return <tt>true</tt> if this list contains no elements
         */
        public boolean isEmpty() {
            return this.getValue().isEmpty();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean equals(Object entry) {
            if (!(entry instanceof Map.Entry)) {
                return false;
            }
            return this.getKey().equals(((Map.Entry<?, ?>) entry).getKey()) && this.getValue().equals(((Map.Entry<?, ?>) entry).getValue());
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public int hashCode() {
            return (_key == null ? 0 : _key.hashCode());
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public synchronized String toString() {
            StringBuffer aLog = new StringBuffer(200);
            aLog.append("\n\t\tname '");
            aLog.append(_key);
            aLog.append("' ");
            if ((_value != null) && (!_value.isEmpty())) {
                for (DNSEntry entry : _value) {
                    aLog.append("\n\t\t\t");
                    aLog.append(entry.toString());
                }
            } else {
                aLog.append(" no entries");
            }
            return aLog.toString();
        }
    }

    /**
     *
     */
    public DNSCache() {
        this(1024);
    }

    /**
     * @param map
     */
    public DNSCache(DNSCache map) {
        this(map != null ? map.size() : 1024);
        if (map != null) {
            this.putAll(map);
        }
    }

    /**
     * Create a table with a given initial size.
     *
     * @param initialCapacity
     */
    public DNSCache(int initialCapacity) {
        super();
        _entrySet = new HashSet<Map.Entry<String, List<? extends DNSEntry>>>(initialCapacity);
    }

    // ====================================================================
    // Map

    /*
     * (non-Javadoc)
     * @see java.util.AbstractMap#entrySet()
     */
    @Override
    public Set<Map.Entry<String, List<? extends DNSEntry>>> entrySet() {
        if (_entrySet == null) {
            _entrySet = new HashSet<Map.Entry<String, List<? extends DNSEntry>>>();
        }
        return _entrySet;
    }

    /**
     * @param key
     * @return map entry for the key
     */
    protected Map.Entry<String, List<? extends DNSEntry>> getEntry(String key) {
        String stringKey = (key != null ? key.trim().toLowerCase() : null);
        for (Map.Entry<String, List<? extends DNSEntry>> entry : this.entrySet()) {
            if (stringKey != null) {
                if (stringKey.equals(entry.getKey())) {
                    return entry;
                }
            } else {
                if (entry.getKey() == null) {
                    return entry;
                }
            }
        }
        return null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<? extends DNSEntry> put(String key, List<? extends DNSEntry> value) {
        synchronized (this) {
            List<? extends DNSEntry> oldValue = null;
            Map.Entry<String, List<? extends DNSEntry>> oldEntry = this.getEntry(key);
            if (oldEntry != null) {
                oldValue = oldEntry.setValue(value);
            } else {
                this.entrySet().add(new _CacheEntry(key, value));
            }
            return oldValue;
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return new DNSCache(this);
    }

    // ====================================================================

    /**
     * Returns all entries in the cache
     *
     * @return all entries in the cache
     */
    public synchronized Collection<DNSEntry> allValues() {
        List<DNSEntry> allValues = new ArrayList<DNSEntry>();
        for (List<? extends DNSEntry> entry : this.values()) {
            if (entry != null) {
                allValues.addAll(entry);
            }
        }
        return allValues;
    }

    /**
     * Iterate only over items with matching name. Returns an list of DNSEntry or null. To retrieve all entries, one must iterate over this linked list.
     *
     * @param name
     * @return list of DNSEntries
     */
    public synchronized Collection<? extends DNSEntry> getDNSEntryList(String name) {
        Collection<? extends DNSEntry> entryList = this._getDNSEntryList(name);
        if (entryList != null) {
            entryList = new ArrayList<DNSEntry>(entryList);
        } else {
            entryList = Collections.emptyList();
        }
        return entryList;
    }

    private Collection<? extends DNSEntry> _getDNSEntryList(String name) {
        return this.get(name != null ? name.toLowerCase() : null);
    }

    /**
     * Get a matching DNS entry from the table (using isSameEntry). Returns the entry that was found.
     *
     * @param dnsEntry
     * @return DNSEntry
     */
    public synchronized DNSEntry getDNSEntry(DNSEntry dnsEntry) {
        DNSEntry result = null;
        if (dnsEntry != null) {
            Collection<? extends DNSEntry> entryList = this._getDNSEntryList(dnsEntry.getKey());
            if (entryList != null) {
                for (DNSEntry testDNSEntry : entryList) {
                    if (testDNSEntry.isSameEntry(dnsEntry)) {
                        result = testDNSEntry;
                        break;
                    }
                }
            }
        }
        return result;
    }

    /**
     * Get a matching DNS entry from the table.
     *
     * @param name
     * @param type
     * @param recordClass
     * @return DNSEntry
     */
    public synchronized DNSEntry getDNSEntry(String name, DNSRecordType type, DNSRecordClass recordClass) {
        DNSEntry result = null;
        Collection<? extends DNSEntry> entryList = this._getDNSEntryList(name);
        if (entryList != null) {
            for (DNSEntry testDNSEntry : entryList) {
                if (testDNSEntry.getRecordType().equals(type) && ((DNSRecordClass.CLASS_ANY == recordClass) || testDNSEntry.getRecordClass().equals(recordClass))) {
                    result = testDNSEntry;
                    break;
                }
            }
        }
        return result;
    }

    /**
     * Get all matching DNS entries from the table.
     *
     * @param name
     * @param type
     * @param recordClass
     * @return list of entries
     */
    public synchronized Collection<? extends DNSEntry> getDNSEntryList(String name, DNSRecordType type, DNSRecordClass recordClass) {
        Collection<? extends DNSEntry> entryList = this._getDNSEntryList(name);
        if (entryList != null) {
            entryList = new ArrayList<DNSEntry>(entryList);
            for (Iterator<? extends DNSEntry> i = entryList.iterator(); i.hasNext();) {
                DNSEntry testDNSEntry = i.next();
                if (!testDNSEntry.getRecordType().equals(type) || ((DNSRecordClass.CLASS_ANY != recordClass) && !testDNSEntry.getRecordClass().equals(recordClass))) {
                    i.remove();
                }
            }
        } else {
            entryList = Collections.emptyList();
        }
        return entryList;
    }

    /**
     * Adds an entry to the table.
     *
     * @param dnsEntry
     * @return true if the entry was added
     */
    public synchronized boolean addDNSEntry(final DNSEntry dnsEntry) {
        boolean result = false;
        if (dnsEntry != null) {
            Map.Entry<String, List<? extends DNSEntry>> oldEntry = this.getEntry(dnsEntry.getKey());

            List<DNSEntry> aNewValue = null;
            if (oldEntry != null) {
                aNewValue = new ArrayList<DNSEntry>(oldEntry.getValue());
            } else {
                aNewValue = new ArrayList<DNSEntry>();
            }
            aNewValue.add(dnsEntry);

            if (oldEntry != null) {
                oldEntry.setValue(aNewValue);
            } else {
                this.entrySet().add(new _CacheEntry(dnsEntry.getKey(), aNewValue));
            }
            // This is probably not very informative
            result = true;
        }
        return result;
    }

    /**
     * Removes a specific entry from the table. Returns true if the entry was found.
     *
     * @param dnsEntry
     * @return true if the entry was removed
     */
    public synchronized boolean removeDNSEntry(DNSEntry dnsEntry) {
        boolean result = false;
        if (dnsEntry != null) {
            Map.Entry<String, List<? extends DNSEntry>> existingEntry = this.getEntry(dnsEntry.getKey());
            if (existingEntry != null) {
                result = existingEntry.getValue().remove(dnsEntry);
                // If we just removed the last one we need to get rid of the entry
                if (existingEntry.getValue().isEmpty()) {
                    this.entrySet().remove(existingEntry);
                }
            }
        }
        return result;
    }

    /**
     * Replace an existing entry by a new one.<br/>
     * <b>Note:</b> the 2 entries must have the same key.
     *
     * @param newDNSEntry
     * @param existingDNSEntry
     * @return <code>true</code> if the entry has been replace, <code>false</code> otherwise.
     */
    public synchronized boolean replaceDNSEntry(DNSEntry newDNSEntry, DNSEntry existingDNSEntry) {
        boolean result = false;
        if ((newDNSEntry != null) && (existingDNSEntry != null) && (newDNSEntry.getKey().equals(existingDNSEntry.getKey()))) {
            Map.Entry<String, List<? extends DNSEntry>> oldEntry = this.getEntry(newDNSEntry.getKey());

            List<DNSEntry> aNewValue = null;
            if (oldEntry != null) {
                aNewValue = new ArrayList<DNSEntry>(oldEntry.getValue());
            } else {
                aNewValue = new ArrayList<DNSEntry>();
            }
            aNewValue.remove(existingDNSEntry);
            aNewValue.add(newDNSEntry);

            if (oldEntry != null) {
                oldEntry.setValue(aNewValue);
            } else {
                this.entrySet().add(new _CacheEntry(newDNSEntry.getKey(), aNewValue));
            }
            // This is probably not very informative
            result = true;
        }
        return result;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public synchronized String toString() {
        StringBuffer aLog = new StringBuffer(2000);
        aLog.append("\t---- cache ----");
        for (Map.Entry<String, List<? extends DNSEntry>> entry : this.entrySet()) {
            aLog.append("\n\t\t");
            aLog.append(entry.toString());
        }
        return aLog.toString();
    }

}