a30218e2430b333163786a32bab170962203de20
[jFCPlib.git] / src / net / pterodactylus / fcp / highlevel / FcpClient.java
1 /*
2  * jFCPlib - FcpClient.java -
3  * Copyright © 2009 David Roden
4  *
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.
9  *
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.
14  *
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.
18  */
19
20 package net.pterodactylus.fcp.highlevel;
21
22 import java.io.IOException;
23 import java.net.InetAddress;
24 import java.net.URL;
25 import java.net.UnknownHostException;
26 import java.util.HashSet;
27 import java.util.Set;
28 import java.util.concurrent.CountDownLatch;
29
30 import net.pterodactylus.fcp.AddPeer;
31 import net.pterodactylus.fcp.ClientHello;
32 import net.pterodactylus.fcp.CloseConnectionDuplicateClientName;
33 import net.pterodactylus.fcp.EndListPeers;
34 import net.pterodactylus.fcp.FcpAdapter;
35 import net.pterodactylus.fcp.FcpConnection;
36 import net.pterodactylus.fcp.FcpListener;
37 import net.pterodactylus.fcp.ListPeerNotes;
38 import net.pterodactylus.fcp.ListPeers;
39 import net.pterodactylus.fcp.ModifyPeer;
40 import net.pterodactylus.fcp.NodeHello;
41 import net.pterodactylus.fcp.NodeRef;
42 import net.pterodactylus.fcp.Peer;
43 import net.pterodactylus.fcp.PeerNote;
44 import net.pterodactylus.fcp.PeerRemoved;
45 import net.pterodactylus.fcp.ProtocolError;
46 import net.pterodactylus.fcp.RemovePeer;
47 import net.pterodactylus.util.thread.ObjectWrapper;
48
49 /**
50  * High-level FCP client that hides the details of the underlying FCP
51  * implementation.
52  *
53  * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
54  */
55 public class FcpClient {
56
57         /** Object used for synchronization. */
58         private final Object syncObject = new Object();
59
60         /** The name of this client. */
61         private final String name;
62
63         /** The underlying FCP connection. */
64         private final FcpConnection fcpConnection;
65
66         /**
67          * Creates an FCP client with the given name.
68          *
69          * @param name
70          *            The name of the FCP client
71          * @throws UnknownHostException
72          *             if the hostname “localhost” is unknown
73          */
74         public FcpClient(String name) throws UnknownHostException {
75                 this(name, "localhost");
76         }
77
78         /**
79          * Creates an FCP client.
80          *
81          * @param name
82          *            The name of the FCP client
83          * @param hostname
84          *            The hostname of the Freenet node
85          * @throws UnknownHostException
86          *             if the given hostname can not be resolved
87          */
88         public FcpClient(String name, String hostname) throws UnknownHostException {
89                 this(name, hostname, FcpConnection.DEFAULT_PORT);
90         }
91
92         /**
93          * Creates an FCP client.
94          *
95          * @param name
96          *            The name of the FCP client
97          * @param hostname
98          *            The hostname of the Freenet node
99          * @param port
100          *            The Freenet node’s FCP port
101          * @throws UnknownHostException
102          *             if the given hostname can not be resolved
103          */
104         public FcpClient(String name, String hostname, int port) throws UnknownHostException {
105                 this(name, InetAddress.getByName(hostname), port);
106         }
107
108         /**
109          * Creates an FCP client.
110          *
111          * @param name
112          *            The name of the FCP client
113          * @param host
114          *            The host address of the Freenet node
115          */
116         public FcpClient(String name, InetAddress host) {
117                 this(name, host, FcpConnection.DEFAULT_PORT);
118         }
119
120         /**
121          * Creates an FCP client.
122          *
123          * @param name
124          *            The name of the FCP client
125          * @param host
126          *            The host address of the Freenet node
127          * @param port
128          *            The Freenet node’s FCP port
129          */
130         public FcpClient(String name, InetAddress host, int port) {
131                 this.name = name;
132                 fcpConnection = new FcpConnection(host, port);
133         }
134
135         //
136         // ACTIONS
137         //
138
139         /**
140          * Connects the FCP client.
141          *
142          * @throws IOException
143          *             if an I/O error occurs
144          * @throws FcpException
145          *             if an FCP error occurs
146          */
147         public void connect() throws IOException, FcpException {
148                 new ExtendedFcpAdapter() {
149
150                         /**
151                          * {@inheritDoc}
152                          */
153                         @Override
154                         @SuppressWarnings("synthetic-access")
155                         public void run() throws IOException {
156                                 fcpConnection.connect();
157                                 ClientHello clientHello = new ClientHello(name);
158                                 fcpConnection.sendMessage(clientHello);
159                         }
160
161                         /**
162                          * {@inheritDoc}
163                          */
164                         @Override
165                         public void receivedNodeHello(FcpConnection fcpConnection, NodeHello nodeHello) {
166                                 completionLatch.countDown();
167                         }
168                 }.execute();
169         }
170
171         /**
172          * Disconnects the FCP client.
173          */
174         public void disconnect() {
175                 synchronized (syncObject) {
176                         fcpConnection.close();
177                         syncObject.notifyAll();
178                 }
179         }
180
181         //
182         // PEER MANAGEMENT
183         //
184
185         /**
186          * Returns all peers that the node has.
187          *
188          * @param withMetadata
189          *            <code>true</code> to include peer metadata
190          * @param withVolatile
191          *            <code>true</code> to include volatile peer data
192          * @return A set containing the node’s peers
193          * @throws IOException
194          *             if an I/O error occurs
195          * @throws FcpException
196          *             if an FCP error occurs
197          */
198         public Set<Peer> getPeers(final boolean withMetadata, final boolean withVolatile) throws IOException, FcpException {
199                 final Set<Peer> peers = new HashSet<Peer>();
200                 new ExtendedFcpAdapter() {
201
202                         /**
203                          * {@inheritDoc}
204                          */
205                         @Override
206                         @SuppressWarnings("synthetic-access")
207                         public void run() throws IOException {
208                                 fcpConnection.sendMessage(new ListPeers("list-peers", withMetadata, withVolatile));
209                         }
210
211                         /**
212                          * {@inheritDoc}
213                          */
214                         @Override
215                         public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
216                                 peers.add(peer);
217                         }
218
219                         /**
220                          * {@inheritDoc}
221                          */
222                         @Override
223                         public void receivedEndListPeers(FcpConnection fcpConnection, EndListPeers endListPeers) {
224                                 completionLatch.countDown();
225                         }
226                 }.execute();
227                 return peers;
228         }
229
230         /**
231          * Adds the given peer to the node.
232          *
233          * @param peer
234          *            The peer to add
235          * @throws IOException
236          *             if an I/O error occurs
237          * @throws FcpException
238          *             if an FCP error occurs
239          */
240         public void addPeer(Peer peer) throws IOException, FcpException {
241                 addPeer(peer.getNodeRef());
242         }
243
244         /**
245          * Adds the peer defined by the noderef to the node.
246          *
247          * @param nodeRef
248          *            The noderef that defines the new peer
249          * @throws IOException
250          *             if an I/O error occurs
251          * @throws FcpException
252          *             if an FCP error occurs
253          */
254         public void addPeer(NodeRef nodeRef) throws IOException, FcpException {
255                 addPeer(new AddPeer(nodeRef));
256         }
257
258         /**
259          * Adds a peer, reading the noderef from the given URL.
260          *
261          * @param url
262          *            The URL to read the noderef from
263          * @throws IOException
264          *             if an I/O error occurs
265          * @throws FcpException
266          *             if an FCP error occurs
267          */
268         public void addPeer(URL url) throws IOException, FcpException {
269                 addPeer(new AddPeer(url));
270         }
271
272         /**
273          * Adds a peer, reading the noderef of the peer from the given file.
274          * <strong>Note:</strong> the file to read the noderef from has to reside on
275          * the same machine as the node!
276          *
277          * @param file
278          *            The name of the file containing the peer’s noderef
279          * @throws IOException
280          *             if an I/O error occurs
281          * @throws FcpException
282          *             if an FCP error occurs
283          */
284         public void addPeer(String file) throws IOException, FcpException {
285                 addPeer(new AddPeer(file));
286         }
287
288         /**
289          * Sends the given {@link AddPeer} message to the node. This method should
290          * not be called directly. Use one of {@link #addPeer(Peer)},
291          * {@link #addPeer(NodeRef)}, {@link #addPeer(URL)}, or
292          * {@link #addPeer(String)} instead.
293          *
294          * @param addPeer
295          *            The “AddPeer” message
296          * @throws IOException
297          *             if an I/O error occurs
298          * @throws FcpException
299          *             if an FCP error occurs
300          */
301         private void addPeer(final AddPeer addPeer) throws IOException, FcpException {
302                 new ExtendedFcpAdapter() {
303
304                         /**
305                          * {@inheritDoc}
306                          */
307                         @Override
308                         @SuppressWarnings("synthetic-access")
309                         public void run() throws IOException {
310                                 fcpConnection.sendMessage(addPeer);
311                         }
312
313                         /**
314                          * {@inheritDoc}
315                          */
316                         @Override
317                         public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
318                                 completionLatch.countDown();
319                         }
320                 }.execute();
321         }
322
323         /**
324          * Modifies the given peer.
325          *
326          * @param peer
327          *            The peer to modify
328          * @param allowLocalAddresses
329          *            <code>true</code> to allow local address, <code>false</code>
330          *            to not allow local address, <code>null</code> to not change
331          *            the setting
332          * @param disabled
333          *            <code>true</code> to disable the peer, <code>false</code> to
334          *            enable the peer, <code>null</code> to not change the setting
335          * @param listenOnly
336          *            <code>true</code> to enable “listen only” for the peer,
337          *            <code>false</code> to disable it, <code>null</code> to not
338          *            change it
339          * @throws IOException
340          *             if an I/O error occurs
341          * @throws FcpException
342          *             if an FCP error occurs
343          */
344         public void modifyPeer(final Peer peer, final Boolean allowLocalAddresses, final Boolean disabled, final Boolean listenOnly) throws IOException, FcpException {
345                 new ExtendedFcpAdapter() {
346
347                         /**
348                          * {@inheritDoc}
349                          */
350                         @Override
351                         @SuppressWarnings("synthetic-access")
352                         public void run() throws IOException {
353                                 fcpConnection.sendMessage(new ModifyPeer(peer.getIdentity(), allowLocalAddresses, disabled, listenOnly));
354                         }
355
356                         /**
357                          * {@inheritDoc}
358                          */
359                         @Override
360                         public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
361                                 completionLatch.countDown();
362                         }
363                 }.execute();
364         }
365
366         /**
367          * Removes the given peer.
368          *
369          * @param peer
370          *            The peer to remove
371          * @throws IOException
372          *             if an I/O error occurs
373          * @throws FcpException
374          *             if an FCP error occurs
375          */
376         public void removePeer(final Peer peer) throws IOException, FcpException {
377                 new ExtendedFcpAdapter() {
378
379                         /**
380                          * {@inheritDoc}
381                          */
382                         @Override
383                         @SuppressWarnings("synthetic-access")
384                         public void run() throws IOException {
385                                 fcpConnection.sendMessage(new RemovePeer(peer.getIdentity()));
386                         }
387
388                         /**
389                          * {@inheritDoc}
390                          */
391                         @Override
392                         public void receivedPeerRemoved(FcpConnection fcpConnection, PeerRemoved peerRemoved) {
393                                 completionLatch.countDown();
394                         }
395                 }.execute();
396         }
397
398         //
399         // PEER NOTES MANAGEMENT
400         //
401
402         /**
403          * Returns the peer note of the given peer.
404          *
405          * @param peer
406          *            The peer to get the note for
407          * @return The peer’s note
408          * @throws IOException
409          *             if an I/O error occurs
410          * @throws FcpException
411          *             if an FCP error occurs
412          */
413         public PeerNote getPeerNote(final Peer peer) throws IOException, FcpException {
414                 final ObjectWrapper<PeerNote> objectWrapper = new ObjectWrapper<PeerNote>();
415                 new ExtendedFcpAdapter() {
416
417                         /**
418                          * {@inheritDoc}
419                          */
420                         @Override
421                         @SuppressWarnings("synthetic-access")
422                         public void run() throws IOException {
423                                 fcpConnection.sendMessage(new ListPeerNotes(peer.getIdentity()));
424                         }
425
426                         /**
427                          * {@inheritDoc}
428                          */
429                         @Override
430                         public void receivedPeerNote(FcpConnection fcpConnection, PeerNote peerNote) {
431                                 objectWrapper.set(peerNote);
432                         }
433                 }.execute();
434                 return objectWrapper.get();
435         }
436
437         /**
438          * Implementation of an {@link FcpListener} that can store an
439          * {@link FcpException} and wait for the arrival of a certain command.
440          *
441          * @author David ‘Bombe’ Roden &lt;bombe@freenetproject.org&gt;
442          */
443         private abstract class ExtendedFcpAdapter extends FcpAdapter {
444
445                 /** The count down latch used to wait for completion. */
446                 protected final CountDownLatch completionLatch = new CountDownLatch(1);
447
448                 /** The FCP exception, if any. */
449                 protected FcpException fcpException;
450
451                 /**
452                  * Creates a new extended FCP adapter.
453                  */
454                 public ExtendedFcpAdapter() {
455                         /* do nothing. */
456                 }
457
458                 /**
459                  * Executes the FCP commands in {@link #run()}, wrapping the execution
460                  * and catching exceptions.
461                  *
462                  * @throws IOException
463                  *             if an I/O error occurs
464                  * @throws FcpException
465                  *             if an FCP error occurs
466                  */
467                 @SuppressWarnings("synthetic-access")
468                 public void execute() throws IOException, FcpException {
469                         fcpConnection.addFcpListener(this);
470                         try {
471                                 run();
472                                 while (true) {
473                                         try {
474                                                 completionLatch.await();
475                                                 break;
476                                         } catch (InterruptedException ie1) {
477                                                 /* ignore, we’ll loop. */
478                                         }
479                                 }
480                         } finally {
481                                 fcpConnection.removeFcpListener(this);
482                         }
483                         if (fcpException != null) {
484                                 throw fcpException;
485                         }
486                 }
487
488                 /**
489                  * The FCP commands that actually get executed.
490                  *
491                  * @throws IOException
492                  *             if an I/O error occurs
493                  */
494                 public abstract void run() throws IOException;
495
496                 /**
497                  * {@inheritDoc}
498                  */
499                 @Override
500                 public void connectionClosed(FcpConnection fcpConnection, Throwable throwable) {
501                         fcpException = new FcpException("Connection closed", throwable);
502                         completionLatch.countDown();
503                 }
504
505                 /**
506                  * {@inheritDoc}
507                  */
508                 @Override
509                 public void receivedCloseConnectionDuplicateClientName(FcpConnection fcpConnection, CloseConnectionDuplicateClientName closeConnectionDuplicateClientName) {
510                         fcpException = new FcpException("Connection closed, duplicate client name");
511                         completionLatch.countDown();
512                 }
513
514                 /**
515                  * {@inheritDoc}
516                  */
517                 @Override
518                 public void receivedProtocolError(FcpConnection fcpConnection, ProtocolError protocolError) {
519                         fcpException = new FcpException("Protocol error (" + protocolError.getCode() + ", " + protocolError.getCodeDescription());
520                         completionLatch.countDown();
521                 }
522
523         }
524
525 }