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.IOException;
22 import java.io.InputStream;
23 import java.net.InetAddress;
25 import java.net.UnknownHostException;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.HashMap;
29 import java.util.HashSet;
31 import java.util.Map.Entry;
33 import java.util.concurrent.CountDownLatch;
35 import net.pterodactylus.fcp.AddPeer;
36 import net.pterodactylus.fcp.AllData;
37 import net.pterodactylus.fcp.ClientGet;
38 import net.pterodactylus.fcp.ClientHello;
39 import net.pterodactylus.fcp.CloseConnectionDuplicateClientName;
40 import net.pterodactylus.fcp.DataFound;
41 import net.pterodactylus.fcp.EndListPeerNotes;
42 import net.pterodactylus.fcp.EndListPeers;
43 import net.pterodactylus.fcp.EndListPersistentRequests;
44 import net.pterodactylus.fcp.FCPPluginMessage;
45 import net.pterodactylus.fcp.FCPPluginReply;
46 import net.pterodactylus.fcp.FcpAdapter;
47 import net.pterodactylus.fcp.FcpConnection;
48 import net.pterodactylus.fcp.FcpListener;
49 import net.pterodactylus.fcp.GenerateSSK;
50 import net.pterodactylus.fcp.GetFailed;
51 import net.pterodactylus.fcp.GetNode;
52 import net.pterodactylus.fcp.ListPeerNotes;
53 import net.pterodactylus.fcp.ListPeers;
54 import net.pterodactylus.fcp.ListPersistentRequests;
55 import net.pterodactylus.fcp.ModifyPeer;
56 import net.pterodactylus.fcp.ModifyPeerNote;
57 import net.pterodactylus.fcp.NodeData;
58 import net.pterodactylus.fcp.NodeHello;
59 import net.pterodactylus.fcp.NodeRef;
60 import net.pterodactylus.fcp.Peer;
61 import net.pterodactylus.fcp.PeerNote;
62 import net.pterodactylus.fcp.PeerRemoved;
63 import net.pterodactylus.fcp.PersistentGet;
64 import net.pterodactylus.fcp.PersistentPut;
65 import net.pterodactylus.fcp.ProtocolError;
66 import net.pterodactylus.fcp.RemovePeer;
67 import net.pterodactylus.fcp.SSKKeypair;
68 import net.pterodactylus.fcp.SimpleProgress;
69 import net.pterodactylus.fcp.WatchGlobal;
70 import net.pterodactylus.util.filter.Filter;
71 import net.pterodactylus.util.filter.Filters;
72 import net.pterodactylus.util.io.TemporaryInputStream;
73 import net.pterodactylus.util.thread.ObjectWrapper;
76 * High-level FCP client that hides the details of the underlying FCP
79 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
81 public class FcpClient {
83 /** Object used for synchronization. */
84 private final Object syncObject = new Object();
86 /** Listener management. */
87 private final FcpClientListenerManager fcpClientListenerManager = new FcpClientListenerManager(this);
89 /** The underlying FCP connection. */
90 private final FcpConnection fcpConnection;
92 /** The {@link NodeHello} data sent by the node on connection. */
93 private volatile NodeHello nodeHello;
95 /** Whether the client is currently connected. */
96 private volatile boolean connected;
98 /** The listener for “connection closed” events. */
99 private FcpListener connectionClosedListener;
102 * Creates an FCP client with the given name.
104 * @throws UnknownHostException
105 * if the hostname “localhost” is unknown
107 public FcpClient() throws UnknownHostException {
112 * Creates an FCP client.
115 * The hostname of the Freenet node
116 * @throws UnknownHostException
117 * if the given hostname can not be resolved
119 public FcpClient(String hostname) throws UnknownHostException {
120 this(hostname, FcpConnection.DEFAULT_PORT);
124 * Creates an FCP client.
127 * The hostname of the Freenet node
129 * The Freenet node’s FCP port
130 * @throws UnknownHostException
131 * if the given hostname can not be resolved
133 public FcpClient(String hostname, int port) throws UnknownHostException {
134 this(InetAddress.getByName(hostname), port);
138 * Creates an FCP client.
141 * The host address of the Freenet node
143 public FcpClient(InetAddress host) {
144 this(host, FcpConnection.DEFAULT_PORT);
148 * Creates an FCP client.
151 * The host address of the Freenet node
153 * The Freenet node’s FCP port
155 public FcpClient(InetAddress host, int port) {
156 this(new FcpConnection(host, port), false);
160 * Creates a new high-level FCP client that will use the given connection.
161 * This constructor will assume that the FCP connection is already
164 * @param fcpConnection
165 * The FCP connection to use
167 public FcpClient(FcpConnection fcpConnection) {
168 this(fcpConnection, true);
172 * Creates a new high-level FCP client that will use the given connection.
174 * @param fcpConnection
175 * The FCP connection to use
177 * The initial status of the FCP connection
179 public FcpClient(FcpConnection fcpConnection, boolean connected) {
180 this.fcpConnection = fcpConnection;
181 this.connected = connected;
182 connectionClosedListener = new FcpAdapter() {
188 @SuppressWarnings("synthetic-access")
189 public void connectionClosed(FcpConnection fcpConnection, Throwable throwable) {
190 FcpClient.this.connected = false;
191 fcpClientListenerManager.fireFcpClientDisconnected();
194 fcpConnection.addFcpListener(connectionClosedListener);
198 // LISTENER MANAGEMENT
202 * Adds an FCP listener to the underlying connection.
205 * The FCP listener to add
207 public void addFcpListener(FcpListener fcpListener) {
208 fcpConnection.addFcpListener(fcpListener);
212 * Removes an FCP listener from the underlying connection.
215 * The FCP listener to remove
217 public void removeFcpListener(FcpListener fcpListener) {
218 fcpConnection.removeFcpListener(fcpListener);
222 * Adds an FCP client listener to the list of registered listeners.
224 * @param fcpClientListener
225 * The FCP client listener to add
227 public void addFcpClientListener(FcpClientListener fcpClientListener) {
228 fcpClientListenerManager.addListener(fcpClientListener);
232 * Removes an FCP client listener from the list of registered listeners.
234 * @param fcpClientListener
235 * The FCP client listener to remove
237 public void removeFcpClientListener(FcpClientListener fcpClientListener) {
238 fcpClientListenerManager.removeListener(fcpClientListener);
246 * Returns the {@link NodeHello} object that the node returned when
249 * @return The {@code NodeHello} data container
251 public NodeHello getNodeHello() {
256 * Returns the underlying FCP connection.
258 * @return The underlying FCP connection
260 public FcpConnection getConnection() {
261 return fcpConnection;
269 * Connects the FCP client.
272 * The name of the client
273 * @throws IOException
274 * if an I/O error occurs
275 * @throws FcpException
276 * if an FCP error occurs
278 public void connect(final String name) throws IOException, FcpException {
279 checkConnected(false);
281 new ExtendedFcpAdapter() {
287 @SuppressWarnings("synthetic-access")
288 public void run() throws IOException {
289 fcpConnection.connect();
290 ClientHello clientHello = new ClientHello(name);
291 fcpConnection.sendMessage(clientHello);
292 WatchGlobal watchGlobal = new WatchGlobal(true);
293 fcpConnection.sendMessage(watchGlobal);
300 @SuppressWarnings("synthetic-access")
301 public void receivedNodeHello(FcpConnection fcpConnection, NodeHello nodeHello) {
302 FcpClient.this.nodeHello = nodeHello;
303 completionLatch.countDown();
309 * Returns the file with the given URI.
313 * @return The result of the get request
314 * @throws IOException
315 * if an I/O error occurs
316 * @throws FcpException
317 * if an FCP error occurs
319 public GetResult getURI(final String uri) throws IOException, FcpException {
320 checkConnected(true);
321 final GetResult getResult = new GetResult();
322 new ExtendedFcpAdapter() {
324 @SuppressWarnings("synthetic-access")
325 private final String identifier = createIdentifier("client-get");
328 @SuppressWarnings("synthetic-access")
329 public void run() throws IOException {
330 ClientGet clientGet = new ClientGet(uri, identifier);
331 fcpConnection.sendMessage(clientGet);
335 public void receivedGetFailed(FcpConnection fcpConnection, GetFailed getFailed) {
336 if (!getFailed.getIdentifier().equals(identifier)) {
339 if (getFailed.getCode() == 27) {
341 String newUri = getFailed.getRedirectURI();
342 getResult.realUri(newUri);
344 fcpConnection.sendMessage(new ClientGet(newUri, identifier));
345 } catch (IOException ioe1) {
346 getResult.success(false).exception(ioe1);
347 completionLatch.countDown();
350 getResult.success(false).errorCode(getFailed.getCode());
351 completionLatch.countDown();
356 public void receivedAllData(FcpConnection fcpConnection, AllData allData) {
357 if (!allData.getIdentifier().equals(identifier)) {
360 InputStream temporaryInputStream;
362 temporaryInputStream = new TemporaryInputStream(allData.getPayloadInputStream());
363 getResult.success(true).contentType(allData.getContentType()).contentLength(allData.getDataLength()).inputStream(temporaryInputStream);
364 } catch (IOException ioe1) {
365 getResult.success(false).exception(ioe1);
367 completionLatch.countDown();
375 * Disconnects the FCP client.
377 public void disconnect() {
378 synchronized (syncObject) {
379 fcpConnection.close();
380 syncObject.notifyAll();
385 * Returns whether this client is currently connected.
387 * @return {@code true} if the client is currently connected, {@code false}
390 public boolean isConnected() {
395 * Detaches this client from its underlying FCP connection.
397 public void detach() {
398 fcpConnection.removeFcpListener(connectionClosedListener);
406 * Returns all peers that the node has.
408 * @param withMetadata
409 * <code>true</code> to include peer metadata
410 * @param withVolatile
411 * <code>true</code> to include volatile peer data
412 * @return A set containing the node’s peers
413 * @throws IOException
414 * if an I/O error occurs
415 * @throws FcpException
416 * if an FCP error occurs
418 public Collection<Peer> getPeers(final boolean withMetadata, final boolean withVolatile) throws IOException, FcpException {
419 final Set<Peer> peers = Collections.synchronizedSet(new HashSet<Peer>());
420 new ExtendedFcpAdapter() {
422 /** The ID of the “ListPeers” request. */
423 @SuppressWarnings("synthetic-access")
424 private String identifier = createIdentifier("list-peers");
430 @SuppressWarnings("synthetic-access")
431 public void run() throws IOException {
432 fcpConnection.sendMessage(new ListPeers(identifier, withMetadata, withVolatile));
439 public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
440 if (peer.getIdentifier().equals(identifier)) {
449 public void receivedEndListPeers(FcpConnection fcpConnection, EndListPeers endListPeers) {
450 if (endListPeers.getIdentifier().equals(identifier)) {
451 completionLatch.countDown();
459 * Returns all darknet peers.
461 * @param withMetadata
462 * <code>true</code> to include peer metadata
463 * @param withVolatile
464 * <code>true</code> to include volatile peer data
465 * @return A set containing the node’s darknet peers
466 * @throws IOException
467 * if an I/O error occurs
468 * @throws FcpException
469 * if an FCP error occurs
471 public Collection<Peer> getDarknetPeers(boolean withMetadata, boolean withVolatile) throws IOException, FcpException {
472 Collection<Peer> allPeers = getPeers(withMetadata, withVolatile);
473 Collection<Peer> darknetPeers = new HashSet<Peer>();
474 for (Peer peer : allPeers) {
475 if (!peer.isOpennet() && !peer.isSeed()) {
476 darknetPeers.add(peer);
483 * Returns all opennet peers.
485 * @param withMetadata
486 * <code>true</code> to include peer metadata
487 * @param withVolatile
488 * <code>true</code> to include volatile peer data
489 * @return A set containing the node’s opennet peers
490 * @throws IOException
491 * if an I/O error occurs
492 * @throws FcpException
493 * if an FCP error occurs
495 public Collection<Peer> getOpennetPeers(boolean withMetadata, boolean withVolatile) throws IOException, FcpException {
496 Collection<Peer> allPeers = getPeers(withMetadata, withVolatile);
497 Collection<Peer> opennetPeers = new HashSet<Peer>();
498 for (Peer peer : allPeers) {
499 if (peer.isOpennet() && !peer.isSeed()) {
500 opennetPeers.add(peer);
507 * Returns all seed peers.
509 * @param withMetadata
510 * <code>true</code> to include peer metadata
511 * @param withVolatile
512 * <code>true</code> to include volatile peer data
513 * @return A set containing the node’s seed peers
514 * @throws IOException
515 * if an I/O error occurs
516 * @throws FcpException
517 * if an FCP error occurs
519 public Collection<Peer> getSeedPeers(boolean withMetadata, boolean withVolatile) throws IOException, FcpException {
520 Collection<Peer> allPeers = getPeers(withMetadata, withVolatile);
521 Collection<Peer> seedPeers = new HashSet<Peer>();
522 for (Peer peer : allPeers) {
531 * Adds the given peer to the node.
535 * @throws IOException
536 * if an I/O error occurs
537 * @throws FcpException
538 * if an FCP error occurs
540 public void addPeer(Peer peer) throws IOException, FcpException {
541 addPeer(peer.getNodeRef());
545 * Adds the peer defined by the noderef to the node.
548 * The noderef that defines the new peer
549 * @throws IOException
550 * if an I/O error occurs
551 * @throws FcpException
552 * if an FCP error occurs
554 public void addPeer(NodeRef nodeRef) throws IOException, FcpException {
555 addPeer(new AddPeer(nodeRef));
559 * Adds a peer, reading the noderef from the given URL.
562 * The URL to read the noderef from
563 * @throws IOException
564 * if an I/O error occurs
565 * @throws FcpException
566 * if an FCP error occurs
568 public void addPeer(URL url) throws IOException, FcpException {
569 addPeer(new AddPeer(url));
573 * Adds a peer, reading the noderef of the peer from the given file.
574 * <strong>Note:</strong> the file to read the noderef from has to reside on
575 * the same machine as the node!
578 * The name of the file containing the peer’s noderef
579 * @throws IOException
580 * if an I/O error occurs
581 * @throws FcpException
582 * if an FCP error occurs
584 public void addPeer(String file) throws IOException, FcpException {
585 addPeer(new AddPeer(file));
589 * Sends the given {@link AddPeer} message to the node. This method should
590 * not be called directly. Use one of {@link #addPeer(Peer)},
591 * {@link #addPeer(NodeRef)}, {@link #addPeer(URL)}, or
592 * {@link #addPeer(String)} instead.
595 * The “AddPeer” message
596 * @throws IOException
597 * if an I/O error occurs
598 * @throws FcpException
599 * if an FCP error occurs
601 private void addPeer(final AddPeer addPeer) throws IOException, FcpException {
602 new ExtendedFcpAdapter() {
608 @SuppressWarnings("synthetic-access")
609 public void run() throws IOException {
610 fcpConnection.sendMessage(addPeer);
617 public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
618 completionLatch.countDown();
624 * Modifies the given peer.
628 * @param allowLocalAddresses
629 * <code>true</code> to allow local address, <code>false</code>
630 * to not allow local address, <code>null</code> to not change
633 * <code>true</code> to disable the peer, <code>false</code> to
634 * enable the peer, <code>null</code> to not change the setting
636 * <code>true</code> to enable “listen only” for the peer,
637 * <code>false</code> to disable it, <code>null</code> to not
639 * @throws IOException
640 * if an I/O error occurs
641 * @throws FcpException
642 * if an FCP error occurs
644 public void modifyPeer(final Peer peer, final Boolean allowLocalAddresses, final Boolean disabled, final Boolean listenOnly) throws IOException, FcpException {
645 new ExtendedFcpAdapter() {
651 @SuppressWarnings("synthetic-access")
652 public void run() throws IOException {
653 fcpConnection.sendMessage(new ModifyPeer(peer.getIdentity(), allowLocalAddresses, disabled, listenOnly));
660 public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
661 completionLatch.countDown();
667 * Removes the given peer.
671 * @throws IOException
672 * if an I/O error occurs
673 * @throws FcpException
674 * if an FCP error occurs
676 public void removePeer(final Peer peer) throws IOException, FcpException {
677 new ExtendedFcpAdapter() {
683 @SuppressWarnings("synthetic-access")
684 public void run() throws IOException {
685 fcpConnection.sendMessage(new RemovePeer(peer.getIdentity()));
692 public void receivedPeerRemoved(FcpConnection fcpConnection, PeerRemoved peerRemoved) {
693 completionLatch.countDown();
699 // PEER NOTES MANAGEMENT
703 * Returns the peer note of the given peer.
706 * The peer to get the note for
707 * @return The peer’s note
708 * @throws IOException
709 * if an I/O error occurs
710 * @throws FcpException
711 * if an FCP error occurs
713 public PeerNote getPeerNote(final Peer peer) throws IOException, FcpException {
714 final ObjectWrapper<PeerNote> objectWrapper = new ObjectWrapper<PeerNote>();
715 new ExtendedFcpAdapter() {
721 @SuppressWarnings("synthetic-access")
722 public void run() throws IOException {
723 fcpConnection.sendMessage(new ListPeerNotes(peer.getIdentity()));
730 public void receivedPeerNote(FcpConnection fcpConnection, PeerNote peerNote) {
731 if (peerNote.getNodeIdentifier().equals(peer.getIdentity())) {
732 objectWrapper.set(peerNote);
740 public void receivedEndListPeerNotes(FcpConnection fcpConnection, EndListPeerNotes endListPeerNotes) {
741 completionLatch.countDown();
744 return objectWrapper.get();
748 * Replaces the peer note for the given peer.
753 * The new base64-encoded note text
755 * The type of the note (currently only <code>1</code> is
757 * @throws IOException
758 * if an I/O error occurs
759 * @throws FcpException
760 * if an FCP error occurs
762 public void modifyPeerNote(final Peer peer, final String noteText, final int noteType) throws IOException, FcpException {
763 new ExtendedFcpAdapter() {
769 @SuppressWarnings("synthetic-access")
770 public void run() throws IOException {
771 fcpConnection.sendMessage(new ModifyPeerNote(peer.getIdentity(), noteText, noteType));
778 public void receivedPeer(FcpConnection fcpConnection, Peer receivedPeer) {
779 if (receivedPeer.getIdentity().equals(peer.getIdentity())) {
780 completionLatch.countDown();
791 * Generates a new SSK key pair.
793 * @return The generated key pair
794 * @throws IOException
795 * if an I/O error occurs
796 * @throws FcpException
797 * if an FCP error occurs
799 public SSKKeypair generateKeyPair() throws IOException, FcpException {
800 final ObjectWrapper<SSKKeypair> sskKeypairWrapper = new ObjectWrapper<SSKKeypair>();
801 new ExtendedFcpAdapter() {
807 @SuppressWarnings("synthetic-access")
808 public void run() throws IOException {
809 fcpConnection.sendMessage(new GenerateSSK());
816 public void receivedSSKKeypair(FcpConnection fcpConnection, SSKKeypair sskKeypair) {
817 sskKeypairWrapper.set(sskKeypair);
818 completionLatch.countDown();
821 return sskKeypairWrapper.get();
825 // REQUEST MANAGEMENT
829 * Returns all currently visible persistent get requests.
832 * <code>true</code> to return get requests from the global
833 * queue, <code>false</code> to only show requests from the
835 * @return All get requests
836 * @throws IOException
837 * if an I/O error occurs
838 * @throws FcpException
839 * if an FCP error occurs
841 public Collection<Request> getGetRequests(final boolean global) throws IOException, FcpException {
842 return Filters.filteredCollection(getRequests(global), new Filter<Request>() {
847 public boolean filterObject(Request request) {
848 return request instanceof GetRequest;
854 * Returns all currently visible persistent put requests.
857 * <code>true</code> to return put requests from the global
858 * queue, <code>false</code> to only show requests from the
860 * @return All put requests
861 * @throws IOException
862 * if an I/O error occurs
863 * @throws FcpException
864 * if an FCP error occurs
866 public Collection<Request> getPutRequests(final boolean global) throws IOException, FcpException {
867 return Filters.filteredCollection(getRequests(global), new Filter<Request>() {
872 public boolean filterObject(Request request) {
873 return request instanceof PutRequest;
879 * Returns all currently visible persistent requests.
882 * <code>true</code> to return requests from the global queue,
883 * <code>false</code> to only show requests from the client-local
885 * @return All requests
886 * @throws IOException
887 * if an I/O error occurs
888 * @throws FcpException
889 * if an FCP error occurs
891 public Collection<Request> getRequests(final boolean global) throws IOException, FcpException {
892 final Map<String, Request> requests = Collections.synchronizedMap(new HashMap<String, Request>());
893 new ExtendedFcpAdapter() {
899 @SuppressWarnings("synthetic-access")
900 public void run() throws IOException {
901 fcpConnection.sendMessage(new ListPersistentRequests());
908 public void receivedPersistentGet(FcpConnection fcpConnection, PersistentGet persistentGet) {
909 if (!persistentGet.isGlobal() || global) {
910 GetRequest getRequest = new GetRequest(persistentGet);
911 requests.put(persistentGet.getIdentifier(), getRequest);
918 * @see net.pterodactylus.fcp.FcpAdapter#receivedDataFound(net.pterodactylus.fcp.FcpConnection,
919 * net.pterodactylus.fcp.DataFound)
922 public void receivedDataFound(FcpConnection fcpConnection, DataFound dataFound) {
923 Request getRequest = requests.get(dataFound.getIdentifier());
924 if (getRequest == null) {
927 getRequest.setComplete(true);
928 getRequest.setLength(dataFound.getDataLength());
929 getRequest.setContentType(dataFound.getMetadataContentType());
935 * @see net.pterodactylus.fcp.FcpAdapter#receivedGetFailed(net.pterodactylus.fcp.FcpConnection,
936 * net.pterodactylus.fcp.GetFailed)
939 public void receivedGetFailed(FcpConnection fcpConnection, GetFailed getFailed) {
940 Request getRequest = requests.get(getFailed.getIdentifier());
941 if (getRequest == null) {
944 getRequest.setComplete(true);
945 getRequest.setFailed(true);
946 getRequest.setFatal(getFailed.isFatal());
947 getRequest.setErrorCode(getFailed.getCode());
953 * @see net.pterodactylus.fcp.FcpAdapter#receivedPersistentPut(net.pterodactylus.fcp.FcpConnection,
954 * net.pterodactylus.fcp.PersistentPut)
957 public void receivedPersistentPut(FcpConnection fcpConnection, PersistentPut persistentPut) {
958 if (!persistentPut.isGlobal() || global) {
959 PutRequest putRequest = new PutRequest(persistentPut);
960 requests.put(persistentPut.getIdentifier(), putRequest);
967 * @see net.pterodactylus.fcp.FcpAdapter#receivedSimpleProgress(net.pterodactylus.fcp.FcpConnection,
968 * net.pterodactylus.fcp.SimpleProgress)
971 public void receivedSimpleProgress(FcpConnection fcpConnection, SimpleProgress simpleProgress) {
972 Request request = requests.get(simpleProgress.getIdentifier());
973 if (request == null) {
976 request.setTotalBlocks(simpleProgress.getTotal());
977 request.setRequiredBlocks(simpleProgress.getRequired());
978 request.setFailedBlocks(simpleProgress.getFailed());
979 request.setFatallyFailedBlocks(simpleProgress.getFatallyFailed());
980 request.setSucceededBlocks(simpleProgress.getSucceeded());
981 request.setFinalizedTotal(simpleProgress.isFinalizedTotal());
988 public void receivedEndListPersistentRequests(FcpConnection fcpConnection, EndListPersistentRequests endListPersistentRequests) {
989 completionLatch.countDown();
992 return requests.values();
996 * Sends a message to a plugin and waits for the response.
999 * The name of the plugin class
1001 * The parameters for the plugin
1002 * @return The responses from the plugin
1003 * @throws FcpException
1004 * if an FCP error occurs
1005 * @throws IOException
1006 * if an I/O error occurs
1008 public Map<String, String> sendPluginMessage(String pluginClass, Map<String, String> parameters) throws IOException, FcpException {
1009 return sendPluginMessage(pluginClass, parameters, 0, null);
1013 * Sends a message to a plugin and waits for the response.
1015 * @param pluginClass
1016 * The name of the plugin class
1018 * The parameters for the plugin
1020 * The length of the optional data stream, or {@code 0} if there
1021 * is no optional data stream
1022 * @param dataInputStream
1023 * The input stream for the payload, or {@code null} if there is
1025 * @return The responses from the plugin
1026 * @throws FcpException
1027 * if an FCP error occurs
1028 * @throws IOException
1029 * if an I/O error occurs
1031 public Map<String, String> sendPluginMessage(final String pluginClass, final Map<String, String> parameters, final long dataLength, final InputStream dataInputStream) throws IOException, FcpException {
1032 final Map<String, String> pluginReplies = Collections.synchronizedMap(new HashMap<String, String>());
1033 new ExtendedFcpAdapter() {
1035 @SuppressWarnings("synthetic-access")
1036 private final String identifier = createIdentifier("FCPPluginMessage");
1039 @SuppressWarnings("synthetic-access")
1040 public void run() throws IOException {
1041 FCPPluginMessage fcpPluginMessage = new FCPPluginMessage(pluginClass);
1042 for (Entry<String, String> parameter : parameters.entrySet()) {
1043 fcpPluginMessage.setParameter(parameter.getKey(), parameter.getValue());
1045 fcpPluginMessage.setIdentifier(identifier);
1046 if ((dataLength > 0) && (dataInputStream != null)) {
1047 fcpPluginMessage.setDataLength(dataLength);
1048 fcpPluginMessage.setPayloadInputStream(dataInputStream);
1050 fcpConnection.sendMessage(fcpPluginMessage);
1057 public void receivedFCPPluginReply(FcpConnection fcpConnection, FCPPluginReply fcpPluginReply) {
1058 if (!fcpPluginReply.getIdentifier().equals(identifier)) {
1061 pluginReplies.putAll(fcpPluginReply.getReplies());
1062 completionLatch.countDown();
1066 return pluginReplies;
1074 * Returns information about the node.
1076 * @param giveOpennetRef
1077 * Whether to return the OpenNet reference
1078 * @param withPrivate
1079 * Whether to return private node data
1080 * @param withVolatile
1081 * Whether to return volatile node data
1082 * @return Node information
1083 * @throws FcpException
1084 * if an FCP error occurs
1085 * @throws IOException
1086 * if an I/O error occurs
1088 public NodeData getNodeInformation(final Boolean giveOpennetRef, final Boolean withPrivate, final Boolean withVolatile) throws IOException, FcpException {
1089 final ObjectWrapper<NodeData> nodeDataWrapper = new ObjectWrapper<NodeData>();
1090 new ExtendedFcpAdapter() {
1093 @SuppressWarnings("synthetic-access")
1094 public void run() throws IOException {
1095 GetNode getNodeMessage = new GetNode(giveOpennetRef, withPrivate, withVolatile);
1096 fcpConnection.sendMessage(getNodeMessage);
1103 public void receivedNodeData(FcpConnection fcpConnection, NodeData nodeData) {
1104 nodeDataWrapper.set(nodeData);
1105 completionLatch.countDown();
1108 return nodeDataWrapper.get();
1116 * Creates a unique request identifier.
1119 * The basename of the request
1120 * @return The created request identifier
1122 private String createIdentifier(String basename) {
1123 return basename + "-" + System.currentTimeMillis() + "-" + (int) (Math.random() * Integer.MAX_VALUE);
1127 * Checks whether the connection is in the required state.
1130 * The required connection state
1131 * @throws FcpException
1132 * if the connection is not in the required state
1134 private void checkConnected(boolean connected) throws FcpException {
1135 if (this.connected != connected) {
1136 throw new FcpException("Client is " + (connected ? "not" : "already") + " connected.");
1141 * Tells the client that it is now disconnected. This method is called by
1142 * {@link ExtendedFcpAdapter} only.
1144 private void setDisconnected() {
1149 * Implementation of an {@link FcpListener} that can store an
1150 * {@link FcpException} and wait for the arrival of a certain command.
1152 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
1154 private abstract class ExtendedFcpAdapter extends FcpAdapter {
1156 /** The count down latch used to wait for completion. */
1157 protected final CountDownLatch completionLatch = new CountDownLatch(1);
1159 /** The FCP exception, if any. */
1160 protected FcpException fcpException;
1163 * Creates a new extended FCP adapter.
1165 public ExtendedFcpAdapter() {
1170 * Executes the FCP commands in {@link #run()}, wrapping the execution
1171 * and catching exceptions.
1173 * @throws IOException
1174 * if an I/O error occurs
1175 * @throws FcpException
1176 * if an FCP error occurs
1178 @SuppressWarnings("synthetic-access")
1179 public void execute() throws IOException, FcpException {
1180 checkConnected(true);
1181 fcpConnection.addFcpListener(this);
1186 completionLatch.await();
1188 } catch (InterruptedException ie1) {
1189 /* ignore, we’ll loop. */
1192 } catch (IOException ioe1) {
1196 fcpConnection.removeFcpListener(this);
1198 if (fcpException != null) {
1205 * The FCP commands that actually get executed.
1207 * @throws IOException
1208 * if an I/O error occurs
1210 public abstract void run() throws IOException;
1216 public void connectionClosed(FcpConnection fcpConnection, Throwable throwable) {
1217 fcpException = new FcpException("Connection closed", throwable);
1218 completionLatch.countDown();
1225 public void receivedCloseConnectionDuplicateClientName(FcpConnection fcpConnection, CloseConnectionDuplicateClientName closeConnectionDuplicateClientName) {
1226 fcpException = new FcpException("Connection closed, duplicate client name");
1227 completionLatch.countDown();
1234 public void receivedProtocolError(FcpConnection fcpConnection, ProtocolError protocolError) {
1235 fcpException = new FcpException("Protocol error (" + protocolError.getCode() + ", " + protocolError.getCodeDescription());
1236 completionLatch.countDown();