Make all member collections final.
[jSite2.git] / src / net / pterodactylus / jsite / core / NodeManager.java
index 5ed51a7..9cdc60d 100644 (file)
 
 package net.pterodactylus.jsite.core;
 
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
+import java.net.UnknownHostException;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashMap;
-import java.util.HashSet;
+import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Properties;
-import java.util.Set;
 import java.util.logging.Level;
 import java.util.logging.Logger;
 
 import net.pterodactylus.fcp.highlevel.HighLevelClient;
 import net.pterodactylus.fcp.highlevel.HighLevelClientListener;
+import net.pterodactylus.fcp.highlevel.HighLevelException;
+import net.pterodactylus.fcp.highlevel.KeyGenerationResult;
+import net.pterodactylus.jsite.util.IdGenerator;
 import net.pterodactylus.util.io.Closer;
 import net.pterodactylus.util.logging.Logging;
+import net.pterodactylus.util.number.Hex;
 
 /**
  * TODO
  *
  * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
- * @version $Id$
  */
-public class NodeManager implements HighLevelClientListener {
+public class NodeManager implements Iterable<Node>, PropertyChangeListener, HighLevelClientListener {
 
        /** Logger. */
        private static final Logger logger = Logging.getLogger(NodeManager.class.getName());
@@ -61,20 +66,23 @@ public class NodeManager implements HighLevelClientListener {
        /** Object used for synchronization. */
        private final Object syncObject = new Object();
 
-       /** Node listeners. */
-       private List<NodeListener> nodeListeners = Collections.synchronizedList(new ArrayList<NodeListener>());
+       /** Node listener support. */
+       private final NodeListenerSupport nodeListenerSupport = new NodeListenerSupport();
 
        /** All nodes. */
-       private List<Node> nodes = Collections.synchronizedList(new ArrayList<Node>());
+       private final List<Node> nodes = Collections.synchronizedList(new ArrayList<Node>());
 
-       /** All FCP connections. */
-       private Map<Node, HighLevelClient> nodeClients = Collections.synchronizedMap(new HashMap<Node, HighLevelClient>());
+       /** Map from node ID to node. */
+       private final Map<String, Node> idNodes = Collections.synchronizedMap(new HashMap<String, Node>());
 
-       /** Keeps track of which connection is in use right now. */
-       private Set<HighLevelClient> usedConnections = Collections.synchronizedSet(new HashSet<HighLevelClient>());
+       /** All FCP connections. */
+       private final Map<Node, HighLevelClient> nodeClients = Collections.synchronizedMap(new HashMap<Node, HighLevelClient>());
 
        /** Maps nodes to high-level clients. */
-       private Map<HighLevelClient, Node> clientNodes = Collections.synchronizedMap(new HashMap<HighLevelClient, Node>());
+       private final Map<HighLevelClient, Node> clientNodes = Collections.synchronizedMap(new HashMap<HighLevelClient, Node>());
+
+       /** Collection of currently connected nodes. */
+       private final Set<Node> connectedNodes = Collections.synchronizedSet(new HashSet<Node>());
 
        /**
         * Creates a new FCP collector.
@@ -100,7 +108,7 @@ public class NodeManager implements HighLevelClientListener {
         *            The listener to add
         */
        public void addNodeListener(NodeListener nodeListener) {
-               nodeListeners.add(nodeListener);
+               nodeListenerSupport.addListener(nodeListener);
        }
 
        /**
@@ -110,34 +118,7 @@ public class NodeManager implements HighLevelClientListener {
         *            The listener to remove
         */
        public void removeNodeListener(NodeListener nodeListener) {
-               nodeListeners.remove(nodeListener);
-       }
-
-       /**
-        * Notifies all listeners that the given node was connected.
-        *
-        * @param node
-        *            The node that is now connected
-        */
-       private void fireNodeConnected(Node node) {
-               for (NodeListener nodeListener: nodeListeners) {
-                       nodeListener.nodeConnected(node);
-               }
-       }
-
-       /**
-        * Notifies all listeners that the given node was disconnected.
-        *
-        * @param node
-        *            The node that is now disconnected
-        * @param throwable
-        *            The exception that caused the disconnect, or <code>null</code>
-        *            if there was no exception
-        */
-       private void fireNodeDisconnected(Node node, Throwable throwable) {
-               for (NodeListener nodeListener: nodeListeners) {
-                       nodeListener.nodeDisconnected(node, throwable);
-               }
+               nodeListenerSupport.removeListener(nodeListener);
        }
 
        //
@@ -165,6 +146,13 @@ public class NodeManager implements HighLevelClientListener {
                return nodes.contains(node);
        }
 
+       /**
+        * {@inheritDoc}
+        */
+       public Iterator<Node> iterator() {
+               return nodes.iterator();
+       }
+
        //
        // ACTIONS
        //
@@ -176,6 +164,7 @@ public class NodeManager implements HighLevelClientListener {
         *             if an I/O error occurs loading the nodes
         */
        public void load() throws IOException {
+               logger.log(Level.FINEST, "load()");
                File directoryFile = new File(directory);
                File nodeFile = new File(directoryFile, "nodes.properties");
                if (!nodeFile.exists() || !nodeFile.isFile() || !nodeFile.canRead()) {
@@ -193,6 +182,10 @@ public class NodeManager implements HighLevelClientListener {
                List<Node> loadedNodes = new ArrayList<Node>();
                while (nodeProperties.containsKey("nodes." + ++nodeIndex + ".name")) {
                        String nodePrefix = "nodes." + nodeIndex;
+                       String nodeId = nodeProperties.getProperty(nodePrefix + ".id");
+                       if (nodeId == null) {
+                               nodeId = Hex.toHex(IdGenerator.generateId());
+                       }
                        String nodeName = nodeProperties.getProperty(nodePrefix + ".name");
                        if (!Verifier.verifyNodeName(nodeName)) {
                                logger.log(Level.WARNING, "invalid node name “" + nodeName + "”, skipping…");
@@ -217,14 +210,18 @@ public class NodeManager implements HighLevelClientListener {
                                continue;
                        }
                        Node newNode = new Node();
+                       newNode.setId(nodeId);
                        newNode.setName(nodeName);
                        newNode.setHostname(nodeHostname);
                        newNode.setPort(nodePort);
                        loadedNodes.add(newNode);
                }
+               logger.log(Level.FINE, "loaded " + loadedNodes.size() + " nodes from config");
                synchronized (syncObject) {
                        nodes.clear();
-                       nodes.addAll(loadedNodes);
+                       for (Node node : loadedNodes) {
+                               addNode(node);
+                       }
                }
        }
 
@@ -235,6 +232,7 @@ public class NodeManager implements HighLevelClientListener {
         *             if an I/O error occurs saving the nodes
         */
        public void save() throws IOException {
+               logger.log(Level.FINEST, "save()");
                File directoryFile = new File(directory);
                if (!directoryFile.exists()) {
                        if (!directoryFile.mkdirs()) {
@@ -243,8 +241,9 @@ public class NodeManager implements HighLevelClientListener {
                }
                Properties nodeProperties = new Properties();
                int nodeIndex = -1;
-               for (Node node: nodes) {
+               for (Node node : nodes) {
                        String nodePrefix = "nodes." + ++nodeIndex;
+                       nodeProperties.setProperty(nodePrefix + ".id", node.getId());
                        nodeProperties.setProperty(nodePrefix + ".name", node.getName());
                        nodeProperties.setProperty(nodePrefix + ".hostname", node.getHostname());
                        nodeProperties.setProperty(nodePrefix + ".port", String.valueOf(node.getPort()));
@@ -265,13 +264,24 @@ public class NodeManager implements HighLevelClientListener {
         * @see #connect(Node)
         * @param node
         *            The node to connect to
+        * @return <code>true</code> if the node was added, <code>false</code> if
+        *         the node was not added because it was already known
         */
-       public void addNode(Node node) {
-               synchronized (syncObject) {
-                       if (!nodes.contains(node)) {
-                               nodes.add(node);
-                       }
+       public boolean addNode(Node node) {
+               logger.log(Level.FINEST, "addNode(node=" + node + ")");
+               if (nodes.contains(node)) {
+                       logger.log(Level.WARNING, "was told to add already known node: " + node);
+                       return false;
                }
+               node.addPropertyChangeListener(this);
+               HighLevelClient highLevelClient = new HighLevelClient(clientName);
+               nodes.add(node);
+               idNodes.put(node.getId(), node);
+               clientNodes.put(highLevelClient, node);
+               nodeClients.put(node, highLevelClient);
+               highLevelClient.addHighLevelClientListener(this);
+               nodeListenerSupport.fireNodeAdded(node);
+               return true;
        }
 
        /**
@@ -282,6 +292,7 @@ public class NodeManager implements HighLevelClientListener {
         *            The node to remove
         */
        public void removeNode(Node node) {
+               logger.log(Level.FINEST, "removeNode(node=" + node + ")");
                synchronized (syncObject) {
                        if (!nodes.contains(node)) {
                                return;
@@ -289,6 +300,10 @@ public class NodeManager implements HighLevelClientListener {
                        if (nodeClients.containsKey(node)) {
                                disconnect(node);
                        }
+                       nodes.remove(node);
+                       idNodes.remove(node.getId());
+                       node.removePropertyChangeListener(this);
+                       nodeListenerSupport.fireNodeRemoved(node);
                }
        }
 
@@ -299,16 +314,19 @@ public class NodeManager implements HighLevelClientListener {
         *            The node to connect to
         */
        public void connect(Node node) {
+               logger.log(Level.FINEST, "connect(node=" + node + ")");
+               HighLevelClient highLevelClient;
+               highLevelClient = nodeClients.get(node);
+               if (highLevelClient == null) {
+                       logger.log(Level.WARNING, "was told to connect to unknown node: " + node);
+                       return;
+               }
                try {
-                       HighLevelClient highLevelClient = new HighLevelClient(clientName, node.getHostname(), node.getPort());
-                       synchronized (syncObject) {
-                               clientNodes.put(highLevelClient, node);
-                               nodeClients.put(node, highLevelClient);
-                       }
-                       highLevelClient.addHighLevelClientListener(this);
-                       highLevelClient.connect();
+                       highLevelClient.connect(node.getHostname(), node.getPort());
+               } catch (UnknownHostException uhe1) {
+                       nodeListenerSupport.fireNodeConnectionFailed(node, uhe1);
                } catch (IOException ioe1) {
-                       fireNodeDisconnected(node, ioe1);
+                       nodeListenerSupport.fireNodeConnectionFailed(node, ioe1);
                }
        }
 
@@ -319,6 +337,7 @@ public class NodeManager implements HighLevelClientListener {
         *            The node to disconnect
         */
        public void disconnect(Node node) {
+               logger.log(Level.FINEST, "disconnect(node=" + node + ")");
                synchronized (syncObject) {
                        if (!nodes.contains(node)) {
                                return;
@@ -337,50 +356,75 @@ public class NodeManager implements HighLevelClientListener {
                return Collections.unmodifiableList(nodes);
        }
 
-       //
-       // PRIVATE METHODS
-       //
+       /**
+        * Returns the high-level client for a given node.
+        *
+        * @param node
+        *            The node to get a high-level client for
+        * @return The high-level client for a node, or <code>null</code> if the
+        *         node was disconnected or removed
+        */
+       public HighLevelClient getHighLevelClient(Node node) {
+               return nodeClients.get(node);
+       }
 
        /**
-        * Finds a currently unused high-level client, optionally waiting until a
-        * client is free and marking it used.
+        * Returns the node for a high-level client.
         *
-        * @param wait
-        *            <code>true</code> to wait for a free connection,
-        *            <code>false</code> to return <code>null</code>
-        * @param markAsUsed
-        *            <code>true</code> to mark the connection as used before
-        *            returning it, <code>false</code> not to mark it
-        * @return An unused FCP connection, or <code>null</code> if no connection
-        *         could be found
+        * @param highLevelClient
+        *            The high-level client to get the node for
+        * @return The node for the high-level client, or <code>null</code> if the
+        *         high-level client is not known
         */
-       @SuppressWarnings("unused")
-       private HighLevelClient findUnusedClient(boolean wait, boolean markAsUsed) {
-               synchronized (syncObject) {
-                       HighLevelClient freeHighLevelClient = null;
-                       while (freeHighLevelClient == null) {
-                               for (HighLevelClient highLevelClient: nodeClients.values()) {
-                                       if (!usedConnections.contains(highLevelClient)) {
-                                               freeHighLevelClient = highLevelClient;
-                                               break;
-                                       }
-                               }
-                               if (freeHighLevelClient != null) {
-                                       if (markAsUsed) {
-                                               usedConnections.add(freeHighLevelClient);
-                                       }
-                                       return freeHighLevelClient;
-                               }
-                               if (!wait) {
-                                       return null;
-                               }
-                       }
-                       /* we never get here, but the compiler doesn't realize. */
-                       return null;
+       public Node getNode(HighLevelClient highLevelClient) {
+               return clientNodes.get(highLevelClient);
+       }
+
+       /**
+        * Returns the node identified by the given ID.
+        *
+        * @param id
+        *            The ID of the node
+        * @return The node with the given ID, or <code>null</code> if no such node
+        *         was found
+        */
+       Node getNode(String id) {
+               return idNodes.get(id);
+       }
+
+       /**
+        * Generates a new SSK key pair.
+        *
+        * @return An array with the private key at index <code>0</code> and the
+        *         public key at index <code>1</code>
+        * @throws IOException
+        *             if an I/O error occurs communicating with the node
+        * @throws JSiteException
+        *             if there is a problem with the node
+        */
+       public String[] generateKeyPair() throws IOException, JSiteException {
+               logger.log(Level.FINEST, "generateKeyPair()");
+               if (nodes.isEmpty()) {
+                       throw new NoNodeException("no node configured");
                }
+               Node node = nodes.get(0);
+               HighLevelClient highLevelClient = nodeClients.get(node);
+               try {
+                       KeyGenerationResult keyGenerationResult = highLevelClient.generateKey().getResult();
+                       return new String[] { keyGenerationResult.getInsertURI(), keyGenerationResult.getRequestURI() };
+               } catch (HighLevelException hle1) {
+                       throw new BackendException(hle1);
+               } catch (InterruptedException e) {
+                       /* ignore. */
+               }
+               return null;
        }
 
        //
+       // PRIVATE METHODS
+       //
+
+       //
        // INTERFACE HighLevelClientListener
        //
 
@@ -388,28 +432,59 @@ public class NodeManager implements HighLevelClientListener {
         * {@inheritDoc}
         */
        public void clientConnected(HighLevelClient highLevelClient) {
-               logger.log(Level.FINER, "clientConnected(c=" + highLevelClient + ")");
+               logger.log(Level.FINEST, "clientConnected(highLevelClient=" + highLevelClient + ")");
                Node node = clientNodes.get(highLevelClient);
                if (node == null) {
                        logger.log(Level.WARNING, "got event for unknown client");
                        return;
                }
-               fireNodeConnected(node);
+               nodeListenerSupport.fireNodeConnected(node);
        }
 
        /**
         * {@inheritDoc}
         */
        public void clientDisconnected(HighLevelClient highLevelClient, Throwable throwable) {
-               logger.log(Level.FINER, "clientDisconnected(c=" + highLevelClient + ",t=" + throwable +")");
+               logger.log(Level.FINEST, "clientDisconnected(highLevelClient=" + highLevelClient + ",throwable=" + throwable + ")");
                synchronized (syncObject) {
-                       Node node = clientNodes.remove(highLevelClient);
+                       Node node = clientNodes.get(highLevelClient);
                        if (node == null) {
                                logger.log(Level.WARNING, "got event for unknown client");
                                return;
                        }
-                       nodeClients.remove(node);
-                       fireNodeDisconnected(node, throwable);
+                       nodeListenerSupport.fireNodeDisconnected(node, throwable);
+               }
+       }
+
+       //
+       // INTERFACE PropertyChangeListener
+       //
+
+       /**
+        * {@inheritDoc}
+        */
+       public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
+               Object eventSource = propertyChangeEvent.getSource();
+               if (eventSource instanceof Node) {
+                       String propertyName = propertyChangeEvent.getPropertyName();
+                       if ("hostname".equals(propertyName) || "port".equals(propertyName)) {
+                               Node node = (Node) eventSource;
+                               HighLevelClient highLevelClient = nodeClients.get(node);
+                               if (highLevelClient == null) {
+                                       logger.log(Level.WARNING, "got property change event for unknown node: " + node);
+                                       return;
+                               }
+                               if (highLevelClient.isConnected()) {
+                                       highLevelClient.disconnect();
+                                       try {
+                                               highLevelClient.connect(node.getHostname(), node.getPort());
+                                       } catch (UnknownHostException uhe1) {
+                                               nodeListenerSupport.fireNodeConnectionFailed(node, uhe1);
+                                       } catch (IOException ioe1) {
+                                               nodeListenerSupport.fireNodeConnectionFailed(node, ioe1);
+                                       }
+                               }
+                       }
                }
        }