1 package au.gov.amsa.ais.router.model; 2 3 import java.io.Closeable; 4 import java.io.IOException; 5 import java.util.Optional; 6 7 import org.slf4j.Logger; 8 import org.slf4j.LoggerFactory; 9 10 import au.gov.amsa.streams.StringServer; 11 import rx.Observable; 12 13 public final class Port implements Closeable { 14 15 private static final Logger log = LoggerFactory.getLogger(Port.class); 16 17 private final int port; 18 private final Optional<GroupMember> group; 19 private final boolean enabled; 20 private final Optional<UserGroup> userGroup; 21 private final Observable<String> lines; 22 23 private Port(int port, Optional<GroupMember> group, boolean enabled, 24 Optional<UserGroup> userGroup) { 25 this.port = port; 26 this.group = group; 27 this.enabled = enabled; 28 this.userGroup = userGroup; 29 this.lines = createLines(); 30 } 31 32 private Observable<String> createLines() { 33 if (group.isPresent()) { 34 return group.get().lines(); 35 } else { 36 return Observable.empty(); 37 } 38 } 39 40 public int port() { 41 return port; 42 } 43 44 public Optional<GroupMember> group() { 45 return group; 46 } 47 48 public Optional<UserGroup> userGroup() { 49 return userGroup; 50 } 51 52 public boolean enabled() { 53 return enabled; 54 } 55 56 public static Builder builder() { 57 return new Builder(); 58 } 59 60 private Optional<StringServer> server = Optional.empty(); 61 private final Object serverLock = new Object(); 62 63 public void start() { 64 log.info("starting " + this); 65 synchronized (serverLock) { 66 if (server.isPresent()) { 67 throw new RuntimeException("server already started"); 68 } else if (enabled && group.isPresent()) { 69 server = Optional.of(StringServer.create(lines.map(line -> line + "\n"), port)); 70 server.get().start(); 71 } 72 } 73 } 74 75 public void stop() { 76 synchronized (serverLock) { 77 if (server.isPresent()) { 78 server.get().stop(); 79 } 80 } 81 } 82 83 public static class Builder { 84 85 private int port; 86 private Optional<GroupMember> group = Optional.empty(); 87 private final Optional<UserGroup> userGroup = Optional.empty(); 88 private boolean enabled = true; 89 90 private Builder() { 91 } 92 93 public Builder port(int port) { 94 this.port = port; 95 return this; 96 } 97 98 public Builder group(GroupMember group) { 99 this.group = Optional.of(group); 100 return this; 101 } 102 103 public Builder enabled(boolean enabled) { 104 this.enabled = enabled; 105 return this; 106 } 107 108 public Port build() { 109 return new Port(port, group, enabled, userGroup); 110 } 111 } 112 113 @Override 114 public void close() throws IOException { 115 stop(); 116 } 117 118 @Override 119 public String toString() { 120 StringBuilder b = new StringBuilder(); 121 b.append("Port [port="); 122 b.append(port); 123 b.append(", group="); 124 b.append(group); 125 b.append(", enabled="); 126 b.append(enabled); 127 b.append(", userGroup="); 128 b.append(userGroup); 129 b.append("]"); 130 return b.toString(); 131 } 132 133 }