4 * Copyright 2015 TJ <hacker@iamtj>.
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 package uk.ac.ntu.n0521366.wsyd.libs.net;
26 import java.net.InetSocketAddress;
27 import java.text.MessageFormat;
28 import java.util.ArrayList;
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.logging.Level;
31 import java.util.logging.Logger;
34 * Maps service names on hosts to an InetAddress:Port pair.
36 * @author TJ <hacker@iamtj>
38 public class ServiceAddressMap {
40 * Multi-thread safe map keyed on the service name.
42 protected ConcurrentHashMap<String, LastSeenHost> _serviceToAddressMap = new ConcurrentHashMap<>();
45 * Encapsulates a unique network host and the last time it was seen.
47 public static class LastSeenHost {
51 * STATIC = was manually entered and should not be removed
52 * DYNAMIC = was discovered via multicast announcement or new connection and can be removed
54 public static enum STATE {STATIC, DYNAMIC}
57 final long timeInMillis;
58 final InetSocketAddress address;
61 * Constructs a new instance of a host.
63 * @param address The current address:port
64 * @param timeInMillis time last seen
65 * @param state whether record was added through dynamic discovery
67 LastSeenHost(InetSocketAddress address, long timeInMillis, STATE state) {
68 this.address = address;
69 this.timeInMillis = timeInMillis;
74 * Construct a new instance of a dynamically announced host.
78 LastSeenHost(InetSocketAddress host) {
79 this(host, System.currentTimeMillis(), STATE.DYNAMIC);
83 * Formatted string representation of InetAddress and timestamp.
84 * @return the representation
87 public String toString() {
88 return MessageFormat.format("{0}:{1,number,integer}@{2}", this.address.getHostString(), this.address.getPort(), this.timeInMillis);
95 private static Logger LOGGER = null;
98 * Facility name for logger
100 private String _facility = null;
103 * Construct a map with a Logger.
105 * @param facility The log facility to tag messages with
106 * @param logger The Logger
108 public ServiceAddressMap(String facility, Logger logger) {
109 this._facility = facility;
118 private void log(Level level, String message) {
121 LOGGER.logp(level, _facility, null, message);
125 * Remove stale service records.
127 * @param ageInMillis milliseconds since last seen to be considered stale
128 * @return quantity of records removed
130 public ArrayList<String> cleanServiceAddressMap(long ageInMillis) {
131 ArrayList<String> result = new ArrayList<>();
132 long expireTime = System.currentTimeMillis() - ageInMillis;
133 java.util.Enumeration<String> keys = this._serviceToAddressMap.keys();
134 while (keys.hasMoreElements()) {
135 String key = keys.nextElement();
137 // XXX: special handling for "all" target - never remove it
138 LastSeenHost host = _serviceToAddressMap.get(key);
139 if (host != null && host.state == LastSeenHost.STATE.DYNAMIC) {
140 if (host.timeInMillis < expireTime) {
141 if (_serviceToAddressMap.remove(key, host)) {
143 log(Level.INFO, MessageFormat.format("Removed \"{0}\" from service map", key));
152 * Ensure service is in the map of known hosts.
153 * @param service the service name to check
154 * @return true is the target service is known
156 protected boolean isServiceValid(String service) {
157 return this._serviceToAddressMap.containsKey(service);
161 * Get the current InetSocketAddress of a target.
163 * @param target name of the service
164 * @return IP address and port of the service
166 public InetSocketAddress getServiceAddress(String target) {
167 InetSocketAddress result = null;
169 if (target != null && target.length() > 0) {
170 LastSeenHost host = this._serviceToAddressMap.get(target);
172 result = host.address;
178 public void put(String service, LastSeenHost host) {
179 this._serviceToAddressMap.put(service, host);
182 public LastSeenHost get(String service) {
183 return this._serviceToAddressMap.get(service);