Expose connection uptime
authorDavid ‘Bombe’ Roden <bombe@pterodactylus.net>
Mon, 23 Feb 2015 05:37:22 +0000 (06:37 +0100)
committerDavid ‘Bombe’ Roden <bombe@pterodactylus.net>
Mon, 23 Feb 2015 05:37:22 +0000 (06:37 +0100)
src/main/java/net/pterodactylus/irc/Connection.java
src/main/java/net/pterodactylus/irc/DefaultConnection.java

index 580b4d7..ca6c494 100644 (file)
@@ -1,6 +1,8 @@
 package net.pterodactylus.irc;
 
 import java.io.IOException;
+import java.time.Duration;
+import java.util.Optional;
 
 /**
  * A connection to an IRC server.
@@ -144,4 +146,6 @@ public interface Connection {
         */
        void close() throws IOException;
 
+       Optional<Duration> getUptime();
+
 }
index 8fe4c4b..876aefb 100644 (file)
@@ -30,11 +30,14 @@ import java.io.InputStreamReader;
 import java.io.OutputStream;
 import java.io.UnsupportedEncodingException;
 import java.net.Socket;
+import java.time.Duration;
+import java.time.Instant;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Optional;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
 
 import javax.net.SocketFactory;
 
@@ -120,6 +123,7 @@ public class DefaultConnection extends AbstractExecutionThreadService implements
 
        /** Whether the connection has already been established. */
        private final AtomicBoolean established = new AtomicBoolean();
+       private final AtomicReference<Instant> connectionTime = new AtomicReference<>();
 
        /**
         * Creates a new connection.
@@ -230,6 +234,13 @@ public class DefaultConnection extends AbstractExecutionThreadService implements
                }
        }
 
+       @Override
+       public java.util.Optional<Duration> getUptime() {
+               return established.get() ?
+                               java.util.Optional.of(Duration.between(connectionTime.get(), Instant.now())) :
+                               java.util.Optional.<Duration>empty();
+       }
+
        //
        // ABSTRACTEXECUTIONTHREADSERVICE METHODS
        //
@@ -358,6 +369,7 @@ public class DefaultConnection extends AbstractExecutionThreadService implements
        @Subscribe
        public void connectionEstablished(ConnectionEstablished connectionEstablished) {
                if (connectionEstablished.connection() == this) {
+                       connectionTime.set(Instant.now());
                        established.set(true);
                }
        }