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