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