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