Remove “name” field, the name is only used when connecting.
[jFCPlib.git] / src / main / java / net / pterodactylus / fcp / highlevel / FcpClient.java
1 /*
2  * jFCPlib - FcpClient.java - Copyright © 2009 David Roden
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17  */
18
19 package net.pterodactylus.fcp.highlevel;
20
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.net.InetAddress;
24 import java.net.URL;
25 import java.net.UnknownHostException;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.Map;
31 import java.util.Set;
32 import java.util.Map.Entry;
33 import java.util.concurrent.CountDownLatch;
34
35 import net.pterodactylus.fcp.AddPeer;
36 import net.pterodactylus.fcp.ClientHello;
37 import net.pterodactylus.fcp.CloseConnectionDuplicateClientName;
38 import net.pterodactylus.fcp.DataFound;
39 import net.pterodactylus.fcp.EndListPeerNotes;
40 import net.pterodactylus.fcp.EndListPeers;
41 import net.pterodactylus.fcp.EndListPersistentRequests;
42 import net.pterodactylus.fcp.FCPPluginMessage;
43 import net.pterodactylus.fcp.FCPPluginReply;
44 import net.pterodactylus.fcp.FcpAdapter;
45 import net.pterodactylus.fcp.FcpConnection;
46 import net.pterodactylus.fcp.FcpListener;
47 import net.pterodactylus.fcp.GenerateSSK;
48 import net.pterodactylus.fcp.GetFailed;
49 import net.pterodactylus.fcp.GetNode;
50 import net.pterodactylus.fcp.ListPeerNotes;
51 import net.pterodactylus.fcp.ListPeers;
52 import net.pterodactylus.fcp.ListPersistentRequests;
53 import net.pterodactylus.fcp.ModifyPeer;
54 import net.pterodactylus.fcp.ModifyPeerNote;
55 import net.pterodactylus.fcp.NodeData;
56 import net.pterodactylus.fcp.NodeHello;
57 import net.pterodactylus.fcp.NodeRef;
58 import net.pterodactylus.fcp.Peer;
59 import net.pterodactylus.fcp.PeerNote;
60 import net.pterodactylus.fcp.PeerRemoved;
61 import net.pterodactylus.fcp.PersistentGet;
62 import net.pterodactylus.fcp.PersistentPut;
63 import net.pterodactylus.fcp.ProtocolError;
64 import net.pterodactylus.fcp.RemovePeer;
65 import net.pterodactylus.fcp.SSKKeypair;
66 import net.pterodactylus.fcp.SimpleProgress;
67 import net.pterodactylus.fcp.WatchGlobal;
68 import net.pterodactylus.util.filter.Filter;
69 import net.pterodactylus.util.filter.Filters;
70 import net.pterodactylus.util.thread.ObjectWrapper;
71
72 /**
73  * High-level FCP client that hides the details of the underlying FCP
74  * implementation.
75  *
76  * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
77  */
78 public class FcpClient {
79
80         /** Object used for synchronization. */
81         private final Object syncObject = new Object();
82
83         /** Listener management. */
84         private final FcpClientListenerManager fcpClientListenerManager = new FcpClientListenerManager(this);
85
86         /** The underlying FCP connection. */
87         private final FcpConnection fcpConnection;
88
89         /** The {@link NodeHello} data sent by the node on connection. */
90         private volatile NodeHello nodeHello;
91
92         /** Whether the client is currently connected. */
93         private volatile boolean connected;
94
95         /**
96          * Creates an FCP client with the given name.
97          *
98          * @throws UnknownHostException
99          *             if the hostname “localhost” is unknown
100          */
101         public FcpClient() throws UnknownHostException {
102                 this("localhost");
103         }
104
105         /**
106          * Creates an FCP client.
107          *
108          * @param hostname
109          *            The hostname of the Freenet node
110          * @throws UnknownHostException
111          *             if the given hostname can not be resolved
112          */
113         public FcpClient(String hostname) throws UnknownHostException {
114                 this(hostname, FcpConnection.DEFAULT_PORT);
115         }
116
117         /**
118          * Creates an FCP client.
119          *
120          * @param hostname
121          *            The hostname of the Freenet node
122          * @param port
123          *            The Freenet node’s FCP port
124          * @throws UnknownHostException
125          *             if the given hostname can not be resolved
126          */
127         public FcpClient(String hostname, int port) throws UnknownHostException {
128                 this(InetAddress.getByName(hostname), port);
129         }
130
131         /**
132          * Creates an FCP client.
133          *
134          * @param host
135          *            The host address of the Freenet node
136          */
137         public FcpClient(InetAddress host) {
138                 this(host, FcpConnection.DEFAULT_PORT);
139         }
140
141         /**
142          * Creates an FCP client.
143          *
144          * @param host
145          *            The host address of the Freenet node
146          * @param port
147          *            The Freenet node’s FCP port
148          */
149         public FcpClient(InetAddress host, int port) {
150                 fcpConnection = new FcpConnection(host, port);
151                 fcpConnection.addFcpListener(new FcpAdapter() {
152
153                         /**
154                          * {@inheritDoc}
155                          */
156                         @Override
157                         @SuppressWarnings("synthetic-access")
158                         public void connectionClosed(FcpConnection fcpConnection, Throwable throwable) {
159                                 connected = false;
160                                 fcpClientListenerManager.fireFcpClientDisconnected();
161                         }
162                 });
163         }
164
165         //
166         // LISTENER MANAGEMENT
167         //
168
169         /**
170          * Adds an FCP listener to the underlying connection.
171          *
172          * @param fcpListener
173          *            The FCP listener to add
174          */
175         public void addFcpListener(FcpListener fcpListener) {
176                 fcpConnection.addFcpListener(fcpListener);
177         }
178
179         /**
180          * Removes an FCP listener from the underlying connection.
181          *
182          * @param fcpListener
183          *            The FCP listener to remove
184          */
185         public void removeFcpListener(FcpListener fcpListener) {
186                 fcpConnection.removeFcpListener(fcpListener);
187         }
188
189         /**
190          * Adds an FCP client listener to the list of registered listeners.
191          *
192          * @param fcpClientListener
193          *            The FCP client listener to add
194          */
195         public void addFcpClientListener(FcpClientListener fcpClientListener) {
196                 fcpClientListenerManager.addListener(fcpClientListener);
197         }
198
199         /**
200          * Removes an FCP client listener from the list of registered listeners.
201          *
202          * @param fcpClientListener
203          *            The FCP client listener to remove
204          */
205         public void removeFcpClientListener(FcpClientListener fcpClientListener) {
206                 fcpClientListenerManager.removeListener(fcpClientListener);
207         }
208
209         //
210         // ACCESSORS
211         //
212
213         /**
214          * Returns the {@link NodeHello} object that the node returned when
215          * connecting.
216          *
217          * @return The {@code NodeHello} data container
218          */
219         public NodeHello getNodeHello() {
220                 return nodeHello;
221         }
222
223         /**
224          * Returns the underlying FCP connection.
225          *
226          * @return The underlying FCP connection
227          */
228         public FcpConnection getConnection() {
229                 return fcpConnection;
230         }
231
232         //
233         // ACTIONS
234         //
235
236         /**
237          * Connects the FCP client.
238          *
239          * @param name
240          *            The name of the client
241          * @throws IOException
242          *             if an I/O error occurs
243          * @throws FcpException
244          *             if an FCP error occurs
245          */
246         public void connect(final String name) throws IOException, FcpException {
247                 checkConnected(false);
248                 connected = true;
249                 new ExtendedFcpAdapter() {
250
251                         /**
252                          * {@inheritDoc}
253                          */
254                         @Override
255                         @SuppressWarnings("synthetic-access")
256                         public void run() throws IOException {
257                                 fcpConnection.connect();
258                                 ClientHello clientHello = new ClientHello(name);
259                                 fcpConnection.sendMessage(clientHello);
260                                 WatchGlobal watchGlobal = new WatchGlobal(true);
261                                 fcpConnection.sendMessage(watchGlobal);
262                         }
263
264                         /**
265                          * {@inheritDoc}
266                          */
267                         @Override
268                         @SuppressWarnings("synthetic-access")
269                         public void receivedNodeHello(FcpConnection fcpConnection, NodeHello nodeHello) {
270                                 FcpClient.this.nodeHello = nodeHello;
271                                 completionLatch.countDown();
272                         }
273                 }.execute();
274         }
275
276         /**
277          * Disconnects the FCP client.
278          */
279         public void disconnect() {
280                 synchronized (syncObject) {
281                         fcpConnection.close();
282                         syncObject.notifyAll();
283                 }
284         }
285
286         /**
287          * Returns whether this client is currently connected.
288          *
289          * @return {@code true} if the client is currently connected, {@code false}
290          *         otherwise
291          */
292         public boolean isConnected() {
293                 return connected;
294         }
295
296         //
297         // PEER MANAGEMENT
298         //
299
300         /**
301          * Returns all peers that the node has.
302          *
303          * @param withMetadata
304          *            <code>true</code> to include peer metadata
305          * @param withVolatile
306          *            <code>true</code> to include volatile peer data
307          * @return A set containing the node’s peers
308          * @throws IOException
309          *             if an I/O error occurs
310          * @throws FcpException
311          *             if an FCP error occurs
312          */
313         public Collection<Peer> getPeers(final boolean withMetadata, final boolean withVolatile) throws IOException, FcpException {
314                 final Set<Peer> peers = Collections.synchronizedSet(new HashSet<Peer>());
315                 new ExtendedFcpAdapter() {
316
317                         /** The ID of the “ListPeers” request. */
318                         @SuppressWarnings("synthetic-access")
319                         private String identifier = createIdentifier("list-peers");
320
321                         /**
322                          * {@inheritDoc}
323                          */
324                         @Override
325                         @SuppressWarnings("synthetic-access")
326                         public void run() throws IOException {
327                                 fcpConnection.sendMessage(new ListPeers(identifier, withMetadata, withVolatile));
328                         }
329
330                         /**
331                          * {@inheritDoc}
332                          */
333                         @Override
334                         public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
335                                 if (peer.getIdentifier().equals(identifier)) {
336                                         peers.add(peer);
337                                 }
338                         }
339
340                         /**
341                          * {@inheritDoc}
342                          */
343                         @Override
344                         public void receivedEndListPeers(FcpConnection fcpConnection, EndListPeers endListPeers) {
345                                 if (endListPeers.getIdentifier().equals(identifier)) {
346                                         completionLatch.countDown();
347                                 }
348                         }
349                 }.execute();
350                 return peers;
351         }
352
353         /**
354          * Returns all darknet peers.
355          *
356          * @param withMetadata
357          *            <code>true</code> to include peer metadata
358          * @param withVolatile
359          *            <code>true</code> to include volatile peer data
360          * @return A set containing the node’s darknet peers
361          * @throws IOException
362          *             if an I/O error occurs
363          * @throws FcpException
364          *             if an FCP error occurs
365          */
366         public Collection<Peer> getDarknetPeers(boolean withMetadata, boolean withVolatile) throws IOException, FcpException {
367                 Collection<Peer> allPeers = getPeers(withMetadata, withVolatile);
368                 Collection<Peer> darknetPeers = new HashSet<Peer>();
369                 for (Peer peer : allPeers) {
370                         if (!peer.isOpennet() && !peer.isSeed()) {
371                                 darknetPeers.add(peer);
372                         }
373                 }
374                 return darknetPeers;
375         }
376
377         /**
378          * Returns all opennet peers.
379          *
380          * @param withMetadata
381          *            <code>true</code> to include peer metadata
382          * @param withVolatile
383          *            <code>true</code> to include volatile peer data
384          * @return A set containing the node’s opennet peers
385          * @throws IOException
386          *             if an I/O error occurs
387          * @throws FcpException
388          *             if an FCP error occurs
389          */
390         public Collection<Peer> getOpennetPeers(boolean withMetadata, boolean withVolatile) throws IOException, FcpException {
391                 Collection<Peer> allPeers = getPeers(withMetadata, withVolatile);
392                 Collection<Peer> opennetPeers = new HashSet<Peer>();
393                 for (Peer peer : allPeers) {
394                         if (peer.isOpennet() && !peer.isSeed()) {
395                                 opennetPeers.add(peer);
396                         }
397                 }
398                 return opennetPeers;
399         }
400
401         /**
402          * Returns all seed peers.
403          *
404          * @param withMetadata
405          *            <code>true</code> to include peer metadata
406          * @param withVolatile
407          *            <code>true</code> to include volatile peer data
408          * @return A set containing the node’s seed peers
409          * @throws IOException
410          *             if an I/O error occurs
411          * @throws FcpException
412          *             if an FCP error occurs
413          */
414         public Collection<Peer> getSeedPeers(boolean withMetadata, boolean withVolatile) throws IOException, FcpException {
415                 Collection<Peer> allPeers = getPeers(withMetadata, withVolatile);
416                 Collection<Peer> seedPeers = new HashSet<Peer>();
417                 for (Peer peer : allPeers) {
418                         if (peer.isSeed()) {
419                                 seedPeers.add(peer);
420                         }
421                 }
422                 return seedPeers;
423         }
424
425         /**
426          * Adds the given peer to the node.
427          *
428          * @param peer
429          *            The peer to add
430          * @throws IOException
431          *             if an I/O error occurs
432          * @throws FcpException
433          *             if an FCP error occurs
434          */
435         public void addPeer(Peer peer) throws IOException, FcpException {
436                 addPeer(peer.getNodeRef());
437         }
438
439         /**
440          * Adds the peer defined by the noderef to the node.
441          *
442          * @param nodeRef
443          *            The noderef that defines the new peer
444          * @throws IOException
445          *             if an I/O error occurs
446          * @throws FcpException
447          *             if an FCP error occurs
448          */
449         public void addPeer(NodeRef nodeRef) throws IOException, FcpException {
450                 addPeer(new AddPeer(nodeRef));
451         }
452
453         /**
454          * Adds a peer, reading the noderef from the given URL.
455          *
456          * @param url
457          *            The URL to read the noderef from
458          * @throws IOException
459          *             if an I/O error occurs
460          * @throws FcpException
461          *             if an FCP error occurs
462          */
463         public void addPeer(URL url) throws IOException, FcpException {
464                 addPeer(new AddPeer(url));
465         }
466
467         /**
468          * Adds a peer, reading the noderef of the peer from the given file.
469          * <strong>Note:</strong> the file to read the noderef from has to reside on
470          * the same machine as the node!
471          *
472          * @param file
473          *            The name of the file containing the peer’s noderef
474          * @throws IOException
475          *             if an I/O error occurs
476          * @throws FcpException
477          *             if an FCP error occurs
478          */
479         public void addPeer(String file) throws IOException, FcpException {
480                 addPeer(new AddPeer(file));
481         }
482
483         /**
484          * Sends the given {@link AddPeer} message to the node. This method should
485          * not be called directly. Use one of {@link #addPeer(Peer)},
486          * {@link #addPeer(NodeRef)}, {@link #addPeer(URL)}, or
487          * {@link #addPeer(String)} instead.
488          *
489          * @param addPeer
490          *            The “AddPeer” message
491          * @throws IOException
492          *             if an I/O error occurs
493          * @throws FcpException
494          *             if an FCP error occurs
495          */
496         private void addPeer(final AddPeer addPeer) throws IOException, FcpException {
497                 new ExtendedFcpAdapter() {
498
499                         /**
500                          * {@inheritDoc}
501                          */
502                         @Override
503                         @SuppressWarnings("synthetic-access")
504                         public void run() throws IOException {
505                                 fcpConnection.sendMessage(addPeer);
506                         }
507
508                         /**
509                          * {@inheritDoc}
510                          */
511                         @Override
512                         public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
513                                 completionLatch.countDown();
514                         }
515                 }.execute();
516         }
517
518         /**
519          * Modifies the given peer.
520          *
521          * @param peer
522          *            The peer to modify
523          * @param allowLocalAddresses
524          *            <code>true</code> to allow local address, <code>false</code>
525          *            to not allow local address, <code>null</code> to not change
526          *            the setting
527          * @param disabled
528          *            <code>true</code> to disable the peer, <code>false</code> to
529          *            enable the peer, <code>null</code> to not change the setting
530          * @param listenOnly
531          *            <code>true</code> to enable “listen only” for the peer,
532          *            <code>false</code> to disable it, <code>null</code> to not
533          *            change it
534          * @throws IOException
535          *             if an I/O error occurs
536          * @throws FcpException
537          *             if an FCP error occurs
538          */
539         public void modifyPeer(final Peer peer, final Boolean allowLocalAddresses, final Boolean disabled, final Boolean listenOnly) throws IOException, FcpException {
540                 new ExtendedFcpAdapter() {
541
542                         /**
543                          * {@inheritDoc}
544                          */
545                         @Override
546                         @SuppressWarnings("synthetic-access")
547                         public void run() throws IOException {
548                                 fcpConnection.sendMessage(new ModifyPeer(peer.getIdentity(), allowLocalAddresses, disabled, listenOnly));
549                         }
550
551                         /**
552                          * {@inheritDoc}
553                          */
554                         @Override
555                         public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
556                                 completionLatch.countDown();
557                         }
558                 }.execute();
559         }
560
561         /**
562          * Removes the given peer.
563          *
564          * @param peer
565          *            The peer to remove
566          * @throws IOException
567          *             if an I/O error occurs
568          * @throws FcpException
569          *             if an FCP error occurs
570          */
571         public void removePeer(final Peer peer) throws IOException, FcpException {
572                 new ExtendedFcpAdapter() {
573
574                         /**
575                          * {@inheritDoc}
576                          */
577                         @Override
578                         @SuppressWarnings("synthetic-access")
579                         public void run() throws IOException {
580                                 fcpConnection.sendMessage(new RemovePeer(peer.getIdentity()));
581                         }
582
583                         /**
584                          * {@inheritDoc}
585                          */
586                         @Override
587                         public void receivedPeerRemoved(FcpConnection fcpConnection, PeerRemoved peerRemoved) {
588                                 completionLatch.countDown();
589                         }
590                 }.execute();
591         }
592
593         //
594         // PEER NOTES MANAGEMENT
595         //
596
597         /**
598          * Returns the peer note of the given peer.
599          *
600          * @param peer
601          *            The peer to get the note for
602          * @return The peer’s note
603          * @throws IOException
604          *             if an I/O error occurs
605          * @throws FcpException
606          *             if an FCP error occurs
607          */
608         public PeerNote getPeerNote(final Peer peer) throws IOException, FcpException {
609                 final ObjectWrapper<PeerNote> objectWrapper = new ObjectWrapper<PeerNote>();
610                 new ExtendedFcpAdapter() {
611
612                         /**
613                          * {@inheritDoc}
614                          */
615                         @Override
616                         @SuppressWarnings("synthetic-access")
617                         public void run() throws IOException {
618                                 fcpConnection.sendMessage(new ListPeerNotes(peer.getIdentity()));
619                         }
620
621                         /**
622                          * {@inheritDoc}
623                          */
624                         @Override
625                         public void receivedPeerNote(FcpConnection fcpConnection, PeerNote peerNote) {
626                                 if (peerNote.getNodeIdentifier().equals(peer.getIdentity())) {
627                                         objectWrapper.set(peerNote);
628                                 }
629                         }
630
631                         /**
632                          * {@inheritDoc}
633                          */
634                         @Override
635                         public void receivedEndListPeerNotes(FcpConnection fcpConnection, EndListPeerNotes endListPeerNotes) {
636                                 completionLatch.countDown();
637                         }
638                 }.execute();
639                 return objectWrapper.get();
640         }
641
642         /**
643          * Replaces the peer note for the given peer.
644          *
645          * @param peer
646          *            The peer
647          * @param noteText
648          *            The new base64-encoded note text
649          * @param noteType
650          *            The type of the note (currently only <code>1</code> is
651          *            allowed)
652          * @throws IOException
653          *             if an I/O error occurs
654          * @throws FcpException
655          *             if an FCP error occurs
656          */
657         public void modifyPeerNote(final Peer peer, final String noteText, final int noteType) throws IOException, FcpException {
658                 new ExtendedFcpAdapter() {
659
660                         /**
661                          * {@inheritDoc}
662                          */
663                         @Override
664                         @SuppressWarnings("synthetic-access")
665                         public void run() throws IOException {
666                                 fcpConnection.sendMessage(new ModifyPeerNote(peer.getIdentity(), noteText, noteType));
667                         }
668
669                         /**
670                          * {@inheritDoc}
671                          */
672                         @Override
673                         public void receivedPeer(FcpConnection fcpConnection, Peer receivedPeer) {
674                                 if (receivedPeer.getIdentity().equals(peer.getIdentity())) {
675                                         completionLatch.countDown();
676                                 }
677                         }
678                 }.execute();
679         }
680
681         //
682         // KEY GENERATION
683         //
684
685         /**
686          * Generates a new SSK key pair.
687          *
688          * @return The generated key pair
689          * @throws IOException
690          *             if an I/O error occurs
691          * @throws FcpException
692          *             if an FCP error occurs
693          */
694         public SSKKeypair generateKeyPair() throws IOException, FcpException {
695                 final ObjectWrapper<SSKKeypair> sskKeypairWrapper = new ObjectWrapper<SSKKeypair>();
696                 new ExtendedFcpAdapter() {
697
698                         /**
699                          * {@inheritDoc}
700                          */
701                         @Override
702                         @SuppressWarnings("synthetic-access")
703                         public void run() throws IOException {
704                                 fcpConnection.sendMessage(new GenerateSSK());
705                         }
706
707                         /**
708                          * {@inheritDoc}
709                          */
710                         @Override
711                         public void receivedSSKKeypair(FcpConnection fcpConnection, SSKKeypair sskKeypair) {
712                                 sskKeypairWrapper.set(sskKeypair);
713                                 completionLatch.countDown();
714                         }
715                 }.execute();
716                 return sskKeypairWrapper.get();
717         }
718
719         //
720         // REQUEST MANAGEMENT
721         //
722
723         /**
724          * Returns all currently visible persistent get requests.
725          *
726          * @param global
727          *            <code>true</code> to return get requests from the global
728          *            queue, <code>false</code> to only show requests from the
729          *            client-local queue
730          * @return All get requests
731          * @throws IOException
732          *             if an I/O error occurs
733          * @throws FcpException
734          *             if an FCP error occurs
735          */
736         public Collection<Request> getGetRequests(final boolean global) throws IOException, FcpException {
737                 return Filters.filteredCollection(getRequests(global), new Filter<Request>() {
738
739                         /**
740                          * {@inheritDoc}
741                          */
742                         public boolean filterObject(Request request) {
743                                 return request instanceof GetRequest;
744                         }
745                 });
746         }
747
748         /**
749          * Returns all currently visible persistent put requests.
750          *
751          * @param global
752          *            <code>true</code> to return put requests from the global
753          *            queue, <code>false</code> to only show requests from the
754          *            client-local queue
755          * @return All put requests
756          * @throws IOException
757          *             if an I/O error occurs
758          * @throws FcpException
759          *             if an FCP error occurs
760          */
761         public Collection<Request> getPutRequests(final boolean global) throws IOException, FcpException {
762                 return Filters.filteredCollection(getRequests(global), new Filter<Request>() {
763
764                         /**
765                          * {@inheritDoc}
766                          */
767                         public boolean filterObject(Request request) {
768                                 return request instanceof PutRequest;
769                         }
770                 });
771         }
772
773         /**
774          * Returns all currently visible persistent requests.
775          *
776          * @param global
777          *            <code>true</code> to return requests from the global queue,
778          *            <code>false</code> to only show requests from the client-local
779          *            queue
780          * @return All requests
781          * @throws IOException
782          *             if an I/O error occurs
783          * @throws FcpException
784          *             if an FCP error occurs
785          */
786         public Collection<Request> getRequests(final boolean global) throws IOException, FcpException {
787                 final Map<String, Request> requests = Collections.synchronizedMap(new HashMap<String, Request>());
788                 new ExtendedFcpAdapter() {
789
790                         /**
791                          * {@inheritDoc}
792                          */
793                         @Override
794                         @SuppressWarnings("synthetic-access")
795                         public void run() throws IOException {
796                                 fcpConnection.sendMessage(new ListPersistentRequests());
797                         }
798
799                         /**
800                          * {@inheritDoc}
801                          */
802                         @Override
803                         public void receivedPersistentGet(FcpConnection fcpConnection, PersistentGet persistentGet) {
804                                 if (!persistentGet.isGlobal() || global) {
805                                         GetRequest getRequest = new GetRequest(persistentGet);
806                                         requests.put(persistentGet.getIdentifier(), getRequest);
807                                 }
808                         }
809
810                         /**
811                          * {@inheritDoc}
812                          *
813                          * @see net.pterodactylus.fcp.FcpAdapter#receivedDataFound(net.pterodactylus.fcp.FcpConnection,
814                          *      net.pterodactylus.fcp.DataFound)
815                          */
816                         @Override
817                         public void receivedDataFound(FcpConnection fcpConnection, DataFound dataFound) {
818                                 Request getRequest = requests.get(dataFound.getIdentifier());
819                                 if (getRequest == null) {
820                                         return;
821                                 }
822                                 getRequest.setComplete(true);
823                                 getRequest.setLength(dataFound.getDataLength());
824                                 getRequest.setContentType(dataFound.getMetadataContentType());
825                         }
826
827                         /**
828                          * {@inheritDoc}
829                          *
830                          * @see net.pterodactylus.fcp.FcpAdapter#receivedGetFailed(net.pterodactylus.fcp.FcpConnection,
831                          *      net.pterodactylus.fcp.GetFailed)
832                          */
833                         @Override
834                         public void receivedGetFailed(FcpConnection fcpConnection, GetFailed getFailed) {
835                                 Request getRequest = requests.get(getFailed.getIdentifier());
836                                 if (getRequest == null) {
837                                         return;
838                                 }
839                                 getRequest.setComplete(true);
840                                 getRequest.setFailed(true);
841                                 getRequest.setFatal(getFailed.isFatal());
842                                 getRequest.setErrorCode(getFailed.getCode());
843                         }
844
845                         /**
846                          * {@inheritDoc}
847                          *
848                          * @see net.pterodactylus.fcp.FcpAdapter#receivedPersistentPut(net.pterodactylus.fcp.FcpConnection,
849                          *      net.pterodactylus.fcp.PersistentPut)
850                          */
851                         @Override
852                         public void receivedPersistentPut(FcpConnection fcpConnection, PersistentPut persistentPut) {
853                                 if (!persistentPut.isGlobal() || global) {
854                                         PutRequest putRequest = new PutRequest(persistentPut);
855                                         requests.put(persistentPut.getIdentifier(), putRequest);
856                                 }
857                         }
858
859                         /**
860                          * {@inheritDoc}
861                          *
862                          * @see net.pterodactylus.fcp.FcpAdapter#receivedSimpleProgress(net.pterodactylus.fcp.FcpConnection,
863                          *      net.pterodactylus.fcp.SimpleProgress)
864                          */
865                         @Override
866                         public void receivedSimpleProgress(FcpConnection fcpConnection, SimpleProgress simpleProgress) {
867                                 Request request = requests.get(simpleProgress.getIdentifier());
868                                 if (request == null) {
869                                         return;
870                                 }
871                                 request.setTotalBlocks(simpleProgress.getTotal());
872                                 request.setRequiredBlocks(simpleProgress.getRequired());
873                                 request.setFailedBlocks(simpleProgress.getFailed());
874                                 request.setFatallyFailedBlocks(simpleProgress.getFatallyFailed());
875                                 request.setSucceededBlocks(simpleProgress.getSucceeded());
876                                 request.setFinalizedTotal(simpleProgress.isFinalizedTotal());
877                         }
878
879                         /**
880                          * {@inheritDoc}
881                          */
882                         @Override
883                         public void receivedEndListPersistentRequests(FcpConnection fcpConnection, EndListPersistentRequests endListPersistentRequests) {
884                                 completionLatch.countDown();
885                         }
886                 }.execute();
887                 return requests.values();
888         }
889
890         /**
891          * Sends a message to a plugin and waits for the response.
892          *
893          * @param pluginClass
894          *            The name of the plugin class
895          * @param parameters
896          *            The parameters for the plugin
897          * @return The responses from the plugin
898          * @throws FcpException
899          *             if an FCP error occurs
900          * @throws IOException
901          *             if an I/O error occurs
902          */
903         public Map<String, String> sendPluginMessage(String pluginClass, Map<String, String> parameters) throws IOException, FcpException {
904                 return sendPluginMessage(pluginClass, parameters, 0, null);
905         }
906
907         /**
908          * Sends a message to a plugin and waits for the response.
909          *
910          * @param pluginClass
911          *            The name of the plugin class
912          * @param parameters
913          *            The parameters for the plugin
914          * @param dataLength
915          *            The length of the optional data stream, or {@code 0} if there
916          *            is no optional data stream
917          * @param dataInputStream
918          *            The input stream for the payload, or {@code null} if there is
919          *            no payload
920          * @return The responses from the plugin
921          * @throws FcpException
922          *             if an FCP error occurs
923          * @throws IOException
924          *             if an I/O error occurs
925          */
926         public Map<String, String> sendPluginMessage(final String pluginClass, final Map<String, String> parameters, final long dataLength, final InputStream dataInputStream) throws IOException, FcpException {
927                 final Map<String, String> pluginReplies = Collections.synchronizedMap(new HashMap<String, String>());
928                 new ExtendedFcpAdapter() {
929
930                         @SuppressWarnings("synthetic-access")
931                         private final String identifier = createIdentifier("FCPPluginMessage");
932
933                         @Override
934                         @SuppressWarnings("synthetic-access")
935                         public void run() throws IOException {
936                                 FCPPluginMessage fcpPluginMessage = new FCPPluginMessage(pluginClass);
937                                 for (Entry<String, String> parameter : parameters.entrySet()) {
938                                         fcpPluginMessage.setParameter(parameter.getKey(), parameter.getValue());
939                                 }
940                                 fcpPluginMessage.setIdentifier(identifier);
941                                 if ((dataLength > 0) && (dataInputStream != null)) {
942                                         fcpPluginMessage.setDataLength(dataLength);
943                                         fcpPluginMessage.setPayloadInputStream(dataInputStream);
944                                 }
945                                 fcpConnection.sendMessage(fcpPluginMessage);
946                         }
947
948                         /**
949                          * {@inheritDoc}
950                          */
951                         @Override
952                         public void receivedFCPPluginReply(FcpConnection fcpConnection, FCPPluginReply fcpPluginReply) {
953                                 if (!fcpPluginReply.getIdentifier().equals(identifier)) {
954                                         return;
955                                 }
956                                 pluginReplies.putAll(fcpPluginReply.getReplies());
957                                 completionLatch.countDown();
958                         }
959
960                 }.execute();
961                 return pluginReplies;
962         }
963
964         //
965         // NODE INFORMATION
966         //
967
968         /**
969          * Returns information about the node.
970          *
971          * @param giveOpennetRef
972          *            Whether to return the OpenNet reference
973          * @param withPrivate
974          *            Whether to return private node data
975          * @param withVolatile
976          *            Whether to return volatile node data
977          * @return Node information
978          * @throws FcpException
979          *             if an FCP error occurs
980          * @throws IOException
981          *             if an I/O error occurs
982          */
983         public NodeData getNodeInformation(final Boolean giveOpennetRef, final Boolean withPrivate, final Boolean withVolatile) throws IOException, FcpException {
984                 final ObjectWrapper<NodeData> nodeDataWrapper = new ObjectWrapper<NodeData>();
985                 new ExtendedFcpAdapter() {
986
987                         @Override
988                         @SuppressWarnings("synthetic-access")
989                         public void run() throws IOException {
990                                 GetNode getNodeMessage = new GetNode(giveOpennetRef, withPrivate, withVolatile);
991                                 fcpConnection.sendMessage(getNodeMessage);
992                         }
993
994                         /**
995                          * {@inheritDoc}
996                          */
997                         @Override
998                         public void receivedNodeData(FcpConnection fcpConnection, NodeData nodeData) {
999                                 nodeDataWrapper.set(nodeData);
1000                                 completionLatch.countDown();
1001                         }
1002                 }.execute();
1003                 return nodeDataWrapper.get();
1004         }
1005
1006         //
1007         // PRIVATE METHODS
1008         //
1009
1010         /**
1011          * Creates a unique request identifier.
1012          *
1013          * @param basename
1014          *            The basename of the request
1015          * @return The created request identifier
1016          */
1017         private String createIdentifier(String basename) {
1018                 return basename + "-" + System.currentTimeMillis() + "-" + (int) (Math.random() * Integer.MAX_VALUE);
1019         }
1020
1021         /**
1022          * Checks whether the connection is in the required state.
1023          *
1024          * @param connected
1025          *            The required connection state
1026          * @throws FcpException
1027          *             if the connection is not in the required state
1028          */
1029         private void checkConnected(boolean connected) throws FcpException {
1030                 if (this.connected != connected) {
1031                         throw new FcpException("Client is " + (connected ? "not" : "already") + " connected.");
1032                 }
1033         }
1034
1035         /**
1036          * Tells the client that it is now disconnected. This method is called by
1037          * {@link ExtendedFcpAdapter} only.
1038          */
1039         private void setDisconnected() {
1040                 connected = false;
1041         }
1042
1043         /**
1044          * Implementation of an {@link FcpListener} that can store an
1045          * {@link FcpException} and wait for the arrival of a certain command.
1046          *
1047          * @author David ‘Bombe’ Roden &lt;bombe@freenetproject.org&gt;
1048          */
1049         private abstract class ExtendedFcpAdapter extends FcpAdapter {
1050
1051                 /** The count down latch used to wait for completion. */
1052                 protected final CountDownLatch completionLatch = new CountDownLatch(1);
1053
1054                 /** The FCP exception, if any. */
1055                 protected FcpException fcpException;
1056
1057                 /**
1058                  * Creates a new extended FCP adapter.
1059                  */
1060                 public ExtendedFcpAdapter() {
1061                         /* do nothing. */
1062                 }
1063
1064                 /**
1065                  * Executes the FCP commands in {@link #run()}, wrapping the execution
1066                  * and catching exceptions.
1067                  *
1068                  * @throws IOException
1069                  *             if an I/O error occurs
1070                  * @throws FcpException
1071                  *             if an FCP error occurs
1072                  */
1073                 @SuppressWarnings("synthetic-access")
1074                 public void execute() throws IOException, FcpException {
1075                         checkConnected(true);
1076                         fcpConnection.addFcpListener(this);
1077                         try {
1078                                 run();
1079                                 while (true) {
1080                                         try {
1081                                                 completionLatch.await();
1082                                                 break;
1083                                         } catch (InterruptedException ie1) {
1084                                                 /* ignore, we’ll loop. */
1085                                         }
1086                                 }
1087                         } catch (IOException ioe1) {
1088                                 setDisconnected();
1089                                 throw ioe1;
1090                         } finally {
1091                                 fcpConnection.removeFcpListener(this);
1092                         }
1093                         if (fcpException != null) {
1094                                 setDisconnected();
1095                                 throw fcpException;
1096                         }
1097                 }
1098
1099                 /**
1100                  * The FCP commands that actually get executed.
1101                  *
1102                  * @throws IOException
1103                  *             if an I/O error occurs
1104                  */
1105                 public abstract void run() throws IOException;
1106
1107                 /**
1108                  * {@inheritDoc}
1109                  */
1110                 @Override
1111                 public void connectionClosed(FcpConnection fcpConnection, Throwable throwable) {
1112                         fcpException = new FcpException("Connection closed", throwable);
1113                         completionLatch.countDown();
1114                 }
1115
1116                 /**
1117                  * {@inheritDoc}
1118                  */
1119                 @Override
1120                 public void receivedCloseConnectionDuplicateClientName(FcpConnection fcpConnection, CloseConnectionDuplicateClientName closeConnectionDuplicateClientName) {
1121                         fcpException = new FcpException("Connection closed, duplicate client name");
1122                         completionLatch.countDown();
1123                 }
1124
1125                 /**
1126                  * {@inheritDoc}
1127                  */
1128                 @Override
1129                 public void receivedProtocolError(FcpConnection fcpConnection, ProtocolError protocolError) {
1130                         fcpException = new FcpException("Protocol error (" + protocolError.getCode() + ", " + protocolError.getCodeDescription());
1131                         completionLatch.countDown();
1132                 }
1133
1134         }
1135
1136 }