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