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