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.HighLevelException;
44 import net.pterodactylus.fcp.highlevel.KeyGenerationResult;
45 import net.pterodactylus.util.io.Closer;
46 import net.pterodactylus.util.logging.Logging;
51 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
54 public class NodeManager implements Iterable<Node>, PropertyChangeListener, HighLevelClientListener {
57 private static final Logger logger = Logging.getLogger(NodeManager.class.getName());
59 /** The FCP client name. */
60 private final String clientName;
62 /** The directory for the configuration. */
63 private final String directory;
65 /** Object used for synchronization. */
66 private final Object syncObject = new Object();
68 /** Node listeners. */
69 private List<NodeListener> nodeListeners = Collections.synchronizedList(new ArrayList<NodeListener>());
72 private List<Node> nodes = Collections.synchronizedList(new ArrayList<Node>());
74 /** All FCP connections. */
75 private Map<Node, HighLevelClient> nodeClients = Collections.synchronizedMap(new HashMap<Node, HighLevelClient>());
77 /** Maps nodes to high-level clients. */
78 private Map<HighLevelClient, Node> clientNodes = Collections.synchronizedMap(new HashMap<HighLevelClient, Node>());
81 * Creates a new FCP collector.
84 * The name of the FCP client
86 * The directory in which to store the nodes
88 public NodeManager(String clientName, String directory) {
89 this.clientName = clientName;
90 this.directory = directory;
98 * Adds the given listener to the list of listeners.
100 * @param nodeListener
101 * The listener to add
103 public void addNodeListener(NodeListener nodeListener) {
104 nodeListeners.add(nodeListener);
108 * Removes the given listener from the list of listeners.
110 * @param nodeListener
111 * The listener to remove
113 public void removeNodeListener(NodeListener nodeListener) {
114 nodeListeners.remove(nodeListener);
118 * Notifies all listeners that a node was added.
121 * The node that was added.
123 private void fireNodeAdded(Node node) {
124 for (NodeListener nodeListener: nodeListeners) {
125 nodeListener.nodeAdded(node);
130 * Notifies all listeners that a node was removed.
133 * The node that was removed
135 private void fireNodeRemoved(Node node) {
136 for (NodeListener nodeListener: nodeListeners) {
137 nodeListener.nodeRemoved(node);
142 * Notifies all listeners that the given node was connected.
145 * The node that is now connected
147 private void fireNodeConnected(Node node) {
148 for (NodeListener nodeListener: nodeListeners) {
149 nodeListener.nodeConnected(node);
154 * Notifies all listeners that a connection to a node has failed.
157 * The node that could not be connected
159 * The cause of the failure
161 private void fireNodeConnectionFailed(Node node, Throwable cause) {
162 for (NodeListener nodeListener: nodeListeners) {
163 nodeListener.nodeConnectionFailed(node, cause);
168 * Notifies all listeners that the given node was disconnected.
171 * The node that is now disconnected
173 * The exception that caused the disconnect, or <code>null</code>
174 * if there was no exception
176 private void fireNodeDisconnected(Node node, Throwable throwable) {
177 for (NodeListener nodeListener: nodeListeners) {
178 nodeListener.nodeDisconnected(node, throwable);
187 * Returns the directory in which the nodes are stored.
189 * @return The directory the nodes are stored in
191 public String getDirectory() {
196 * Checks whether the given node is already connected.
200 * @return <code>true</code> if the node is already connected,
201 * <code>false</code> otherwise
203 public boolean hasNode(Node node) {
204 return nodes.contains(node);
210 public Iterator<Node> iterator() {
211 return nodes.iterator();
221 * @throws IOException
222 * if an I/O error occurs loading the nodes
224 public void load() throws IOException {
225 File directoryFile = new File(directory);
226 File nodeFile = new File(directoryFile, "nodes.properties");
227 if (!nodeFile.exists() || !nodeFile.isFile() || !nodeFile.canRead()) {
230 Properties nodeProperties = new Properties();
231 InputStream nodeInputStream = null;
233 nodeInputStream = new FileInputStream(nodeFile);
234 nodeProperties.load(nodeInputStream);
236 Closer.close(nodeInputStream);
239 List<Node> loadedNodes = new ArrayList<Node>();
240 while (nodeProperties.containsKey("nodes." + ++nodeIndex + ".name")) {
241 String nodePrefix = "nodes." + nodeIndex;
242 String nodeName = nodeProperties.getProperty(nodePrefix + ".name");
243 if (!Verifier.verifyNodeName(nodeName)) {
244 logger.log(Level.WARNING, "invalid node name “" + nodeName + "”, skipping…");
247 String nodeHostname = nodeProperties.getProperty(nodePrefix + ".hostname");
248 if (!Verifier.verifyHostname(nodeHostname)) {
249 logger.log(Level.WARNING, "invalid host name “" + nodeHostname + "”");
250 /* not fatal, might be valid later on. */
252 String nodePortString = nodeProperties.getProperty(nodePrefix + ".port");
253 if (!Verifier.verifyPort(nodePortString)) {
254 logger.log(Level.WARNING, "invalid port number “" + nodePortString + "”, skipping…");
259 nodePort = Integer.valueOf(nodePortString);
260 } catch (NumberFormatException nfe1) {
261 /* shouldn't happen, port number was checked before. */
262 logger.log(Level.SEVERE, "invalid port number “" + nodePortString + "”, check failed! skipping…");
265 Node newNode = new Node();
266 newNode.setName(nodeName);
267 newNode.setHostname(nodeHostname);
268 newNode.setPort(nodePort);
269 loadedNodes.add(newNode);
271 logger.fine("loaded " + loadedNodes.size() + " nodes from config");
272 synchronized (syncObject) {
274 for (Node node: loadedNodes) {
281 * Saves all configured nodes.
283 * @throws IOException
284 * if an I/O error occurs saving the nodes
286 public void save() throws IOException {
287 File directoryFile = new File(directory);
288 if (!directoryFile.exists()) {
289 if (!directoryFile.mkdirs()) {
290 throw new IOException("could not create directory: " + directory);
293 Properties nodeProperties = new Properties();
295 for (Node node: nodes) {
296 String nodePrefix = "nodes." + ++nodeIndex;
297 nodeProperties.setProperty(nodePrefix + ".name", node.getName());
298 nodeProperties.setProperty(nodePrefix + ".hostname", node.getHostname());
299 nodeProperties.setProperty(nodePrefix + ".port", String.valueOf(node.getPort()));
301 File projectFile = new File(directoryFile, "nodes.properties");
302 OutputStream nodeOutputStream = null;
304 nodeOutputStream = new FileOutputStream(projectFile);
305 nodeProperties.store(nodeOutputStream, "jSite nodes");
307 Closer.close(nodeOutputStream);
312 * Adds the given node to this manager.
314 * @see #connect(Node)
316 * The node to connect to
317 * @return <code>true</code> if the node was added, <code>false</code>
318 * if the node was not added because it was already known
320 public boolean addNode(Node node) {
321 if (nodes.contains(node)) {
322 logger.warning("was told to add already known node: " + node);
325 node.addPropertyChangeListener(this);
326 HighLevelClient highLevelClient = new HighLevelClient(clientName);
328 clientNodes.put(highLevelClient, node);
329 nodeClients.put(node, highLevelClient);
330 highLevelClient.addHighLevelClientListener(this);
336 * Removes the given node from the node manager, disconnecting it if it is
337 * currently connected.
342 public void removeNode(Node node) {
343 synchronized (syncObject) {
344 if (!nodes.contains(node)) {
347 if (nodeClients.containsKey(node)) {
350 node.removePropertyChangeListener(this);
351 fireNodeRemoved(node);
356 * Tries to establish a connection with the given node.
359 * The node to connect to
361 public void connect(Node node) {
362 HighLevelClient highLevelClient;
363 highLevelClient = nodeClients.get(node);
364 if (highLevelClient == null) {
365 logger.warning("was told to connect to unknown node: " + node);
369 highLevelClient.connect(node.getHostname(), node.getPort());
370 } catch (UnknownHostException uhe1) {
371 fireNodeConnectionFailed(node, uhe1);
372 } catch (IOException ioe1) {
373 fireNodeConnectionFailed(node, ioe1);
378 * Disconnects the given node without removing it.
381 * The node to disconnect
383 public void disconnect(Node node) {
384 synchronized (syncObject) {
385 if (!nodes.contains(node)) {
388 HighLevelClient highLevelClient = nodeClients.get(node);
389 highLevelClient.disconnect();
394 * Returns a list of all nodes.
396 * @return A list of all nodes
398 public List<Node> getNodes() {
399 return Collections.unmodifiableList(nodes);
403 * Returns the high-level client for a given node.
406 * The node to get a high-level client for
407 * @return The high-level client for a node, or <code>null</code> if the
408 * node was disconnected or removed
410 public HighLevelClient getHighLevelClient(Node node) {
411 return nodeClients.get(node);
415 * Returns the node for a high-level client.
417 * @param highLevelClient
418 * The high-level client to get the node for
419 * @return The node for the high-level client, or <code>null</code> if the
420 * high-level client is not known
422 public Node getNode(HighLevelClient highLevelClient) {
423 return clientNodes.get(highLevelClient);
427 * Generates a new SSK key pair.
429 * @return An array with the private key at index <code>0</code> and the
430 * public key at index <code>1</code>
431 * @throws IOException
432 * if an I/O error occurs communicating with the node
433 * @throws JSiteException
434 * if there is a problem with the node
436 public String[] generateKeyPair() throws IOException, JSiteException {
437 if (nodes.isEmpty()) {
438 throw new NoNodeException("no node configured");
440 Node node = nodes.get(0);
441 HighLevelClient highLevelClient = nodeClients.get(node);
443 KeyGenerationResult keyGenerationResult = highLevelClient.generateKey().getResult();
444 return new String[] { keyGenerationResult.getInsertURI(), keyGenerationResult.getRequestURI() };
445 } catch (HighLevelException hle1) {
446 throw new BackendException(hle1);
447 } catch (InterruptedException e) {
458 // INTERFACE HighLevelClientListener
464 public void clientConnected(HighLevelClient highLevelClient) {
465 logger.log(Level.FINER, "clientConnected(c=" + highLevelClient + ")");
466 Node node = clientNodes.get(highLevelClient);
468 logger.log(Level.WARNING, "got event for unknown client");
471 fireNodeConnected(node);
477 public void clientDisconnected(HighLevelClient highLevelClient, Throwable throwable) {
478 logger.log(Level.FINER, "clientDisconnected(c=" + highLevelClient + ",t=" + throwable + ")");
479 synchronized (syncObject) {
480 Node node = clientNodes.get(highLevelClient);
482 logger.log(Level.WARNING, "got event for unknown client");
485 fireNodeDisconnected(node, throwable);
490 // INTERFACE PropertyChangeListener
496 public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
497 Object eventSource = propertyChangeEvent.getSource();
498 if (eventSource instanceof Node) {
499 String propertyName = propertyChangeEvent.getPropertyName();
500 if ("hostname".equals(propertyName) || "port".equals(propertyName)) {
501 Node node = (Node) eventSource;
502 HighLevelClient highLevelClient = nodeClients.get(node);
503 if (highLevelClient == null) {
504 logger.log(Level.WARNING, "got property change event for unknown node: " + node);
507 if (highLevelClient.isConnected()) {
508 highLevelClient.disconnect();
510 highLevelClient.connect(node.getHostname(), node.getPort());
511 } catch (UnknownHostException uhe1) {
512 fireNodeConnectionFailed(node, uhe1);
513 } catch (IOException ioe1) {
514 fireNodeConnectionFailed(node, ioe1);