2 * jFCPlib - FcpClient.java - Copyright © 2009 David Roden
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.
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.
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.
19 package net.pterodactylus.fcp.highlevel;
21 import static com.google.common.collect.FluentIterable.from;
23 import java.io.Closeable;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.net.InetAddress;
28 import java.net.UnknownHostException;
29 import java.util.Collection;
30 import java.util.Collections;
31 import java.util.HashMap;
32 import java.util.HashSet;
34 import java.util.Map.Entry;
36 import java.util.concurrent.CountDownLatch;
37 import java.util.concurrent.atomic.AtomicReference;
39 import net.pterodactylus.fcp.AddPeer;
40 import net.pterodactylus.fcp.AllData;
41 import net.pterodactylus.fcp.ClientGet;
42 import net.pterodactylus.fcp.ClientHello;
43 import net.pterodactylus.fcp.CloseConnectionDuplicateClientName;
44 import net.pterodactylus.fcp.DataFound;
45 import net.pterodactylus.fcp.EndListPeerNotes;
46 import net.pterodactylus.fcp.EndListPeers;
47 import net.pterodactylus.fcp.EndListPersistentRequests;
48 import net.pterodactylus.fcp.FCPPluginMessage;
49 import net.pterodactylus.fcp.FCPPluginReply;
50 import net.pterodactylus.fcp.FcpAdapter;
51 import net.pterodactylus.fcp.FcpConnection;
52 import net.pterodactylus.fcp.FcpListener;
53 import net.pterodactylus.fcp.GenerateSSK;
54 import net.pterodactylus.fcp.GetFailed;
55 import net.pterodactylus.fcp.GetNode;
56 import net.pterodactylus.fcp.ListPeerNotes;
57 import net.pterodactylus.fcp.ListPeers;
58 import net.pterodactylus.fcp.ListPersistentRequests;
59 import net.pterodactylus.fcp.ModifyPeer;
60 import net.pterodactylus.fcp.ModifyPeerNote;
61 import net.pterodactylus.fcp.NodeData;
62 import net.pterodactylus.fcp.NodeHello;
63 import net.pterodactylus.fcp.NodeRef;
64 import net.pterodactylus.fcp.Peer;
65 import net.pterodactylus.fcp.PeerNote;
66 import net.pterodactylus.fcp.PeerRemoved;
67 import net.pterodactylus.fcp.PersistentGet;
68 import net.pterodactylus.fcp.PersistentPut;
69 import net.pterodactylus.fcp.ProtocolError;
70 import net.pterodactylus.fcp.RemovePeer;
71 import net.pterodactylus.fcp.SSKKeypair;
72 import net.pterodactylus.fcp.SimpleProgress;
73 import net.pterodactylus.fcp.WatchGlobal;
75 import com.google.common.base.Predicate;
78 * High-level FCP client that hides the details of the underlying FCP
81 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
83 public class FcpClient implements Closeable {
85 /** Object used for synchronization. */
86 private final Object syncObject = new Object();
88 /** Listener management. */
89 private final FcpClientListenerManager fcpClientListenerManager = new FcpClientListenerManager(this);
91 /** The underlying FCP connection. */
92 private final FcpConnection fcpConnection;
94 /** The {@link NodeHello} data sent by the node on connection. */
95 private volatile NodeHello nodeHello;
97 /** Whether the client is currently connected. */
98 private volatile boolean connected;
100 /** The listener for “connection closed” events. */
101 private FcpListener connectionClosedListener;
104 * Creates an FCP client with the given name.
106 * @throws UnknownHostException
107 * if the hostname “localhost” is unknown
109 public FcpClient() throws UnknownHostException {
114 * Creates an FCP client.
117 * The hostname of the Freenet node
118 * @throws UnknownHostException
119 * if the given hostname can not be resolved
121 public FcpClient(String hostname) throws UnknownHostException {
122 this(hostname, FcpConnection.DEFAULT_PORT);
126 * Creates an FCP client.
129 * The hostname of the Freenet node
131 * The Freenet node’s FCP port
132 * @throws UnknownHostException
133 * if the given hostname can not be resolved
135 public FcpClient(String hostname, int port) throws UnknownHostException {
136 this(InetAddress.getByName(hostname), port);
140 * Creates an FCP client.
143 * The host address of the Freenet node
145 public FcpClient(InetAddress host) {
146 this(host, FcpConnection.DEFAULT_PORT);
150 * Creates an FCP client.
153 * The host address of the Freenet node
155 * The Freenet node’s FCP port
157 public FcpClient(InetAddress host, int port) {
158 this(new FcpConnection(host, port), false);
162 * Creates a new high-level FCP client that will use the given connection.
163 * This constructor will assume that the FCP connection is already
166 * @param fcpConnection
167 * The FCP connection to use
169 public FcpClient(FcpConnection fcpConnection) {
170 this(fcpConnection, true);
174 * Creates a new high-level FCP client that will use the given connection.
176 * @param fcpConnection
177 * The FCP connection to use
179 * The initial status of the FCP connection
181 public FcpClient(FcpConnection fcpConnection, boolean connected) {
182 this.fcpConnection = fcpConnection;
183 this.connected = connected;
184 connectionClosedListener = new FcpAdapter() {
190 @SuppressWarnings("synthetic-access")
191 public void connectionClosed(FcpConnection fcpConnection, Throwable throwable) {
192 FcpClient.this.connected = false;
193 fcpClientListenerManager.fireFcpClientDisconnected();
196 fcpConnection.addFcpListener(connectionClosedListener);
200 // LISTENER MANAGEMENT
204 * Adds an FCP listener to the underlying connection.
207 * The FCP listener to add
209 public void addFcpListener(FcpListener fcpListener) {
210 fcpConnection.addFcpListener(fcpListener);
214 * Removes an FCP listener from the underlying connection.
217 * The FCP listener to remove
219 public void removeFcpListener(FcpListener fcpListener) {
220 fcpConnection.removeFcpListener(fcpListener);
224 * Adds an FCP client listener to the list of registered listeners.
226 * @param fcpClientListener
227 * The FCP client listener to add
229 public void addFcpClientListener(FcpClientListener fcpClientListener) {
230 fcpClientListenerManager.addListener(fcpClientListener);
234 * Removes an FCP client listener from the list of registered listeners.
236 * @param fcpClientListener
237 * The FCP client listener to remove
239 public void removeFcpClientListener(FcpClientListener fcpClientListener) {
240 fcpClientListenerManager.removeListener(fcpClientListener);
248 * Returns the {@link NodeHello} object that the node returned when
251 * @return The {@code NodeHello} data container
253 public NodeHello getNodeHello() {
258 * Returns the underlying FCP connection.
260 * @return The underlying FCP connection
262 public FcpConnection getConnection() {
263 return fcpConnection;
271 * Connects the FCP client.
274 * The name of the client
275 * @throws IOException
276 * if an I/O error occurs
277 * @throws FcpException
278 * if an FCP error occurs
280 public void connect(final String name) throws IOException, FcpException {
281 checkConnected(false);
283 new ExtendedFcpAdapter() {
289 @SuppressWarnings("synthetic-access")
290 public void run() throws IOException {
291 fcpConnection.connect();
292 ClientHello clientHello = new ClientHello(name);
293 fcpConnection.sendMessage(clientHello);
294 WatchGlobal watchGlobal = new WatchGlobal(true);
295 fcpConnection.sendMessage(watchGlobal);
302 @SuppressWarnings("synthetic-access")
303 public void receivedNodeHello(FcpConnection fcpConnection, NodeHello nodeHello) {
304 FcpClient.this.nodeHello = nodeHello;
305 completionLatch.countDown();
311 * Returns the file with the given URI. The retrieved data will be run
312 * through Freenet’s content filter.
316 * @return The result of the get request
317 * @throws IOException
318 * if an I/O error occurs
319 * @throws FcpException
320 * if an FCP error occurs
322 public GetResult getURI(final String uri) throws IOException, FcpException {
323 return getURI(uri, true);
327 * Returns the file with the given URI.
332 * {@code true} to filter the retrieved data, {@code false}
334 * @return The result of the get request
335 * @throws IOException
336 * if an I/O error occurs
337 * @throws FcpException
338 * if an FCP error occurs
340 public GetResult getURI(final String uri, final boolean filterData) throws IOException, FcpException {
341 checkConnected(true);
342 final GetResult getResult = new GetResult();
343 new ExtendedFcpAdapter() {
345 @SuppressWarnings("synthetic-access")
346 private final String identifier = createIdentifier("client-get");
349 @SuppressWarnings("synthetic-access")
350 public void run() throws IOException {
351 ClientGet clientGet = new ClientGet(uri, identifier);
352 clientGet.setFilterData(filterData);
353 fcpConnection.sendMessage(clientGet);
357 public void receivedGetFailed(FcpConnection fcpConnection, GetFailed getFailed) {
358 if (!getFailed.getIdentifier().equals(identifier)) {
361 if ((getFailed.getCode() == 27) || (getFailed.getCode() == 24)) {
363 String newUri = getFailed.getRedirectURI();
364 getResult.realUri(newUri);
366 ClientGet clientGet = new ClientGet(newUri, identifier);
367 clientGet.setFilterData(filterData);
368 fcpConnection.sendMessage(clientGet);
369 } catch (IOException ioe1) {
370 getResult.success(false).exception(ioe1);
371 completionLatch.countDown();
374 getResult.success(false).errorCode(getFailed.getCode());
375 completionLatch.countDown();
380 public void receivedAllData(FcpConnection fcpConnection, AllData allData) {
381 if (!allData.getIdentifier().equals(identifier)) {
384 getResult.success(true).contentType(allData.getContentType()).contentLength(allData.getDataLength()).inputStream(allData.getPayloadInputStream());
385 completionLatch.countDown();
393 * Disconnects the FCP client.
395 public void disconnect() {
396 synchronized (syncObject) {
397 fcpConnection.close();
398 syncObject.notifyAll();
406 public void close() {
411 * Returns whether this client is currently connected.
413 * @return {@code true} if the client is currently connected, {@code false}
416 public boolean isConnected() {
421 * Detaches this client from its underlying FCP connection.
423 public void detach() {
424 fcpConnection.removeFcpListener(connectionClosedListener);
432 * Returns all peers that the node has.
434 * @param withMetadata
435 * <code>true</code> to include peer metadata
436 * @param withVolatile
437 * <code>true</code> to include volatile peer data
438 * @return A set containing the node’s peers
439 * @throws IOException
440 * if an I/O error occurs
441 * @throws FcpException
442 * if an FCP error occurs
444 public Collection<Peer> getPeers(final boolean withMetadata, final boolean withVolatile) throws IOException, FcpException {
445 final Set<Peer> peers = Collections.synchronizedSet(new HashSet<Peer>());
446 new ExtendedFcpAdapter() {
448 /** The ID of the “ListPeers” request. */
449 @SuppressWarnings("synthetic-access")
450 private String identifier = createIdentifier("list-peers");
456 @SuppressWarnings("synthetic-access")
457 public void run() throws IOException {
458 fcpConnection.sendMessage(new ListPeers(identifier, withMetadata, withVolatile));
465 public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
466 if (peer.getIdentifier().equals(identifier)) {
475 public void receivedEndListPeers(FcpConnection fcpConnection, EndListPeers endListPeers) {
476 if (endListPeers.getIdentifier().equals(identifier)) {
477 completionLatch.countDown();
485 * Returns all darknet peers.
487 * @param withMetadata
488 * <code>true</code> to include peer metadata
489 * @param withVolatile
490 * <code>true</code> to include volatile peer data
491 * @return A set containing the node’s darknet peers
492 * @throws IOException
493 * if an I/O error occurs
494 * @throws FcpException
495 * if an FCP error occurs
497 public Collection<Peer> getDarknetPeers(boolean withMetadata, boolean withVolatile) throws IOException, FcpException {
498 Collection<Peer> allPeers = getPeers(withMetadata, withVolatile);
499 Collection<Peer> darknetPeers = new HashSet<Peer>();
500 for (Peer peer : allPeers) {
501 if (!peer.isOpennet() && !peer.isSeed()) {
502 darknetPeers.add(peer);
509 * Returns all opennet peers.
511 * @param withMetadata
512 * <code>true</code> to include peer metadata
513 * @param withVolatile
514 * <code>true</code> to include volatile peer data
515 * @return A set containing the node’s opennet peers
516 * @throws IOException
517 * if an I/O error occurs
518 * @throws FcpException
519 * if an FCP error occurs
521 public Collection<Peer> getOpennetPeers(boolean withMetadata, boolean withVolatile) throws IOException, FcpException {
522 Collection<Peer> allPeers = getPeers(withMetadata, withVolatile);
523 Collection<Peer> opennetPeers = new HashSet<Peer>();
524 for (Peer peer : allPeers) {
525 if (peer.isOpennet() && !peer.isSeed()) {
526 opennetPeers.add(peer);
533 * Returns all seed peers.
535 * @param withMetadata
536 * <code>true</code> to include peer metadata
537 * @param withVolatile
538 * <code>true</code> to include volatile peer data
539 * @return A set containing the node’s seed peers
540 * @throws IOException
541 * if an I/O error occurs
542 * @throws FcpException
543 * if an FCP error occurs
545 public Collection<Peer> getSeedPeers(boolean withMetadata, boolean withVolatile) throws IOException, FcpException {
546 Collection<Peer> allPeers = getPeers(withMetadata, withVolatile);
547 Collection<Peer> seedPeers = new HashSet<Peer>();
548 for (Peer peer : allPeers) {
557 * Adds the given peer to the node.
561 * @throws IOException
562 * if an I/O error occurs
563 * @throws FcpException
564 * if an FCP error occurs
566 public void addPeer(Peer peer) throws IOException, FcpException {
567 addPeer(peer.getNodeRef());
571 * Adds the peer defined by the noderef to the node.
574 * The noderef that defines the new peer
575 * @throws IOException
576 * if an I/O error occurs
577 * @throws FcpException
578 * if an FCP error occurs
580 public void addPeer(NodeRef nodeRef) throws IOException, FcpException {
581 addPeer(new AddPeer(nodeRef));
585 * Adds a peer, reading the noderef from the given URL.
588 * The URL to read the noderef from
589 * @throws IOException
590 * if an I/O error occurs
591 * @throws FcpException
592 * if an FCP error occurs
594 public void addPeer(URL url) throws IOException, FcpException {
595 addPeer(new AddPeer(url));
599 * Adds a peer, reading the noderef of the peer from the given file.
600 * <strong>Note:</strong> the file to read the noderef from has to reside
601 * on the same machine as the node!
604 * The name of the file containing the peer’s noderef
605 * @throws IOException
606 * if an I/O error occurs
607 * @throws FcpException
608 * if an FCP error occurs
610 public void addPeer(String file) throws IOException, FcpException {
611 addPeer(new AddPeer(file));
615 * Sends the given {@link AddPeer} message to the node. This method should
616 * not be called directly. Use one of {@link #addPeer(Peer)},
617 * {@link #addPeer(NodeRef)}, {@link #addPeer(URL)}, or
618 * {@link #addPeer(String)} instead.
621 * The “AddPeer” message
622 * @throws IOException
623 * if an I/O error occurs
624 * @throws FcpException
625 * if an FCP error occurs
627 private void addPeer(final AddPeer addPeer) throws IOException, FcpException {
628 new ExtendedFcpAdapter() {
634 @SuppressWarnings("synthetic-access")
635 public void run() throws IOException {
636 fcpConnection.sendMessage(addPeer);
643 public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
644 completionLatch.countDown();
650 * Modifies the given peer.
654 * @param allowLocalAddresses
655 * <code>true</code> to allow local address, <code>false</code>
656 * to not allow local address, <code>null</code> to not change
659 * <code>true</code> to disable the peer, <code>false</code> to
660 * enable the peer, <code>null</code> to not change the setting
662 * <code>true</code> to enable “listen only” for the peer,
663 * <code>false</code> to disable it, <code>null</code> to not
665 * @throws IOException
666 * if an I/O error occurs
667 * @throws FcpException
668 * if an FCP error occurs
670 public void modifyPeer(final Peer peer, final Boolean allowLocalAddresses, final Boolean disabled, final Boolean listenOnly) throws IOException, FcpException {
671 new ExtendedFcpAdapter() {
677 @SuppressWarnings("synthetic-access")
678 public void run() throws IOException {
679 fcpConnection.sendMessage(new ModifyPeer(peer.getIdentity(), allowLocalAddresses, disabled, listenOnly));
686 public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
687 completionLatch.countDown();
693 * Removes the given peer.
697 * @throws IOException
698 * if an I/O error occurs
699 * @throws FcpException
700 * if an FCP error occurs
702 public void removePeer(final Peer peer) throws IOException, FcpException {
703 new ExtendedFcpAdapter() {
709 @SuppressWarnings("synthetic-access")
710 public void run() throws IOException {
711 fcpConnection.sendMessage(new RemovePeer(peer.getIdentity()));
718 public void receivedPeerRemoved(FcpConnection fcpConnection, PeerRemoved peerRemoved) {
719 completionLatch.countDown();
725 // PEER NOTES MANAGEMENT
729 * Returns the peer note of the given peer.
732 * The peer to get the note for
733 * @return The peer’s note
734 * @throws IOException
735 * if an I/O error occurs
736 * @throws FcpException
737 * if an FCP error occurs
739 public PeerNote getPeerNote(final Peer peer) throws IOException, FcpException {
740 final AtomicReference<PeerNote> objectWrapper = new AtomicReference<PeerNote>();
741 new ExtendedFcpAdapter() {
747 @SuppressWarnings("synthetic-access")
748 public void run() throws IOException {
749 fcpConnection.sendMessage(new ListPeerNotes(peer.getIdentity()));
756 public void receivedPeerNote(FcpConnection fcpConnection, PeerNote peerNote) {
757 if (peerNote.getNodeIdentifier().equals(peer.getIdentity())) {
758 objectWrapper.set(peerNote);
766 public void receivedEndListPeerNotes(FcpConnection fcpConnection, EndListPeerNotes endListPeerNotes) {
767 completionLatch.countDown();
770 return objectWrapper.get();
774 * Replaces the peer note for the given peer.
779 * The new base64-encoded note text
781 * The type of the note (currently only <code>1</code> is
783 * @throws IOException
784 * if an I/O error occurs
785 * @throws FcpException
786 * if an FCP error occurs
788 public void modifyPeerNote(final Peer peer, final String noteText, final int noteType) throws IOException, FcpException {
789 new ExtendedFcpAdapter() {
795 @SuppressWarnings("synthetic-access")
796 public void run() throws IOException {
797 fcpConnection.sendMessage(new ModifyPeerNote(peer.getIdentity(), noteText, noteType));
804 public void receivedPeer(FcpConnection fcpConnection, Peer receivedPeer) {
805 if (receivedPeer.getIdentity().equals(peer.getIdentity())) {
806 completionLatch.countDown();
817 * Generates a new SSK key pair.
819 * @return The generated key pair
820 * @throws IOException
821 * if an I/O error occurs
822 * @throws FcpException
823 * if an FCP error occurs
825 public SSKKeypair generateKeyPair() throws IOException, FcpException {
826 final AtomicReference<SSKKeypair> sskKeypairWrapper = new AtomicReference<SSKKeypair>();
827 new ExtendedFcpAdapter() {
833 @SuppressWarnings("synthetic-access")
834 public void run() throws IOException {
835 fcpConnection.sendMessage(new GenerateSSK());
842 public void receivedSSKKeypair(FcpConnection fcpConnection, SSKKeypair sskKeypair) {
843 sskKeypairWrapper.set(sskKeypair);
844 completionLatch.countDown();
847 return sskKeypairWrapper.get();
851 // REQUEST MANAGEMENT
855 * Returns all currently visible persistent get requests.
858 * <code>true</code> to return get requests from the global
859 * queue, <code>false</code> to only show requests from the
861 * @return All get requests
862 * @throws IOException
863 * if an I/O error occurs
864 * @throws FcpException
865 * if an FCP error occurs
867 public Collection<Request> getGetRequests(final boolean global) throws IOException, FcpException {
868 return from(getRequests(global)).filter(new Predicate<Request>() {
870 public boolean apply(Request request) {
871 return request instanceof GetRequest;
877 * Returns all currently visible persistent put requests.
880 * <code>true</code> to return put requests from the global
881 * queue, <code>false</code> to only show requests from the
883 * @return All put requests
884 * @throws IOException
885 * if an I/O error occurs
886 * @throws FcpException
887 * if an FCP error occurs
889 public Collection<Request> getPutRequests(final boolean global) throws IOException, FcpException {
890 return from(getRequests(global)).filter(new Predicate<Request>() {
892 public boolean apply(Request request) {
893 return request instanceof PutRequest;
899 * Returns all currently visible persistent requests.
902 * <code>true</code> to return requests from the global queue,
903 * <code>false</code> to only show requests from the
905 * @return All requests
906 * @throws IOException
907 * if an I/O error occurs
908 * @throws FcpException
909 * if an FCP error occurs
911 public Collection<Request> getRequests(final boolean global) throws IOException, FcpException {
912 final Map<String, Request> requests = Collections.synchronizedMap(new HashMap<String, Request>());
913 new ExtendedFcpAdapter() {
919 @SuppressWarnings("synthetic-access")
920 public void run() throws IOException {
921 fcpConnection.sendMessage(new ListPersistentRequests());
928 public void receivedPersistentGet(FcpConnection fcpConnection, PersistentGet persistentGet) {
929 if (!persistentGet.isGlobal() || global) {
930 GetRequest getRequest = new GetRequest(persistentGet);
931 requests.put(persistentGet.getIdentifier(), getRequest);
938 * @see net.pterodactylus.fcp.FcpAdapter#receivedDataFound(net.pterodactylus.fcp.FcpConnection,
939 * net.pterodactylus.fcp.DataFound)
942 public void receivedDataFound(FcpConnection fcpConnection, DataFound dataFound) {
943 Request getRequest = requests.get(dataFound.getIdentifier());
944 if (getRequest == null) {
947 getRequest.setComplete(true);
948 getRequest.setLength(dataFound.getDataLength());
949 getRequest.setContentType(dataFound.getMetadataContentType());
955 * @see net.pterodactylus.fcp.FcpAdapter#receivedGetFailed(net.pterodactylus.fcp.FcpConnection,
956 * net.pterodactylus.fcp.GetFailed)
959 public void receivedGetFailed(FcpConnection fcpConnection, GetFailed getFailed) {
960 Request getRequest = requests.get(getFailed.getIdentifier());
961 if (getRequest == null) {
964 getRequest.setComplete(true);
965 getRequest.setFailed(true);
966 getRequest.setFatal(getFailed.isFatal());
967 getRequest.setErrorCode(getFailed.getCode());
973 * @see net.pterodactylus.fcp.FcpAdapter#receivedPersistentPut(net.pterodactylus.fcp.FcpConnection,
974 * net.pterodactylus.fcp.PersistentPut)
977 public void receivedPersistentPut(FcpConnection fcpConnection, PersistentPut persistentPut) {
978 if (!persistentPut.isGlobal() || global) {
979 PutRequest putRequest = new PutRequest(persistentPut);
980 requests.put(persistentPut.getIdentifier(), putRequest);
987 * @see net.pterodactylus.fcp.FcpAdapter#receivedSimpleProgress(net.pterodactylus.fcp.FcpConnection,
988 * net.pterodactylus.fcp.SimpleProgress)
991 public void receivedSimpleProgress(FcpConnection fcpConnection, SimpleProgress simpleProgress) {
992 Request request = requests.get(simpleProgress.getIdentifier());
993 if (request == null) {
996 request.setTotalBlocks(simpleProgress.getTotal());
997 request.setRequiredBlocks(simpleProgress.getRequired());
998 request.setFailedBlocks(simpleProgress.getFailed());
999 request.setFatallyFailedBlocks(simpleProgress.getFatallyFailed());
1000 request.setSucceededBlocks(simpleProgress.getSucceeded());
1001 request.setFinalizedTotal(simpleProgress.isFinalizedTotal());
1008 public void receivedEndListPersistentRequests(FcpConnection fcpConnection, EndListPersistentRequests endListPersistentRequests) {
1009 completionLatch.countDown();
1012 return requests.values();
1016 * Sends a message to a plugin and waits for the response.
1018 * @param pluginClass
1019 * The name of the plugin class
1021 * The parameters for the plugin
1022 * @return The responses from the plugin
1023 * @throws FcpException
1024 * if an FCP error occurs
1025 * @throws IOException
1026 * if an I/O error occurs
1028 public Map<String, String> sendPluginMessage(String pluginClass, Map<String, String> parameters) throws IOException, FcpException {
1029 return sendPluginMessage(pluginClass, parameters, 0, null);
1033 * Sends a message to a plugin and waits for the response.
1035 * @param pluginClass
1036 * The name of the plugin class
1038 * The parameters for the plugin
1040 * The length of the optional data stream, or {@code 0} if there
1041 * is no optional data stream
1042 * @param dataInputStream
1043 * The input stream for the payload, or {@code null} if there is
1045 * @return The responses from the plugin
1046 * @throws FcpException
1047 * if an FCP error occurs
1048 * @throws IOException
1049 * if an I/O error occurs
1051 public Map<String, String> sendPluginMessage(final String pluginClass, final Map<String, String> parameters, final long dataLength, final InputStream dataInputStream) throws IOException, FcpException {
1052 final Map<String, String> pluginReplies = Collections.synchronizedMap(new HashMap<String, String>());
1053 new ExtendedFcpAdapter() {
1055 @SuppressWarnings("synthetic-access")
1056 private final String identifier = createIdentifier("FCPPluginMessage");
1059 @SuppressWarnings("synthetic-access")
1060 public void run() throws IOException {
1061 FCPPluginMessage fcpPluginMessage = new FCPPluginMessage(pluginClass);
1062 for (Entry<String, String> parameter : parameters.entrySet()) {
1063 fcpPluginMessage.setParameter(parameter.getKey(), parameter.getValue());
1065 fcpPluginMessage.setIdentifier(identifier);
1066 if ((dataLength > 0) && (dataInputStream != null)) {
1067 fcpPluginMessage.setDataLength(dataLength);
1068 fcpPluginMessage.setPayloadInputStream(dataInputStream);
1070 fcpConnection.sendMessage(fcpPluginMessage);
1077 public void receivedFCPPluginReply(FcpConnection fcpConnection, FCPPluginReply fcpPluginReply) {
1078 if (!fcpPluginReply.getIdentifier().equals(identifier)) {
1081 pluginReplies.putAll(fcpPluginReply.getReplies());
1082 completionLatch.countDown();
1086 return pluginReplies;
1094 * Returns information about the node.
1096 * @param giveOpennetRef
1097 * Whether to return the OpenNet reference
1098 * @param withPrivate
1099 * Whether to return private node data
1100 * @param withVolatile
1101 * Whether to return volatile node data
1102 * @return Node information
1103 * @throws FcpException
1104 * if an FCP error occurs
1105 * @throws IOException
1106 * if an I/O error occurs
1108 public NodeData getNodeInformation(final Boolean giveOpennetRef, final Boolean withPrivate, final Boolean withVolatile) throws IOException, FcpException {
1109 final AtomicReference<NodeData> nodeDataWrapper = new AtomicReference<NodeData>();
1110 new ExtendedFcpAdapter() {
1113 @SuppressWarnings("synthetic-access")
1114 public void run() throws IOException {
1115 GetNode getNodeMessage = new GetNode(giveOpennetRef, withPrivate, withVolatile);
1116 fcpConnection.sendMessage(getNodeMessage);
1123 public void receivedNodeData(FcpConnection fcpConnection, NodeData nodeData) {
1124 nodeDataWrapper.set(nodeData);
1125 completionLatch.countDown();
1128 return nodeDataWrapper.get();
1136 * Creates a unique request identifier.
1139 * The basename of the request
1140 * @return The created request identifier
1142 private String createIdentifier(String basename) {
1143 return basename + "-" + System.currentTimeMillis() + "-" + (int) (Math.random() * Integer.MAX_VALUE);
1147 * Checks whether the connection is in the required state.
1150 * The required connection state
1151 * @throws FcpException
1152 * if the connection is not in the required state
1154 private void checkConnected(boolean connected) throws FcpException {
1155 if (this.connected != connected) {
1156 throw new FcpException("Client is " + (connected ? "not" : "already") + " connected.");
1161 * Tells the client that it is now disconnected. This method is called by
1162 * {@link ExtendedFcpAdapter} only.
1164 private void setDisconnected() {
1169 * Implementation of an {@link FcpListener} that can store an
1170 * {@link FcpException} and wait for the arrival of a certain command.
1172 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
1174 private abstract class ExtendedFcpAdapter extends FcpAdapter {
1176 /** The count down latch used to wait for completion. */
1177 protected final CountDownLatch completionLatch = new CountDownLatch(1);
1179 /** The FCP exception, if any. */
1180 protected FcpException fcpException;
1183 * Creates a new extended FCP adapter.
1185 public ExtendedFcpAdapter() {
1190 * Executes the FCP commands in {@link #run()}, wrapping the execution
1191 * and catching exceptions.
1193 * @throws IOException
1194 * if an I/O error occurs
1195 * @throws FcpException
1196 * if an FCP error occurs
1198 @SuppressWarnings("synthetic-access")
1199 public void execute() throws IOException, FcpException {
1200 checkConnected(true);
1201 fcpConnection.addFcpListener(this);
1206 completionLatch.await();
1208 } catch (InterruptedException ie1) {
1209 /* ignore, we’ll loop. */
1212 } catch (IOException ioe1) {
1216 fcpConnection.removeFcpListener(this);
1218 if (fcpException != null) {
1225 * The FCP commands that actually get executed.
1227 * @throws IOException
1228 * if an I/O error occurs
1230 public abstract void run() throws IOException;
1236 public void connectionClosed(FcpConnection fcpConnection, Throwable throwable) {
1237 fcpException = new FcpException("Connection closed", throwable);
1238 completionLatch.countDown();
1245 public void receivedCloseConnectionDuplicateClientName(FcpConnection fcpConnection, CloseConnectionDuplicateClientName closeConnectionDuplicateClientName) {
1246 fcpException = new FcpException("Connection closed, duplicate client name");
1247 completionLatch.countDown();
1254 public void receivedProtocolError(FcpConnection fcpConnection, ProtocolError protocolError) {
1255 fcpException = new FcpException("Protocol error (" + protocolError.getCode() + ", " + protocolError.getCodeDescription());
1256 completionLatch.countDown();