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.logging.Level;
import java.util.logging.Logger;
-import net.pterodactylus.fcp.highlevel.ConnectResult;
-import net.pterodactylus.fcp.highlevel.HighLevelCallback;
-import net.pterodactylus.fcp.highlevel.HighLevelClient;
+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 {
+public class NodeManager implements Iterable<Node>, PropertyChangeListener {
/** Logger. */
- private static final Logger logger = Logger.getLogger(NodeManager.class.getName());
+ private static final Logger logger = Logging.getLogger(NodeManager.class.getName());
/** The FCP client name. */
private final String clientName;
/** Object used for synchronization. */
private final Object syncObject = new Object();
- /** All nodes. */
- private List<Node> nodes = Collections.synchronizedList(new ArrayList<Node>());
+ /** Node listener support. */
+ private final NodeListenerSupport nodeListenerSupport = new NodeListenerSupport();
- /** All FCP connections. */
- private Map<Node, HighLevelClient> nodeConnections = Collections.synchronizedMap(new HashMap<Node, HighLevelClient>());
+ /** All nodes. */
+ private final List<Node> nodes = Collections.synchronizedList(new ArrayList<Node>());
- /** Keeps track of which connection is in use right now. */
- private Set<HighLevelClient> usedConnections = Collections.synchronizedSet(new HashSet<HighLevelClient>());
+ /** Map from node ID to node. */
+ private final Map<String, Node> idNodes = Collections.synchronizedMap(new HashMap<String, Node>());
- /** Maps nodes to high-level clients. */
- private 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.
}
//
+ // EVENT MANAGEMENT
+ //
+
+ /**
+ * Adds the given listener to the list of listeners.
+ *
+ * @param nodeListener
+ * The listener to add
+ */
+ public void addNodeListener(NodeListener nodeListener) {
+ nodeListenerSupport.addListener(nodeListener);
+ }
+
+ /**
+ * Removes the given listener from the list of listeners.
+ *
+ * @param nodeListener
+ * The listener to remove
+ */
+ public void removeNodeListener(NodeListener nodeListener) {
+ nodeListenerSupport.removeListener(nodeListener);
+ }
+
+ //
// ACCESSORS
//
return nodes.contains(node);
}
+ /**
+ * Returns whether the given node is currently connected.
+ *
+ * @param node
+ * The node to check
+ * @return <code>true</code> if the node is currently connected,
+ * <code>false</code> otherwise
+ */
+ public boolean isNodeConnected(Node node) {
+ return connectedNodes.contains(node);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Iterator<Node> iterator() {
+ return nodes.iterator();
+ }
+
//
// ACTIONS
//
* 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()) {
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…");
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);
+ }
}
}
* 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()) {
}
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()));
}
/**
- * Adds a connection to the given node. The connection is made instantly so
- * this method may block. If the node can not be connected, it will not be
- * added to the list of nodes.
+ * Adds the given node to this manager.
*
+ * @see #connect(Node)
* @param node
* The node to connect to
- * @return <code>true</code> if the connection to the node could be
- * established
- * @throws UnknownHostException
- * if the hostname of the node can not be resolved
- * @throws IOException
- * if an I/O error occurs connecting to the node
+ * @return <code>true</code> if the node was added, <code>false</code> if
+ * the node was not added because it was already known
*/
- public boolean addNode(Node node) throws UnknownHostException, IOException {
+ public boolean addNode(Node node) {
+ logger.log(Level.FINEST, "addNode(node=" + node + ")");
if (nodes.contains(node)) {
- return true;
+ logger.log(Level.WARNING, "was told to add already known node: " + node);
+ return false;
}
- HighLevelClient highLevelClient = new HighLevelClient(clientName, node.getHostname(), node.getPort());
- HighLevelCallback<ConnectResult> connectCallback = highLevelClient.connect();
- ConnectResult connectResult = null;
- while (connectResult == null) {
- try {
- connectResult = connectCallback.getResult();
- } catch (InterruptedException e) {
- /* ignore. */
+ node.addPropertyChangeListener(this);
+ nodes.add(node);
+ idNodes.put(node.getId(), node);
+ nodeListenerSupport.fireNodeAdded(node);
+ return true;
+ }
+
+ /**
+ * Removes the given node from the node manager, disconnecting it if it is
+ * currently connected.
+ *
+ * @param node
+ * The node to remove
+ */
+ public void removeNode(Node node) {
+ logger.log(Level.FINEST, "removeNode(node=" + node + ")");
+ synchronized (syncObject) {
+ if (!nodes.contains(node)) {
+ return;
}
+ nodes.remove(node);
+ idNodes.remove(node.getId());
+ node.removePropertyChangeListener(this);
+ nodeListenerSupport.fireNodeRemoved(node);
}
- if (connectResult.isConnected()) {
- synchronized (syncObject) {
- nodes.add(node);
- nodeConnections.put(node, highLevelClient);
- clientNodes.put(highLevelClient, node);
- }
+ }
+
+ /**
+ * Tries to establish a connection with the given node.
+ *
+ * @param node
+ * The node to connect to
+ */
+ public void connect(Node node) {
+ logger.log(Level.FINEST, "connect(node=" + node + ")");
+ if (!nodes.contains(node)) {
+ logger.log(Level.WARNING, "Was told to connect to node (" + node + ") I don’t know about!");
+ return;
}
- return connectResult.isConnected();
+ }
+
+ /**
+ * Disconnects the given node without removing it.
+ *
+ * @param node
+ * The node to disconnect
+ */
+ public void disconnect(Node node) {
+ logger.log(Level.FINEST, "disconnect(node=" + node + ")");
}
/**
* @return A list of all nodes
*/
public List<Node> getNodes() {
- return new ArrayList<Node>(clientNodes.values());
+ return Collections.unmodifiableList(nodes);
+ }
+
+ /**
+ * 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");
+ }
+ return null;
}
//
// PRIVATE METHODS
//
+ //
+ // INTERFACE PropertyChangeListener
+ //
+
/**
- * Finds a currently unused high-level client, optionally waiting until a
- * client is free and marking it used.
- *
- * @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
+ * {@inheritDoc}
*/
- @SuppressWarnings("unused")
- private HighLevelClient findUnusedClient(boolean wait, boolean markAsUsed) {
- synchronized (syncObject) {
- HighLevelClient freeHighLevelClient = null;
- while (freeHighLevelClient == null) {
- for (HighLevelClient highLevelClient: nodeConnections.values()) {
- if (!usedConnections.contains(highLevelClient)) {
- freeHighLevelClient = highLevelClient;
- break;
- }
- }
- if (freeHighLevelClient != null) {
- if (markAsUsed) {
- usedConnections.add(freeHighLevelClient);
- }
- return freeHighLevelClient;
- }
- if (!wait) {
- return null;
- }
+ public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
+ Object eventSource = propertyChangeEvent.getSource();
+ if (eventSource instanceof Node) {
+ String propertyName = propertyChangeEvent.getPropertyName();
+ if ("hostname".equals(propertyName) || "port".equals(propertyName)) {
+ /* TODO - reconnect. */
}
- /* we never get here, but the compiler doesn't realize. */
- return null;
}
}