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 java.io.Closeable;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.net.InetAddress;
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;
32 import java.util.Map.Entry;
34 import java.util.concurrent.CountDownLatch;
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;
77 * High-level FCP client that hides the details of the underlying FCP
80 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
82 public class FcpClient implements Closeable {
84 /** Object used for synchronization. */
85 private final Object syncObject = new Object();
87 /** Listener management. */
88 private final FcpClientListenerManager fcpClientListenerManager = new FcpClientListenerManager(this);
90 /** The underlying FCP connection. */
91 private final FcpConnection fcpConnection;
93 /** The {@link NodeHello} data sent by the node on connection. */
94 private volatile NodeHello nodeHello;
96 /** Whether the client is currently connected. */
97 private volatile boolean connected;
99 /** The listener for “connection closed” events. */
100 private FcpListener connectionClosedListener;
103 * Creates an FCP client with the given name.
105 * @throws UnknownHostException
106 * if the hostname “localhost” is unknown
108 public FcpClient() throws UnknownHostException {
113 * Creates an FCP client.
116 * The hostname of the Freenet node
117 * @throws UnknownHostException
118 * if the given hostname can not be resolved
120 public FcpClient(String hostname) throws UnknownHostException {
121 this(hostname, FcpConnection.DEFAULT_PORT);
125 * Creates an FCP client.
128 * The hostname of the Freenet node
130 * The Freenet node’s FCP port
131 * @throws UnknownHostException
132 * if the given hostname can not be resolved
134 public FcpClient(String hostname, int port) throws UnknownHostException {
135 this(InetAddress.getByName(hostname), port);
139 * Creates an FCP client.
142 * The host address of the Freenet node
144 public FcpClient(InetAddress host) {
145 this(host, FcpConnection.DEFAULT_PORT);
149 * Creates an FCP client.
152 * The host address of the Freenet node
154 * The Freenet node’s FCP port
156 public FcpClient(InetAddress host, int port) {
157 this(new FcpConnection(host, port), false);
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
165 * @param fcpConnection
166 * The FCP connection to use
168 public FcpClient(FcpConnection fcpConnection) {
169 this(fcpConnection, true);
173 * Creates a new high-level FCP client that will use the given connection.
175 * @param fcpConnection
176 * The FCP connection to use
178 * The initial status of the FCP connection
180 public FcpClient(FcpConnection fcpConnection, boolean connected) {
181 this.fcpConnection = fcpConnection;
182 this.connected = connected;
183 connectionClosedListener = new FcpAdapter() {
189 @SuppressWarnings("synthetic-access")
190 public void connectionClosed(FcpConnection fcpConnection, Throwable throwable) {
191 FcpClient.this.connected = false;
192 fcpClientListenerManager.fireFcpClientDisconnected();
195 fcpConnection.addFcpListener(connectionClosedListener);
199 // LISTENER MANAGEMENT
203 * Adds an FCP listener to the underlying connection.
206 * The FCP listener to add
208 public void addFcpListener(FcpListener fcpListener) {
209 fcpConnection.addFcpListener(fcpListener);
213 * Removes an FCP listener from the underlying connection.
216 * The FCP listener to remove
218 public void removeFcpListener(FcpListener fcpListener) {
219 fcpConnection.removeFcpListener(fcpListener);
223 * Adds an FCP client listener to the list of registered listeners.
225 * @param fcpClientListener
226 * The FCP client listener to add
228 public void addFcpClientListener(FcpClientListener fcpClientListener) {
229 fcpClientListenerManager.addListener(fcpClientListener);
233 * Removes an FCP client listener from the list of registered listeners.
235 * @param fcpClientListener
236 * The FCP client listener to remove
238 public void removeFcpClientListener(FcpClientListener fcpClientListener) {
239 fcpClientListenerManager.removeListener(fcpClientListener);
247 * Returns the {@link NodeHello} object that the node returned when
250 * @return The {@code NodeHello} data container
252 public NodeHello getNodeHello() {
257 * Returns the underlying FCP connection.
259 * @return The underlying FCP connection
261 public FcpConnection getConnection() {
262 return fcpConnection;
270 * Connects the FCP client.
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
279 public void connect(final String name) throws IOException, FcpException {
280 checkConnected(false);
282 new ExtendedFcpAdapter() {
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);
301 @SuppressWarnings("synthetic-access")
302 public void receivedNodeHello(FcpConnection fcpConnection, NodeHello nodeHello) {
303 FcpClient.this.nodeHello = nodeHello;
304 completionLatch.countDown();
310 * Returns the file with the given URI. The retrieved data will be run
311 * through Freenet’s content filter.
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
321 public GetResult getURI(final String uri) throws IOException, FcpException {
322 return getURI(uri, true);
326 * Returns the file with the given URI.
331 * {@code true} to filter the retrieved data, {@code false}
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
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() {
344 @SuppressWarnings("synthetic-access")
345 private final String identifier = createIdentifier("client-get");
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);
356 public void receivedGetFailed(FcpConnection fcpConnection, GetFailed getFailed) {
357 if (!getFailed.getIdentifier().equals(identifier)) {
360 if ((getFailed.getCode() == 27) || (getFailed.getCode() == 24)) {
362 String newUri = getFailed.getRedirectURI();
363 getResult.realUri(newUri);
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();
373 getResult.success(false).errorCode(getFailed.getCode());
374 completionLatch.countDown();
379 public void receivedAllData(FcpConnection fcpConnection, AllData allData) {
380 if (!allData.getIdentifier().equals(identifier)) {
383 InputStream temporaryInputStream;
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);
390 completionLatch.countDown();
398 * Disconnects the FCP client.
400 public void disconnect() {
401 synchronized (syncObject) {
402 fcpConnection.close();
403 syncObject.notifyAll();
411 public void close() {
416 * Returns whether this client is currently connected.
418 * @return {@code true} if the client is currently connected, {@code false}
421 public boolean isConnected() {
426 * Detaches this client from its underlying FCP connection.
428 public void detach() {
429 fcpConnection.removeFcpListener(connectionClosedListener);
437 * Returns all peers that the node has.
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
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() {
453 /** The ID of the “ListPeers” request. */
454 @SuppressWarnings("synthetic-access")
455 private String identifier = createIdentifier("list-peers");
461 @SuppressWarnings("synthetic-access")
462 public void run() throws IOException {
463 fcpConnection.sendMessage(new ListPeers(identifier, withMetadata, withVolatile));
470 public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
471 if (peer.getIdentifier().equals(identifier)) {
480 public void receivedEndListPeers(FcpConnection fcpConnection, EndListPeers endListPeers) {
481 if (endListPeers.getIdentifier().equals(identifier)) {
482 completionLatch.countDown();
490 * Returns all darknet peers.
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
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);
514 * Returns all opennet peers.
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
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);
538 * Returns all seed peers.
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
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) {
562 * Adds the given peer to the node.
566 * @throws IOException
567 * if an I/O error occurs
568 * @throws FcpException
569 * if an FCP error occurs
571 public void addPeer(Peer peer) throws IOException, FcpException {
572 addPeer(peer.getNodeRef());
576 * Adds the peer defined by the noderef to the node.
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
585 public void addPeer(NodeRef nodeRef) throws IOException, FcpException {
586 addPeer(new AddPeer(nodeRef));
590 * Adds a peer, reading the noderef from the given 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
599 public void addPeer(URL url) throws IOException, FcpException {
600 addPeer(new AddPeer(url));
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!
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
615 public void addPeer(String file) throws IOException, FcpException {
616 addPeer(new AddPeer(file));
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.
626 * The “AddPeer” message
627 * @throws IOException
628 * if an I/O error occurs
629 * @throws FcpException
630 * if an FCP error occurs
632 private void addPeer(final AddPeer addPeer) throws IOException, FcpException {
633 new ExtendedFcpAdapter() {
639 @SuppressWarnings("synthetic-access")
640 public void run() throws IOException {
641 fcpConnection.sendMessage(addPeer);
648 public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
649 completionLatch.countDown();
655 * Modifies the given peer.
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
664 * <code>true</code> to disable the peer, <code>false</code> to
665 * enable the peer, <code>null</code> to not change the setting
667 * <code>true</code> to enable “listen only” for the peer,
668 * <code>false</code> to disable it, <code>null</code> to not
670 * @throws IOException
671 * if an I/O error occurs
672 * @throws FcpException
673 * if an FCP error occurs
675 public void modifyPeer(final Peer peer, final Boolean allowLocalAddresses, final Boolean disabled, final Boolean listenOnly) throws IOException, FcpException {
676 new ExtendedFcpAdapter() {
682 @SuppressWarnings("synthetic-access")
683 public void run() throws IOException {
684 fcpConnection.sendMessage(new ModifyPeer(peer.getIdentity(), allowLocalAddresses, disabled, listenOnly));
691 public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
692 completionLatch.countDown();
698 * Removes the given peer.
702 * @throws IOException
703 * if an I/O error occurs
704 * @throws FcpException
705 * if an FCP error occurs
707 public void removePeer(final Peer peer) throws IOException, FcpException {
708 new ExtendedFcpAdapter() {
714 @SuppressWarnings("synthetic-access")
715 public void run() throws IOException {
716 fcpConnection.sendMessage(new RemovePeer(peer.getIdentity()));
723 public void receivedPeerRemoved(FcpConnection fcpConnection, PeerRemoved peerRemoved) {
724 completionLatch.countDown();
730 // PEER NOTES MANAGEMENT
734 * Returns the peer note of the given 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
744 public PeerNote getPeerNote(final Peer peer) throws IOException, FcpException {
745 final ObjectWrapper<PeerNote> objectWrapper = new ObjectWrapper<PeerNote>();
746 new ExtendedFcpAdapter() {
752 @SuppressWarnings("synthetic-access")
753 public void run() throws IOException {
754 fcpConnection.sendMessage(new ListPeerNotes(peer.getIdentity()));
761 public void receivedPeerNote(FcpConnection fcpConnection, PeerNote peerNote) {
762 if (peerNote.getNodeIdentifier().equals(peer.getIdentity())) {
763 objectWrapper.set(peerNote);
771 public void receivedEndListPeerNotes(FcpConnection fcpConnection, EndListPeerNotes endListPeerNotes) {
772 completionLatch.countDown();
775 return objectWrapper.get();
779 * Replaces the peer note for the given peer.
784 * The new base64-encoded note text
786 * The type of the note (currently only <code>1</code> is
788 * @throws IOException
789 * if an I/O error occurs
790 * @throws FcpException
791 * if an FCP error occurs
793 public void modifyPeerNote(final Peer peer, final String noteText, final int noteType) throws IOException, FcpException {
794 new ExtendedFcpAdapter() {
800 @SuppressWarnings("synthetic-access")
801 public void run() throws IOException {
802 fcpConnection.sendMessage(new ModifyPeerNote(peer.getIdentity(), noteText, noteType));
809 public void receivedPeer(FcpConnection fcpConnection, Peer receivedPeer) {
810 if (receivedPeer.getIdentity().equals(peer.getIdentity())) {
811 completionLatch.countDown();
822 * Generates a new SSK key pair.
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
830 public SSKKeypair generateKeyPair() throws IOException, FcpException {
831 final ObjectWrapper<SSKKeypair> sskKeypairWrapper = new ObjectWrapper<SSKKeypair>();
832 new ExtendedFcpAdapter() {
838 @SuppressWarnings("synthetic-access")
839 public void run() throws IOException {
840 fcpConnection.sendMessage(new GenerateSSK());
847 public void receivedSSKKeypair(FcpConnection fcpConnection, SSKKeypair sskKeypair) {
848 sskKeypairWrapper.set(sskKeypair);
849 completionLatch.countDown();
852 return sskKeypairWrapper.get();
856 // REQUEST MANAGEMENT
860 * Returns all currently visible persistent get requests.
863 * <code>true</code> to return get requests from the global
864 * queue, <code>false</code> to only show requests from the
866 * @return All get requests
867 * @throws IOException
868 * if an I/O error occurs
869 * @throws FcpException
870 * if an FCP error occurs
872 public Collection<Request> getGetRequests(final boolean global) throws IOException, FcpException {
873 return Filters.filteredCollection(getRequests(global), new Filter<Request>() {
879 public boolean filterObject(Request request) {
880 return request instanceof GetRequest;
886 * Returns all currently visible persistent put requests.
889 * <code>true</code> to return put requests from the global
890 * queue, <code>false</code> to only show requests from the
892 * @return All put requests
893 * @throws IOException
894 * if an I/O error occurs
895 * @throws FcpException
896 * if an FCP error occurs
898 public Collection<Request> getPutRequests(final boolean global) throws IOException, FcpException {
899 return Filters.filteredCollection(getRequests(global), new Filter<Request>() {
905 public boolean filterObject(Request request) {
906 return request instanceof PutRequest;
912 * Returns all currently visible persistent requests.
915 * <code>true</code> to return requests from the global queue,
916 * <code>false</code> to only show requests from the client-local
918 * @return All requests
919 * @throws IOException
920 * if an I/O error occurs
921 * @throws FcpException
922 * if an FCP error occurs
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() {
932 @SuppressWarnings("synthetic-access")
933 public void run() throws IOException {
934 fcpConnection.sendMessage(new ListPersistentRequests());
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);
951 * @see net.pterodactylus.fcp.FcpAdapter#receivedDataFound(net.pterodactylus.fcp.FcpConnection,
952 * net.pterodactylus.fcp.DataFound)
955 public void receivedDataFound(FcpConnection fcpConnection, DataFound dataFound) {
956 Request getRequest = requests.get(dataFound.getIdentifier());
957 if (getRequest == null) {
960 getRequest.setComplete(true);
961 getRequest.setLength(dataFound.getDataLength());
962 getRequest.setContentType(dataFound.getMetadataContentType());
968 * @see net.pterodactylus.fcp.FcpAdapter#receivedGetFailed(net.pterodactylus.fcp.FcpConnection,
969 * net.pterodactylus.fcp.GetFailed)
972 public void receivedGetFailed(FcpConnection fcpConnection, GetFailed getFailed) {
973 Request getRequest = requests.get(getFailed.getIdentifier());
974 if (getRequest == null) {
977 getRequest.setComplete(true);
978 getRequest.setFailed(true);
979 getRequest.setFatal(getFailed.isFatal());
980 getRequest.setErrorCode(getFailed.getCode());
986 * @see net.pterodactylus.fcp.FcpAdapter#receivedPersistentPut(net.pterodactylus.fcp.FcpConnection,
987 * net.pterodactylus.fcp.PersistentPut)
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);
1000 * @see net.pterodactylus.fcp.FcpAdapter#receivedSimpleProgress(net.pterodactylus.fcp.FcpConnection,
1001 * net.pterodactylus.fcp.SimpleProgress)
1004 public void receivedSimpleProgress(FcpConnection fcpConnection, SimpleProgress simpleProgress) {
1005 Request request = requests.get(simpleProgress.getIdentifier());
1006 if (request == null) {
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());
1021 public void receivedEndListPersistentRequests(FcpConnection fcpConnection, EndListPersistentRequests endListPersistentRequests) {
1022 completionLatch.countDown();
1025 return requests.values();
1029 * Sends a message to a plugin and waits for the response.
1031 * @param pluginClass
1032 * The name of the plugin class
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
1041 public Map<String, String> sendPluginMessage(String pluginClass, Map<String, String> parameters) throws IOException, FcpException {
1042 return sendPluginMessage(pluginClass, parameters, 0, null);
1046 * Sends a message to a plugin and waits for the response.
1048 * @param pluginClass
1049 * The name of the plugin class
1051 * The parameters for the plugin
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
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
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() {
1068 @SuppressWarnings("synthetic-access")
1069 private final String identifier = createIdentifier("FCPPluginMessage");
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());
1078 fcpPluginMessage.setIdentifier(identifier);
1079 if ((dataLength > 0) && (dataInputStream != null)) {
1080 fcpPluginMessage.setDataLength(dataLength);
1081 fcpPluginMessage.setPayloadInputStream(dataInputStream);
1083 fcpConnection.sendMessage(fcpPluginMessage);
1090 public void receivedFCPPluginReply(FcpConnection fcpConnection, FCPPluginReply fcpPluginReply) {
1091 if (!fcpPluginReply.getIdentifier().equals(identifier)) {
1094 pluginReplies.putAll(fcpPluginReply.getReplies());
1095 completionLatch.countDown();
1099 return pluginReplies;
1107 * Returns information about the node.
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
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() {
1126 @SuppressWarnings("synthetic-access")
1127 public void run() throws IOException {
1128 GetNode getNodeMessage = new GetNode(giveOpennetRef, withPrivate, withVolatile);
1129 fcpConnection.sendMessage(getNodeMessage);
1136 public void receivedNodeData(FcpConnection fcpConnection, NodeData nodeData) {
1137 nodeDataWrapper.set(nodeData);
1138 completionLatch.countDown();
1141 return nodeDataWrapper.get();
1149 * Creates a unique request identifier.
1152 * The basename of the request
1153 * @return The created request identifier
1155 private String createIdentifier(String basename) {
1156 return basename + "-" + System.currentTimeMillis() + "-" + (int) (Math.random() * Integer.MAX_VALUE);
1160 * Checks whether the connection is in the required state.
1163 * The required connection state
1164 * @throws FcpException
1165 * if the connection is not in the required state
1167 private void checkConnected(boolean connected) throws FcpException {
1168 if (this.connected != connected) {
1169 throw new FcpException("Client is " + (connected ? "not" : "already") + " connected.");
1174 * Tells the client that it is now disconnected. This method is called by
1175 * {@link ExtendedFcpAdapter} only.
1177 private void setDisconnected() {
1182 * Implementation of an {@link FcpListener} that can store an
1183 * {@link FcpException} and wait for the arrival of a certain command.
1185 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
1187 private abstract class ExtendedFcpAdapter extends FcpAdapter {
1189 /** The count down latch used to wait for completion. */
1190 protected final CountDownLatch completionLatch = new CountDownLatch(1);
1192 /** The FCP exception, if any. */
1193 protected FcpException fcpException;
1196 * Creates a new extended FCP adapter.
1198 public ExtendedFcpAdapter() {
1203 * Executes the FCP commands in {@link #run()}, wrapping the execution
1204 * and catching exceptions.
1206 * @throws IOException
1207 * if an I/O error occurs
1208 * @throws FcpException
1209 * if an FCP error occurs
1211 @SuppressWarnings("synthetic-access")
1212 public void execute() throws IOException, FcpException {
1213 checkConnected(true);
1214 fcpConnection.addFcpListener(this);
1219 completionLatch.await();
1221 } catch (InterruptedException ie1) {
1222 /* ignore, we’ll loop. */
1225 } catch (IOException ioe1) {
1229 fcpConnection.removeFcpListener(this);
1231 if (fcpException != null) {
1238 * The FCP commands that actually get executed.
1240 * @throws IOException
1241 * if an I/O error occurs
1243 public abstract void run() throws IOException;
1249 public void connectionClosed(FcpConnection fcpConnection, Throwable throwable) {
1250 fcpException = new FcpException("Connection closed", throwable);
1251 completionLatch.countDown();
1258 public void receivedCloseConnectionDuplicateClientName(FcpConnection fcpConnection, CloseConnectionDuplicateClientName closeConnectionDuplicateClientName) {
1259 fcpException = new FcpException("Connection closed, duplicate client name");
1260 completionLatch.countDown();
1267 public void receivedProtocolError(FcpConnection fcpConnection, ProtocolError protocolError) {
1268 fcpException = new FcpException("Protocol error (" + protocolError.getCode() + ", " + protocolError.getCodeDescription());
1269 completionLatch.countDown();