001package jmri.server.json.throttle; 002 003import com.fasterxml.jackson.databind.ObjectMapper; 004import java.util.ArrayList; 005import java.util.Collection; 006import java.util.HashMap; 007import java.util.List; 008import jmri.DccLocoAddress; 009import jmri.InstanceManager; 010import jmri.InstanceManagerAutoDefault; 011import jmri.ThrottleListener; 012import jmri.ThrottleManager; 013 014/** 015 * Manager for {@link jmri.server.json.throttle.JsonThrottle} objects. A manager 016 * is needed since multiple JsonThrottle objects may be controlling the same 017 * {@link jmri.DccLocoAddress}. 018 * 019 * @author Randall Wood Copyright 2016, 2018 020 */ 021public class JsonThrottleManager implements InstanceManagerAutoDefault { 022 023 private final HashMap<DccLocoAddress, JsonThrottle> throttles = new HashMap<>(); 024 private final HashMap<JsonThrottle, ArrayList<JsonThrottleSocketService>> services = new HashMap<>(); 025 private final ObjectMapper mapper = new ObjectMapper(); 026 027 public JsonThrottleManager() { 028 // do nothing 029 } 030 031 public Collection<JsonThrottle> getThrottles() { 032 return this.throttles.values(); 033 } 034 035 public void put(DccLocoAddress address, JsonThrottle throttle) { 036 this.throttles.put(address, throttle); 037 } 038 039 public void put(JsonThrottle throttle, JsonThrottleSocketService service) { 040 this.services.computeIfAbsent(throttle, v -> new ArrayList<>()).add(service); 041 } 042 043 public boolean containsKey(DccLocoAddress address) { 044 return this.throttles.containsKey(address); 045 } 046 047 public JsonThrottle get(DccLocoAddress address) { 048 return this.throttles.get(address); 049 } 050 051 public void remove(DccLocoAddress address) { 052 this.throttles.remove(address); 053 } 054 055 public List<JsonThrottleSocketService> getServers(JsonThrottle throttle) { 056 return this.services.computeIfAbsent(throttle, v -> new ArrayList<>()); 057 } 058 059 public void remove(JsonThrottle throttle, JsonThrottleSocketService server) { 060 this.getServers(throttle).remove(server); 061 } 062 063 public ObjectMapper getObjectMapper() { 064 return this.mapper; 065 } 066 067 public boolean canBeLongAddress(int asInt) { 068 return InstanceManager.getDefault(ThrottleManager.class).canBeLongAddress(asInt); 069 } 070 071 public boolean canBeShortAddress(int asInt) { 072 return InstanceManager.getDefault(ThrottleManager.class).canBeShortAddress(asInt); 073 } 074 075 public boolean requestThrottle(DccLocoAddress address, ThrottleListener listener) { 076 return InstanceManager.getDefault(ThrottleManager.class).requestThrottle(address, listener, false); 077 } 078 079 public boolean requestThrottle(jmri.BasicRosterEntry rosterEntry, ThrottleListener listener) { 080 return InstanceManager.getDefault(ThrottleManager.class).requestThrottle(rosterEntry, listener, false); 081 } 082 083 // private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(JsonThrottleManager.class); 084}