Change method of getting persistent get requests that does not change the “WatchGloba...
[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.EndListPersistentRequests;
37 import net.pterodactylus.fcp.FcpAdapter;
38 import net.pterodactylus.fcp.FcpConnection;
39 import net.pterodactylus.fcp.FcpListener;
40 import net.pterodactylus.fcp.GenerateSSK;
41 import net.pterodactylus.fcp.ListPeerNotes;
42 import net.pterodactylus.fcp.ListPeers;
43 import net.pterodactylus.fcp.ListPersistentRequests;
44 import net.pterodactylus.fcp.ModifyPeer;
45 import net.pterodactylus.fcp.ModifyPeerNote;
46 import net.pterodactylus.fcp.NodeHello;
47 import net.pterodactylus.fcp.NodeRef;
48 import net.pterodactylus.fcp.Peer;
49 import net.pterodactylus.fcp.PeerNote;
50 import net.pterodactylus.fcp.PeerRemoved;
51 import net.pterodactylus.fcp.PersistentGet;
52 import net.pterodactylus.fcp.ProtocolError;
53 import net.pterodactylus.fcp.RemovePeer;
54 import net.pterodactylus.fcp.SSKKeypair;
55 import net.pterodactylus.util.thread.ObjectWrapper;
56
57 /**
58  * High-level FCP client that hides the details of the underlying FCP
59  * implementation.
60  *
61  * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
62  */
63 public class FcpClient {
64
65         /** Object used for synchronization. */
66         private final Object syncObject = new Object();
67
68         /** The name of this client. */
69         private final String name;
70
71         /** The underlying FCP connection. */
72         private final FcpConnection fcpConnection;
73
74         /**
75          * Creates an FCP client with the given name.
76          *
77          * @param name
78          *            The name of the FCP client
79          * @throws UnknownHostException
80          *             if the hostname “localhost” is unknown
81          */
82         public FcpClient(String name) throws UnknownHostException {
83                 this(name, "localhost");
84         }
85
86         /**
87          * Creates an FCP client.
88          *
89          * @param name
90          *            The name of the FCP client
91          * @param hostname
92          *            The hostname of the Freenet node
93          * @throws UnknownHostException
94          *             if the given hostname can not be resolved
95          */
96         public FcpClient(String name, String hostname) throws UnknownHostException {
97                 this(name, hostname, FcpConnection.DEFAULT_PORT);
98         }
99
100         /**
101          * Creates an FCP client.
102          *
103          * @param name
104          *            The name of the FCP client
105          * @param hostname
106          *            The hostname of the Freenet node
107          * @param port
108          *            The Freenet node’s FCP port
109          * @throws UnknownHostException
110          *             if the given hostname can not be resolved
111          */
112         public FcpClient(String name, String hostname, int port) throws UnknownHostException {
113                 this(name, InetAddress.getByName(hostname), port);
114         }
115
116         /**
117          * Creates an FCP client.
118          *
119          * @param name
120          *            The name of the FCP client
121          * @param host
122          *            The host address of the Freenet node
123          */
124         public FcpClient(String name, InetAddress host) {
125                 this(name, host, FcpConnection.DEFAULT_PORT);
126         }
127
128         /**
129          * Creates an FCP client.
130          *
131          * @param name
132          *            The name of the FCP client
133          * @param host
134          *            The host address of the Freenet node
135          * @param port
136          *            The Freenet node’s FCP port
137          */
138         public FcpClient(String name, InetAddress host, int port) {
139                 this.name = name;
140                 fcpConnection = new FcpConnection(host, port);
141         }
142
143         //
144         // ACTIONS
145         //
146
147         /**
148          * Connects the FCP client.
149          *
150          * @throws IOException
151          *             if an I/O error occurs
152          * @throws FcpException
153          *             if an FCP error occurs
154          */
155         public void connect() throws IOException, FcpException {
156                 new ExtendedFcpAdapter() {
157
158                         /**
159                          * {@inheritDoc}
160                          */
161                         @Override
162                         @SuppressWarnings("synthetic-access")
163                         public void run() throws IOException {
164                                 fcpConnection.connect();
165                                 ClientHello clientHello = new ClientHello(name);
166                                 fcpConnection.sendMessage(clientHello);
167                         }
168
169                         /**
170                          * {@inheritDoc}
171                          */
172                         @Override
173                         public void receivedNodeHello(FcpConnection fcpConnection, NodeHello nodeHello) {
174                                 completionLatch.countDown();
175                         }
176                 }.execute();
177         }
178
179         /**
180          * Disconnects the FCP client.
181          */
182         public void disconnect() {
183                 synchronized (syncObject) {
184                         fcpConnection.close();
185                         syncObject.notifyAll();
186                 }
187         }
188
189         //
190         // PEER MANAGEMENT
191         //
192
193         /**
194          * Returns all peers that the node has.
195          *
196          * @param withMetadata
197          *            <code>true</code> to include peer metadata
198          * @param withVolatile
199          *            <code>true</code> to include volatile peer data
200          * @return A set containing the node’s peers
201          * @throws IOException
202          *             if an I/O error occurs
203          * @throws FcpException
204          *             if an FCP error occurs
205          */
206         public Set<Peer> getPeers(final boolean withMetadata, final boolean withVolatile) throws IOException, FcpException {
207                 final Set<Peer> peers = Collections.synchronizedSet(new HashSet<Peer>());
208                 new ExtendedFcpAdapter() {
209
210                         /** The ID of the “ListPeers” request. */
211                         @SuppressWarnings("synthetic-access")
212                         private String identifier = createIdentifier("list-peers");
213
214                         /**
215                          * {@inheritDoc}
216                          */
217                         @Override
218                         @SuppressWarnings("synthetic-access")
219                         public void run() throws IOException {
220                                 fcpConnection.sendMessage(new ListPeers(identifier, withMetadata, withVolatile));
221                         }
222
223                         /**
224                          * {@inheritDoc}
225                          */
226                         @Override
227                         public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
228                                 if (peer.getIdentifier().equals(identifier)) {
229                                         peers.add(peer);
230                                 }
231                         }
232
233                         /**
234                          * {@inheritDoc}
235                          */
236                         @Override
237                         public void receivedEndListPeers(FcpConnection fcpConnection, EndListPeers endListPeers) {
238                                 if (endListPeers.getIdentifier().equals(identifier)) {
239                                         completionLatch.countDown();
240                                 }
241                         }
242                 }.execute();
243                 return peers;
244         }
245
246         /**
247          * Adds the given peer to the node.
248          *
249          * @param peer
250          *            The peer to add
251          * @throws IOException
252          *             if an I/O error occurs
253          * @throws FcpException
254          *             if an FCP error occurs
255          */
256         public void addPeer(Peer peer) throws IOException, FcpException {
257                 addPeer(peer.getNodeRef());
258         }
259
260         /**
261          * Adds the peer defined by the noderef to the node.
262          *
263          * @param nodeRef
264          *            The noderef that defines the new peer
265          * @throws IOException
266          *             if an I/O error occurs
267          * @throws FcpException
268          *             if an FCP error occurs
269          */
270         public void addPeer(NodeRef nodeRef) throws IOException, FcpException {
271                 addPeer(new AddPeer(nodeRef));
272         }
273
274         /**
275          * Adds a peer, reading the noderef from the given URL.
276          *
277          * @param url
278          *            The URL to read the noderef from
279          * @throws IOException
280          *             if an I/O error occurs
281          * @throws FcpException
282          *             if an FCP error occurs
283          */
284         public void addPeer(URL url) throws IOException, FcpException {
285                 addPeer(new AddPeer(url));
286         }
287
288         /**
289          * Adds a peer, reading the noderef of the peer from the given file.
290          * <strong>Note:</strong> the file to read the noderef from has to reside on
291          * the same machine as the node!
292          *
293          * @param file
294          *            The name of the file containing the peer’s noderef
295          * @throws IOException
296          *             if an I/O error occurs
297          * @throws FcpException
298          *             if an FCP error occurs
299          */
300         public void addPeer(String file) throws IOException, FcpException {
301                 addPeer(new AddPeer(file));
302         }
303
304         /**
305          * Sends the given {@link AddPeer} message to the node. This method should
306          * not be called directly. Use one of {@link #addPeer(Peer)},
307          * {@link #addPeer(NodeRef)}, {@link #addPeer(URL)}, or
308          * {@link #addPeer(String)} instead.
309          *
310          * @param addPeer
311          *            The “AddPeer” message
312          * @throws IOException
313          *             if an I/O error occurs
314          * @throws FcpException
315          *             if an FCP error occurs
316          */
317         private void addPeer(final AddPeer addPeer) throws IOException, FcpException {
318                 new ExtendedFcpAdapter() {
319
320                         /**
321                          * {@inheritDoc}
322                          */
323                         @Override
324                         @SuppressWarnings("synthetic-access")
325                         public void run() throws IOException {
326                                 fcpConnection.sendMessage(addPeer);
327                         }
328
329                         /**
330                          * {@inheritDoc}
331                          */
332                         @Override
333                         public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
334                                 completionLatch.countDown();
335                         }
336                 }.execute();
337         }
338
339         /**
340          * Modifies the given peer.
341          *
342          * @param peer
343          *            The peer to modify
344          * @param allowLocalAddresses
345          *            <code>true</code> to allow local address, <code>false</code>
346          *            to not allow local address, <code>null</code> to not change
347          *            the setting
348          * @param disabled
349          *            <code>true</code> to disable the peer, <code>false</code> to
350          *            enable the peer, <code>null</code> to not change the setting
351          * @param listenOnly
352          *            <code>true</code> to enable “listen only” for the peer,
353          *            <code>false</code> to disable it, <code>null</code> to not
354          *            change it
355          * @throws IOException
356          *             if an I/O error occurs
357          * @throws FcpException
358          *             if an FCP error occurs
359          */
360         public void modifyPeer(final Peer peer, final Boolean allowLocalAddresses, final Boolean disabled, final Boolean listenOnly) throws IOException, FcpException {
361                 new ExtendedFcpAdapter() {
362
363                         /**
364                          * {@inheritDoc}
365                          */
366                         @Override
367                         @SuppressWarnings("synthetic-access")
368                         public void run() throws IOException {
369                                 fcpConnection.sendMessage(new ModifyPeer(peer.getIdentity(), allowLocalAddresses, disabled, listenOnly));
370                         }
371
372                         /**
373                          * {@inheritDoc}
374                          */
375                         @Override
376                         public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
377                                 completionLatch.countDown();
378                         }
379                 }.execute();
380         }
381
382         /**
383          * Removes the given peer.
384          *
385          * @param peer
386          *            The peer to remove
387          * @throws IOException
388          *             if an I/O error occurs
389          * @throws FcpException
390          *             if an FCP error occurs
391          */
392         public void removePeer(final Peer peer) throws IOException, FcpException {
393                 new ExtendedFcpAdapter() {
394
395                         /**
396                          * {@inheritDoc}
397                          */
398                         @Override
399                         @SuppressWarnings("synthetic-access")
400                         public void run() throws IOException {
401                                 fcpConnection.sendMessage(new RemovePeer(peer.getIdentity()));
402                         }
403
404                         /**
405                          * {@inheritDoc}
406                          */
407                         @Override
408                         public void receivedPeerRemoved(FcpConnection fcpConnection, PeerRemoved peerRemoved) {
409                                 completionLatch.countDown();
410                         }
411                 }.execute();
412         }
413
414         //
415         // PEER NOTES MANAGEMENT
416         //
417
418         /**
419          * Returns the peer note of the given peer.
420          *
421          * @param peer
422          *            The peer to get the note for
423          * @return The peer’s note
424          * @throws IOException
425          *             if an I/O error occurs
426          * @throws FcpException
427          *             if an FCP error occurs
428          */
429         public PeerNote getPeerNote(final Peer peer) throws IOException, FcpException {
430                 final ObjectWrapper<PeerNote> objectWrapper = new ObjectWrapper<PeerNote>();
431                 new ExtendedFcpAdapter() {
432
433                         /**
434                          * {@inheritDoc}
435                          */
436                         @Override
437                         @SuppressWarnings("synthetic-access")
438                         public void run() throws IOException {
439                                 fcpConnection.sendMessage(new ListPeerNotes(peer.getIdentity()));
440                         }
441
442                         /**
443                          * {@inheritDoc}
444                          */
445                         @Override
446                         public void receivedPeerNote(FcpConnection fcpConnection, PeerNote peerNote) {
447                                 if (peerNote.getNodeIdentifier().equals(peer.getIdentity())) {
448                                         objectWrapper.set(peerNote);
449                                 }
450                         }
451
452                         /**
453                          * {@inheritDoc}
454                          */
455                         @Override
456                         public void receivedEndListPeerNotes(FcpConnection fcpConnection, EndListPeerNotes endListPeerNotes) {
457                                 completionLatch.countDown();
458                         }
459                 }.execute();
460                 return objectWrapper.get();
461         }
462
463         /**
464          * Replaces the peer note for the given peer.
465          *
466          * @param peer
467          *            The peer
468          * @param noteText
469          *            The new base64-encoded note text
470          * @param noteType
471          *            The type of the note (currently only <code>1</code> is
472          *            allowed)
473          * @throws IOException
474          *             if an I/O error occurs
475          * @throws FcpException
476          *             if an FCP error occurs
477          */
478         public void modifyPeerNote(final Peer peer, final String noteText, final int noteType) throws IOException, FcpException {
479                 new ExtendedFcpAdapter() {
480
481                         /**
482                          * {@inheritDoc}
483                          */
484                         @Override
485                         @SuppressWarnings("synthetic-access")
486                         public void run() throws IOException {
487                                 fcpConnection.sendMessage(new ModifyPeerNote(peer.getIdentity(), noteText, noteType));
488                         }
489
490                         /**
491                          * {@inheritDoc}
492                          */
493                         @Override
494                         public void receivedPeer(FcpConnection fcpConnection, Peer receivedPeer) {
495                                 if (receivedPeer.getIdentity().equals(peer.getIdentity())) {
496                                         completionLatch.countDown();
497                                 }
498                         }
499                 }.execute();
500         }
501
502         //
503         // KEY GENERATION
504         //
505
506         /**
507          * Generates a new SSK key pair.
508          *
509          * @return The generated key pair
510          * @throws IOException
511          *             if an I/O error occurs
512          * @throws FcpException
513          *             if an FCP error occurs
514          */
515         public SSKKeypair generateKeyPair() throws IOException, FcpException {
516                 final ObjectWrapper<SSKKeypair> sskKeypairWrapper = new ObjectWrapper<SSKKeypair>();
517                 new ExtendedFcpAdapter() {
518
519                         /**
520                          * {@inheritDoc}
521                          */
522                         @Override
523                         @SuppressWarnings("synthetic-access")
524                         public void run() throws IOException {
525                                 fcpConnection.sendMessage(new GenerateSSK());
526                         }
527
528                         /**
529                          * {@inheritDoc}
530                          */
531                         @Override
532                         public void receivedSSKKeypair(FcpConnection fcpConnection, SSKKeypair sskKeypair) {
533                                 sskKeypairWrapper.set(sskKeypair);
534                                 completionLatch.countDown();
535                         }
536                 }.execute();
537                 return sskKeypairWrapper.get();
538         }
539
540         //
541         // REQUEST MANAGEMENT
542         //
543
544         /**
545          * Returns all currently visible persistent get requests.
546          *
547          * @param global
548          *            <code>true</code> to return get requests from the global
549          *            queue, <code>false</code> to only show requests from the
550          *            client-local queue
551          * @return All get requests
552          * @throws IOException
553          *             if an I/O error occurs
554          * @throws FcpException
555          *             if an FCP error occurs
556          */
557         public Set<PersistentGet> getGetRequests(final boolean global) throws IOException, FcpException {
558                 final Set<PersistentGet> getRequests = Collections.synchronizedSet(new HashSet<PersistentGet>());
559                 new ExtendedFcpAdapter() {
560
561                         /**
562                          * {@inheritDoc}
563                          */
564                         @Override
565                         @SuppressWarnings("synthetic-access")
566                         public void run() throws IOException {
567                                 fcpConnection.sendMessage(new ListPersistentRequests());
568                         }
569
570                         /**
571                          * {@inheritDoc}
572                          */
573                         @Override
574                         public void receivedPersistentGet(FcpConnection fcpConnection, PersistentGet persistentGet) {
575                                 if (!persistentGet.isGlobal() || global) {
576                                         getRequests.add(persistentGet);
577                                 }
578                         }
579
580                         /**
581                          * {@inheritDoc}
582                          */
583                         @Override
584                         public void receivedEndListPersistentRequests(FcpConnection fcpConnection, EndListPersistentRequests endListPersistentRequests) {
585                                 completionLatch.countDown();
586                         }
587                 }.execute();
588                 return getRequests;
589         }
590
591         //
592         // PRIVATE METHODS
593         //
594
595         /**
596          * Creates a unique request identifier.
597          *
598          * @param basename
599          *            The basename of the request
600          * @return The created request identifier
601          */
602         private String createIdentifier(String basename) {
603                 return basename + "-" + System.currentTimeMillis() + "-" + (int) (Math.random() * Integer.MAX_VALUE);
604         }
605
606         /**
607          * Implementation of an {@link FcpListener} that can store an
608          * {@link FcpException} and wait for the arrival of a certain command.
609          *
610          * @author David ‘Bombe’ Roden &lt;bombe@freenetproject.org&gt;
611          */
612         private abstract class ExtendedFcpAdapter extends FcpAdapter {
613
614                 /** The count down latch used to wait for completion. */
615                 protected final CountDownLatch completionLatch = new CountDownLatch(1);
616
617                 /** The FCP exception, if any. */
618                 protected FcpException fcpException;
619
620                 /**
621                  * Creates a new extended FCP adapter.
622                  */
623                 public ExtendedFcpAdapter() {
624                         /* do nothing. */
625                 }
626
627                 /**
628                  * Executes the FCP commands in {@link #run()}, wrapping the execution
629                  * and catching exceptions.
630                  *
631                  * @throws IOException
632                  *             if an I/O error occurs
633                  * @throws FcpException
634                  *             if an FCP error occurs
635                  */
636                 @SuppressWarnings("synthetic-access")
637                 public void execute() throws IOException, FcpException {
638                         fcpConnection.addFcpListener(this);
639                         try {
640                                 run();
641                                 while (true) {
642                                         try {
643                                                 completionLatch.await();
644                                                 break;
645                                         } catch (InterruptedException ie1) {
646                                                 /* ignore, we’ll loop. */
647                                         }
648                                 }
649                         } finally {
650                                 fcpConnection.removeFcpListener(this);
651                         }
652                         if (fcpException != null) {
653                                 throw fcpException;
654                         }
655                 }
656
657                 /**
658                  * The FCP commands that actually get executed.
659                  *
660                  * @throws IOException
661                  *             if an I/O error occurs
662                  */
663                 public abstract void run() throws IOException;
664
665                 /**
666                  * {@inheritDoc}
667                  */
668                 @Override
669                 public void connectionClosed(FcpConnection fcpConnection, Throwable throwable) {
670                         fcpException = new FcpException("Connection closed", throwable);
671                         completionLatch.countDown();
672                 }
673
674                 /**
675                  * {@inheritDoc}
676                  */
677                 @Override
678                 public void receivedCloseConnectionDuplicateClientName(FcpConnection fcpConnection, CloseConnectionDuplicateClientName closeConnectionDuplicateClientName) {
679                         fcpException = new FcpException("Connection closed, duplicate client name");
680                         completionLatch.countDown();
681                 }
682
683                 /**
684                  * {@inheritDoc}
685                  */
686                 @Override
687                 public void receivedProtocolError(FcpConnection fcpConnection, ProtocolError protocolError) {
688                         fcpException = new FcpException("Protocol error (" + protocolError.getCode() + ", " + protocolError.getCodeDescription());
689                         completionLatch.countDown();
690                 }
691
692         }
693
694 }