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.HashSet;
35 import java.util.Iterator;
36 import java.util.List;
38 import java.util.Properties;
40 import java.util.logging.Level;
41 import java.util.logging.Logger;
43 import net.pterodactylus.fcp.highlevel.FcpClient;
44 import net.pterodactylus.fcp.highlevel.FcpException;
45 import net.pterodactylus.jsite.util.IdGenerator;
46 import net.pterodactylus.util.io.Closer;
47 import net.pterodactylus.util.logging.Logging;
48 import net.pterodactylus.util.number.Hex;
53 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
55 public class NodeManager implements Iterable<Node>, PropertyChangeListener {
58 private static final Logger logger = Logging.getLogger(NodeManager.class.getName());
60 /** The FCP client name. */
61 private final String clientName;
63 /** The directory for the configuration. */
64 private final String directory;
66 /** Object used for synchronization. */
67 private final Object syncObject = new Object();
69 /** Node listener support. */
70 private final NodeListenerSupport nodeListenerSupport = new NodeListenerSupport();
73 private final List<Node> nodes = Collections.synchronizedList(new ArrayList<Node>());
75 /** Map from node ID to node. */
76 private final Map<String, Node> idNodes = Collections.synchronizedMap(new HashMap<String, Node>());
78 /** Map from node to client. */
79 private final Map<Node, FcpClient> nodeClients = Collections.synchronizedMap(new HashMap<Node, FcpClient>());
81 /** Collection of currently connected nodes. */
82 private final Set<Node> connectedNodes = Collections.synchronizedSet(new HashSet<Node>());
85 * Creates a new FCP collector.
88 * The name of the FCP client
90 * The directory in which to store the nodes
92 public NodeManager(String clientName, String directory) {
93 this.clientName = clientName;
94 this.directory = directory;
102 * Adds the given listener to the list of listeners.
104 * @param nodeListener
105 * The listener to add
107 public void addNodeListener(NodeListener nodeListener) {
108 nodeListenerSupport.addListener(nodeListener);
112 * Removes the given listener from the list of listeners.
114 * @param nodeListener
115 * The listener to remove
117 public void removeNodeListener(NodeListener nodeListener) {
118 nodeListenerSupport.removeListener(nodeListener);
126 * Returns the directory in which the nodes are stored.
128 * @return The directory the nodes are stored in
130 public String getDirectory() {
135 * Checks whether the given node is already connected.
139 * @return <code>true</code> if the node is already connected,
140 * <code>false</code> otherwise
142 public boolean hasNode(Node node) {
143 return nodes.contains(node);
147 * Returns whether the given node is currently connected.
151 * @return <code>true</code> if the node is currently connected,
152 * <code>false</code> otherwise
154 public boolean isNodeConnected(Node node) {
155 return connectedNodes.contains(node);
161 public Iterator<Node> iterator() {
162 return nodes.iterator();
172 * @throws IOException
173 * if an I/O error occurs loading the nodes
175 public void load() throws IOException {
176 logger.log(Level.FINEST, "load()");
177 File directoryFile = new File(directory);
178 File nodeFile = new File(directoryFile, "nodes.properties");
179 if (!nodeFile.exists() || !nodeFile.isFile() || !nodeFile.canRead()) {
182 Properties nodeProperties = new Properties();
183 InputStream nodeInputStream = null;
185 nodeInputStream = new FileInputStream(nodeFile);
186 nodeProperties.load(nodeInputStream);
188 Closer.close(nodeInputStream);
191 List<Node> loadedNodes = new ArrayList<Node>();
192 while (nodeProperties.containsKey("nodes." + ++nodeIndex + ".name")) {
193 String nodePrefix = "nodes." + nodeIndex;
194 String nodeId = nodeProperties.getProperty(nodePrefix + ".id");
195 if (nodeId == null) {
196 nodeId = Hex.toHex(IdGenerator.generateId());
198 String nodeName = nodeProperties.getProperty(nodePrefix + ".name");
199 if (!Verifier.verifyNodeName(nodeName)) {
200 logger.log(Level.WARNING, "invalid node name “" + nodeName + "”, skipping…");
203 String nodeHostname = nodeProperties.getProperty(nodePrefix + ".hostname");
204 if (!Verifier.verifyHostname(nodeHostname)) {
205 logger.log(Level.WARNING, "invalid host name “" + nodeHostname + "”");
206 /* not fatal, might be valid later on. */
208 String nodePortString = nodeProperties.getProperty(nodePrefix + ".port");
209 if (!Verifier.verifyPort(nodePortString)) {
210 logger.log(Level.WARNING, "invalid port number “" + nodePortString + "”, skipping…");
215 nodePort = Integer.valueOf(nodePortString);
216 } catch (NumberFormatException nfe1) {
217 /* shouldn't happen, port number was checked before. */
218 logger.log(Level.SEVERE, "invalid port number “" + nodePortString + "”, check failed! skipping…");
221 Node newNode = new Node();
222 newNode.setId(nodeId);
223 newNode.setName(nodeName);
224 newNode.setHostname(nodeHostname);
225 newNode.setPort(nodePort);
226 loadedNodes.add(newNode);
228 logger.log(Level.FINE, "loaded " + loadedNodes.size() + " nodes from config");
229 synchronized (syncObject) {
231 for (Node node : loadedNodes) {
238 * Saves all configured nodes.
240 * @throws IOException
241 * if an I/O error occurs saving the nodes
243 public void save() throws IOException {
244 logger.log(Level.FINEST, "save()");
245 File directoryFile = new File(directory);
246 if (!directoryFile.exists()) {
247 if (!directoryFile.mkdirs()) {
248 throw new IOException("could not create directory: " + directory);
251 Properties nodeProperties = new Properties();
253 for (Node node : nodes) {
254 String nodePrefix = "nodes." + ++nodeIndex;
255 nodeProperties.setProperty(nodePrefix + ".id", node.getId());
256 nodeProperties.setProperty(nodePrefix + ".name", node.getName());
257 nodeProperties.setProperty(nodePrefix + ".hostname", node.getHostname());
258 nodeProperties.setProperty(nodePrefix + ".port", String.valueOf(node.getPort()));
260 File projectFile = new File(directoryFile, "nodes.properties");
261 OutputStream nodeOutputStream = null;
263 nodeOutputStream = new FileOutputStream(projectFile);
264 nodeProperties.store(nodeOutputStream, "jSite nodes");
266 Closer.close(nodeOutputStream);
271 * Adds the given node to this manager.
273 * @see #connect(Node)
275 * The node to connect to
276 * @return <code>true</code> if the node was added, <code>false</code> if
277 * the node was not added because it was already known
279 public boolean addNode(Node node) {
280 logger.log(Level.FINEST, "addNode(node=" + node + ")");
281 if (nodes.contains(node)) {
282 logger.log(Level.WARNING, "was told to add already known node: " + node);
285 node.addPropertyChangeListener(this);
287 idNodes.put(node.getId(), node);
288 nodeListenerSupport.fireNodeAdded(node);
293 * Removes the given node from the node manager, disconnecting it if it is
294 * currently connected.
299 public void removeNode(Node node) {
300 logger.log(Level.FINEST, "removeNode(node=" + node + ")");
301 synchronized (syncObject) {
302 if (!nodes.contains(node)) {
306 idNodes.remove(node.getId());
307 node.removePropertyChangeListener(this);
308 nodeListenerSupport.fireNodeRemoved(node);
313 * Tries to establish a connection with the given node.
316 * The node to connect to
318 public void connect(Node node) {
319 logger.log(Level.FINEST, "connect(node=" + node + ")");
320 if (!nodes.contains(node)) {
321 logger.log(Level.WARNING, "Was told to connect to node (" + node + ") I don’t know about!");
325 FcpClient fcpClient = new FcpClient(clientName, node.getHostname(), node.getPort());
327 } catch (UnknownHostException uhe1) {
328 nodeListenerSupport.fireNodeConnectionFailed(node, uhe1);
329 } catch (IOException ioe1) {
330 nodeListenerSupport.fireNodeConnectionFailed(node, ioe1);
331 } catch (FcpException fe1) {
332 nodeListenerSupport.fireNodeConnectionFailed(node, fe1);
337 * Disconnects the given node without removing it.
340 * The node to disconnect
342 public void disconnect(Node node) {
343 logger.log(Level.FINEST, "disconnect(node=" + node + ")");
347 * Returns a list of all nodes.
349 * @return A list of all nodes
351 public List<Node> getNodes() {
352 return Collections.unmodifiableList(nodes);
356 * Returns the node identified by the given ID.
360 * @return The node with the given ID, or <code>null</code> if no such node
363 Node getNode(String id) {
364 return idNodes.get(id);
368 * Generates a new SSK key pair.
370 * @return An array with the private key at index <code>0</code> and the
371 * public key at index <code>1</code>
372 * @throws IOException
373 * if an I/O error occurs communicating with the node
374 * @throws JSiteException
375 * if there is a problem with the node
377 public String[] generateKeyPair() throws IOException, JSiteException {
378 logger.log(Level.FINEST, "generateKeyPair()");
379 if (nodes.isEmpty()) {
380 throw new NoNodeException("no node configured");
390 // INTERFACE PropertyChangeListener
396 public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
397 Object eventSource = propertyChangeEvent.getSource();
398 if (eventSource instanceof Node) {
399 String propertyName = propertyChangeEvent.getPropertyName();
400 if ("hostname".equals(propertyName) || "port".equals(propertyName)) {
401 /* TODO - reconnect. */