2 * jSite2 - FcpCollector.java -
3 * Copyright © 2008 David Roden
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 package net.pterodactylus.jsite.core;
22 import java.beans.PropertyChangeEvent;
23 import java.beans.PropertyChangeListener;
25 import java.io.FileInputStream;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.io.OutputStream;
30 import java.net.UnknownHostException;
31 import java.util.ArrayList;
32 import java.util.Collections;
33 import java.util.HashMap;
34 import java.util.Iterator;
35 import java.util.List;
37 import java.util.Properties;
38 import java.util.logging.Level;
39 import java.util.logging.Logger;
41 import net.pterodactylus.fcp.highlevel.HighLevelClient;
42 import net.pterodactylus.fcp.highlevel.HighLevelClientListener;
43 import net.pterodactylus.fcp.highlevel.KeyGenerationResult;
44 import net.pterodactylus.util.io.Closer;
45 import net.pterodactylus.util.logging.Logging;
50 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
53 public class NodeManager implements Iterable<Node>, PropertyChangeListener, HighLevelClientListener {
56 private static final Logger logger = Logging.getLogger(NodeManager.class.getName());
58 /** The FCP client name. */
59 private final String clientName;
61 /** The directory for the configuration. */
62 private final String directory;
64 /** Object used for synchronization. */
65 private final Object syncObject = new Object();
67 /** Node listeners. */
68 private List<NodeListener> nodeListeners = Collections.synchronizedList(new ArrayList<NodeListener>());
71 private List<Node> nodes = Collections.synchronizedList(new ArrayList<Node>());
73 /** All FCP connections. */
74 private Map<Node, HighLevelClient> nodeClients = Collections.synchronizedMap(new HashMap<Node, HighLevelClient>());
76 /** Maps nodes to high-level clients. */
77 private Map<HighLevelClient, Node> clientNodes = Collections.synchronizedMap(new HashMap<HighLevelClient, Node>());
80 * Creates a new FCP collector.
83 * The name of the FCP client
85 * The directory in which to store the nodes
87 public NodeManager(String clientName, String directory) {
88 this.clientName = clientName;
89 this.directory = directory;
97 * Adds the given listener to the list of listeners.
100 * The listener to add
102 public void addNodeListener(NodeListener nodeListener) {
103 nodeListeners.add(nodeListener);
107 * Removes the given listener from the list of listeners.
109 * @param nodeListener
110 * The listener to remove
112 public void removeNodeListener(NodeListener nodeListener) {
113 nodeListeners.remove(nodeListener);
117 * Notifies all listeners that a node was added.
120 * The node that was added.
122 private void fireNodeAdded(Node node) {
123 for (NodeListener nodeListener: nodeListeners) {
124 nodeListener.nodeAdded(node);
129 * Notifies all listeners that a node was removed.
132 * The node that was removed
134 private void fireNodeRemoved(Node node) {
135 for (NodeListener nodeListener: nodeListeners) {
136 nodeListener.nodeRemoved(node);
141 * Notifies all listeners that the given node was connected.
144 * The node that is now connected
146 private void fireNodeConnected(Node node) {
147 for (NodeListener nodeListener: nodeListeners) {
148 nodeListener.nodeConnected(node);
153 * Notifies all listeners that a connection to a node has failed.
156 * The node that could not be connected
158 * The cause of the failure
160 private void fireNodeConnectionFailed(Node node, Throwable cause) {
161 for (NodeListener nodeListener: nodeListeners) {
162 nodeListener.nodeConnectionFailed(node, cause);
167 * Notifies all listeners that the given node was disconnected.
170 * The node that is now disconnected
172 * The exception that caused the disconnect, or <code>null</code>
173 * if there was no exception
175 private void fireNodeDisconnected(Node node, Throwable throwable) {
176 for (NodeListener nodeListener: nodeListeners) {
177 nodeListener.nodeDisconnected(node, throwable);
186 * Returns the directory in which the nodes are stored.
188 * @return The directory the nodes are stored in
190 public String getDirectory() {
195 * Checks whether the given node is already connected.
199 * @return <code>true</code> if the node is already connected,
200 * <code>false</code> otherwise
202 public boolean hasNode(Node node) {
203 return nodes.contains(node);
209 public Iterator<Node> iterator() {
210 return nodes.iterator();
220 * @throws IOException
221 * if an I/O error occurs loading the nodes
223 public void load() throws IOException {
224 File directoryFile = new File(directory);
225 File nodeFile = new File(directoryFile, "nodes.properties");
226 if (!nodeFile.exists() || !nodeFile.isFile() || !nodeFile.canRead()) {
229 Properties nodeProperties = new Properties();
230 InputStream nodeInputStream = null;
232 nodeInputStream = new FileInputStream(nodeFile);
233 nodeProperties.load(nodeInputStream);
235 Closer.close(nodeInputStream);
238 List<Node> loadedNodes = new ArrayList<Node>();
239 while (nodeProperties.containsKey("nodes." + ++nodeIndex + ".name")) {
240 String nodePrefix = "nodes." + nodeIndex;
241 String nodeName = nodeProperties.getProperty(nodePrefix + ".name");
242 if (!Verifier.verifyNodeName(nodeName)) {
243 logger.log(Level.WARNING, "invalid node name “" + nodeName + "”, skipping…");
246 String nodeHostname = nodeProperties.getProperty(nodePrefix + ".hostname");
247 if (!Verifier.verifyHostname(nodeHostname)) {
248 logger.log(Level.WARNING, "invalid host name “" + nodeHostname + "”");
249 /* not fatal, might be valid later on. */
251 String nodePortString = nodeProperties.getProperty(nodePrefix + ".port");
252 if (!Verifier.verifyPort(nodePortString)) {
253 logger.log(Level.WARNING, "invalid port number “" + nodePortString + "”, skipping…");
258 nodePort = Integer.valueOf(nodePortString);
259 } catch (NumberFormatException nfe1) {
260 /* shouldn't happen, port number was checked before. */
261 logger.log(Level.SEVERE, "invalid port number “" + nodePortString + "”, check failed! skipping…");
264 Node newNode = new Node();
265 newNode.setName(nodeName);
266 newNode.setHostname(nodeHostname);
267 newNode.setPort(nodePort);
268 loadedNodes.add(newNode);
270 logger.fine("loaded " + loadedNodes.size() + " nodes from config");
271 synchronized (syncObject) {
273 for (Node node: loadedNodes) {
280 * Saves all configured nodes.
282 * @throws IOException
283 * if an I/O error occurs saving the nodes
285 public void save() throws IOException {
286 File directoryFile = new File(directory);
287 if (!directoryFile.exists()) {
288 if (!directoryFile.mkdirs()) {
289 throw new IOException("could not create directory: " + directory);
292 Properties nodeProperties = new Properties();
294 for (Node node: nodes) {
295 String nodePrefix = "nodes." + ++nodeIndex;
296 nodeProperties.setProperty(nodePrefix + ".name", node.getName());
297 nodeProperties.setProperty(nodePrefix + ".hostname", node.getHostname());
298 nodeProperties.setProperty(nodePrefix + ".port", String.valueOf(node.getPort()));
300 File projectFile = new File(directoryFile, "nodes.properties");
301 OutputStream nodeOutputStream = null;
303 nodeOutputStream = new FileOutputStream(projectFile);
304 nodeProperties.store(nodeOutputStream, "jSite nodes");
306 Closer.close(nodeOutputStream);
311 * Adds the given node to this manager.
313 * @see #connect(Node)
315 * The node to connect to
316 * @return <code>true</code> if the node was added, <code>false</code>
317 * if the node was not added because it was already known
319 public boolean addNode(Node node) {
320 if (nodes.contains(node)) {
321 logger.warning("was told to add already known node: " + node);
324 node.addPropertyChangeListener(this);
325 HighLevelClient highLevelClient = new HighLevelClient(clientName);
327 clientNodes.put(highLevelClient, node);
328 nodeClients.put(node, highLevelClient);
329 highLevelClient.addHighLevelClientListener(this);
335 * Removes the given node from the node manager, disconnecting it if it is
336 * currently connected.
341 public void removeNode(Node node) {
342 synchronized (syncObject) {
343 if (!nodes.contains(node)) {
346 if (nodeClients.containsKey(node)) {
349 node.removePropertyChangeListener(this);
350 fireNodeRemoved(node);
355 * Tries to establish a connection with the given node.
358 * The node to connect to
360 public void connect(Node node) {
361 HighLevelClient highLevelClient;
362 highLevelClient = nodeClients.get(node);
363 if (highLevelClient == null) {
364 logger.warning("was told to connect to unknown node: " + node);
368 highLevelClient.connect(node.getHostname(), node.getPort());
369 } catch (UnknownHostException uhe1) {
370 fireNodeConnectionFailed(node, uhe1);
371 } catch (IOException ioe1) {
372 fireNodeConnectionFailed(node, ioe1);
377 * Disconnects the given node without removing it.
380 * The node to disconnect
382 public void disconnect(Node node) {
383 synchronized (syncObject) {
384 if (!nodes.contains(node)) {
387 HighLevelClient highLevelClient = nodeClients.get(node);
388 highLevelClient.disconnect();
393 * Returns a list of all nodes.
395 * @return A list of all nodes
397 public List<Node> getNodes() {
398 return Collections.unmodifiableList(nodes);
402 * Returns the high-level client for a given node.
405 * The node to get a high-level client for
406 * @return The high-level client for a node, or <code>null</code> if the
407 * node was disconnected or removed
409 public HighLevelClient getHighLevelClient(Node node) {
410 return nodeClients.get(node);
414 * Returns the node for a high-level client.
416 * @param highLevelClient
417 * The high-level client to get the node for
418 * @return The node for the high-level client, or <code>null</code> if the
419 * high-level client is not known
421 public Node getNode(HighLevelClient highLevelClient) {
422 return clientNodes.get(highLevelClient);
426 * Generates a new SSK key pair.
428 * @return An array with the private key at index <code>0</code> and the
429 * public key at index <code>1</code>
430 * @throws IOException
431 * if an I/O error occurs communicating with the node
432 * @throws NoNodeException
433 * if no node is configured
435 public String[] generateKeyPair() throws IOException, NoNodeException {
436 if (nodes.isEmpty()) {
437 throw new NoNodeException("no node configured");
439 Node node = nodes.get(0);
440 HighLevelClient highLevelClient = nodeClients.get(node);
442 KeyGenerationResult keyGenerationResult = highLevelClient.generateKey().getResult();
443 return new String[] { keyGenerationResult.getInsertURI(), keyGenerationResult.getRequestURI() };
444 } catch (InterruptedException e) {
455 // INTERFACE HighLevelClientListener
461 public void clientConnected(HighLevelClient highLevelClient) {
462 logger.log(Level.FINER, "clientConnected(c=" + highLevelClient + ")");
463 Node node = clientNodes.get(highLevelClient);
465 logger.log(Level.WARNING, "got event for unknown client");
468 fireNodeConnected(node);
474 public void clientDisconnected(HighLevelClient highLevelClient, Throwable throwable) {
475 logger.log(Level.FINER, "clientDisconnected(c=" + highLevelClient + ",t=" + throwable + ")");
476 synchronized (syncObject) {
477 Node node = clientNodes.get(highLevelClient);
479 logger.log(Level.WARNING, "got event for unknown client");
482 fireNodeDisconnected(node, throwable);
487 // INTERFACE PropertyChangeListener
493 public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
494 Object eventSource = propertyChangeEvent.getSource();
495 if (eventSource instanceof Node) {
496 String propertyName = propertyChangeEvent.getPropertyName();
497 if ("hostname".equals(propertyName) || "port".equals(propertyName)) {
498 Node node = (Node) eventSource;
499 HighLevelClient highLevelClient = nodeClients.get(node);
500 if (highLevelClient == null) {
501 logger.log(Level.WARNING, "got property change event for unknown node: " + node);
504 if (highLevelClient.isConnected()) {
505 highLevelClient.disconnect();
507 highLevelClient.connect(node.getHostname(), node.getPort());
508 } catch (UnknownHostException uhe1) {
509 fireNodeConnectionFailed(node, uhe1);
510 } catch (IOException ioe1) {
511 fireNodeConnectionFailed(node, ioe1);