2 * jFCPlib - FcpClient.java -
3 * Copyright © 2009 David Roden
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 package net.pterodactylus.fcp.highlevel;
22 import java.io.IOException;
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;
32 import java.util.concurrent.CountDownLatch;
34 import net.pterodactylus.fcp.AddPeer;
35 import net.pterodactylus.fcp.ClientHello;
36 import net.pterodactylus.fcp.CloseConnectionDuplicateClientName;
37 import net.pterodactylus.fcp.DataFound;
38 import net.pterodactylus.fcp.EndListPeerNotes;
39 import net.pterodactylus.fcp.EndListPeers;
40 import net.pterodactylus.fcp.EndListPersistentRequests;
41 import net.pterodactylus.fcp.FcpAdapter;
42 import net.pterodactylus.fcp.FcpConnection;
43 import net.pterodactylus.fcp.FcpListener;
44 import net.pterodactylus.fcp.GenerateSSK;
45 import net.pterodactylus.fcp.GetFailed;
46 import net.pterodactylus.fcp.ListPeerNotes;
47 import net.pterodactylus.fcp.ListPeers;
48 import net.pterodactylus.fcp.ListPersistentRequests;
49 import net.pterodactylus.fcp.ModifyPeer;
50 import net.pterodactylus.fcp.ModifyPeerNote;
51 import net.pterodactylus.fcp.NodeHello;
52 import net.pterodactylus.fcp.NodeRef;
53 import net.pterodactylus.fcp.Peer;
54 import net.pterodactylus.fcp.PeerNote;
55 import net.pterodactylus.fcp.PeerRemoved;
56 import net.pterodactylus.fcp.PersistentGet;
57 import net.pterodactylus.fcp.PersistentPut;
58 import net.pterodactylus.fcp.ProtocolError;
59 import net.pterodactylus.fcp.RemovePeer;
60 import net.pterodactylus.fcp.SSKKeypair;
61 import net.pterodactylus.fcp.SimpleProgress;
62 import net.pterodactylus.fcp.WatchGlobal;
63 import net.pterodactylus.util.filter.Filter;
64 import net.pterodactylus.util.filter.Filters;
65 import net.pterodactylus.util.thread.ObjectWrapper;
68 * High-level FCP client that hides the details of the underlying FCP
71 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
73 public class FcpClient {
75 /** Object used for synchronization. */
76 private final Object syncObject = new Object();
78 /** The name of this client. */
79 private final String name;
81 /** The underlying FCP connection. */
82 private final FcpConnection fcpConnection;
84 /** Whether the client is currently connected. */
85 private volatile boolean connected;
88 * Creates an FCP client with the given name.
91 * The name of the FCP client
92 * @throws UnknownHostException
93 * if the hostname “localhost” is unknown
95 public FcpClient(String name) throws UnknownHostException {
96 this(name, "localhost");
100 * Creates an FCP client.
103 * The name of the FCP client
105 * The hostname of the Freenet node
106 * @throws UnknownHostException
107 * if the given hostname can not be resolved
109 public FcpClient(String name, String hostname) throws UnknownHostException {
110 this(name, hostname, FcpConnection.DEFAULT_PORT);
114 * Creates an FCP client.
117 * The name of the FCP client
119 * The hostname of the Freenet node
121 * The Freenet node’s FCP port
122 * @throws UnknownHostException
123 * if the given hostname can not be resolved
125 public FcpClient(String name, String hostname, int port) throws UnknownHostException {
126 this(name, InetAddress.getByName(hostname), port);
130 * Creates an FCP client.
133 * The name of the FCP client
135 * The host address of the Freenet node
137 public FcpClient(String name, InetAddress host) {
138 this(name, host, FcpConnection.DEFAULT_PORT);
142 * Creates an FCP client.
145 * The name of the FCP client
147 * The host address of the Freenet node
149 * The Freenet node’s FCP port
151 public FcpClient(String name, InetAddress host, int port) {
153 fcpConnection = new FcpConnection(host, port);
161 * Connects the FCP client.
163 * @throws IOException
164 * if an I/O error occurs
165 * @throws FcpException
166 * if an FCP error occurs
168 public void connect() throws IOException, FcpException {
169 checkConnected(false);
171 new ExtendedFcpAdapter() {
177 @SuppressWarnings("synthetic-access")
178 public void run() throws IOException {
179 fcpConnection.connect();
180 ClientHello clientHello = new ClientHello(name);
181 fcpConnection.sendMessage(clientHello);
182 WatchGlobal watchGlobal = new WatchGlobal(true);
183 fcpConnection.sendMessage(watchGlobal);
190 public void receivedNodeHello(FcpConnection fcpConnection, NodeHello nodeHello) {
191 completionLatch.countDown();
197 * Disconnects the FCP client.
199 public void disconnect() {
200 synchronized (syncObject) {
201 fcpConnection.close();
202 syncObject.notifyAll();
211 * Returns all peers that the node has.
213 * @param withMetadata
214 * <code>true</code> to include peer metadata
215 * @param withVolatile
216 * <code>true</code> to include volatile peer data
217 * @return A set containing the node’s peers
218 * @throws IOException
219 * if an I/O error occurs
220 * @throws FcpException
221 * if an FCP error occurs
223 public Collection<Peer> getPeers(final boolean withMetadata, final boolean withVolatile) throws IOException, FcpException {
224 final Set<Peer> peers = Collections.synchronizedSet(new HashSet<Peer>());
225 new ExtendedFcpAdapter() {
227 /** The ID of the “ListPeers” request. */
228 @SuppressWarnings("synthetic-access")
229 private String identifier = createIdentifier("list-peers");
235 @SuppressWarnings("synthetic-access")
236 public void run() throws IOException {
237 fcpConnection.sendMessage(new ListPeers(identifier, withMetadata, withVolatile));
244 public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
245 if (peer.getIdentifier().equals(identifier)) {
254 public void receivedEndListPeers(FcpConnection fcpConnection, EndListPeers endListPeers) {
255 if (endListPeers.getIdentifier().equals(identifier)) {
256 completionLatch.countDown();
264 * Returns all darknet peers.
266 * @param withMetadata
267 * <code>true</code> to include peer metadata
268 * @param withVolatile
269 * <code>true</code> to include volatile peer data
270 * @return A set containing the node’s darknet peers
271 * @throws IOException
272 * if an I/O error occurs
273 * @throws FcpException
274 * if an FCP error occurs
276 public Collection<Peer> getDarknetPeers(boolean withMetadata, boolean withVolatile) throws IOException, FcpException {
277 Collection<Peer> allPeers = getPeers(withMetadata, withVolatile);
278 Collection<Peer> darknetPeers = new HashSet<Peer>();
279 for (Peer peer : allPeers) {
280 if (!peer.isOpennet() && !peer.isSeed()) {
281 darknetPeers.add(peer);
288 * Returns all opennet peers.
290 * @param withMetadata
291 * <code>true</code> to include peer metadata
292 * @param withVolatile
293 * <code>true</code> to include volatile peer data
294 * @return A set containing the node’s opennet peers
295 * @throws IOException
296 * if an I/O error occurs
297 * @throws FcpException
298 * if an FCP error occurs
300 public Collection<Peer> getOpennetPeers(boolean withMetadata, boolean withVolatile) throws IOException, FcpException {
301 Collection<Peer> allPeers = getPeers(withMetadata, withVolatile);
302 Collection<Peer> opennetPeers = new HashSet<Peer>();
303 for (Peer peer : allPeers) {
304 if (peer.isOpennet() && !peer.isSeed()) {
305 opennetPeers.add(peer);
312 * Returns all seed peers.
314 * @param withMetadata
315 * <code>true</code> to include peer metadata
316 * @param withVolatile
317 * <code>true</code> to include volatile peer data
318 * @return A set containing the node’s seed peers
319 * @throws IOException
320 * if an I/O error occurs
321 * @throws FcpException
322 * if an FCP error occurs
324 public Collection<Peer> getSeedPeers(boolean withMetadata, boolean withVolatile) throws IOException, FcpException {
325 Collection<Peer> allPeers = getPeers(withMetadata, withVolatile);
326 Collection<Peer> seedPeers = new HashSet<Peer>();
327 for (Peer peer : allPeers) {
336 * Adds the given peer to the node.
340 * @throws IOException
341 * if an I/O error occurs
342 * @throws FcpException
343 * if an FCP error occurs
345 public void addPeer(Peer peer) throws IOException, FcpException {
346 addPeer(peer.getNodeRef());
350 * Adds the peer defined by the noderef to the node.
353 * The noderef that defines the new peer
354 * @throws IOException
355 * if an I/O error occurs
356 * @throws FcpException
357 * if an FCP error occurs
359 public void addPeer(NodeRef nodeRef) throws IOException, FcpException {
360 addPeer(new AddPeer(nodeRef));
364 * Adds a peer, reading the noderef from the given URL.
367 * The URL to read the noderef from
368 * @throws IOException
369 * if an I/O error occurs
370 * @throws FcpException
371 * if an FCP error occurs
373 public void addPeer(URL url) throws IOException, FcpException {
374 addPeer(new AddPeer(url));
378 * Adds a peer, reading the noderef of the peer from the given file.
379 * <strong>Note:</strong> the file to read the noderef from has to reside on
380 * the same machine as the node!
383 * The name of the file containing the peer’s noderef
384 * @throws IOException
385 * if an I/O error occurs
386 * @throws FcpException
387 * if an FCP error occurs
389 public void addPeer(String file) throws IOException, FcpException {
390 addPeer(new AddPeer(file));
394 * Sends the given {@link AddPeer} message to the node. This method should
395 * not be called directly. Use one of {@link #addPeer(Peer)},
396 * {@link #addPeer(NodeRef)}, {@link #addPeer(URL)}, or
397 * {@link #addPeer(String)} instead.
400 * The “AddPeer” message
401 * @throws IOException
402 * if an I/O error occurs
403 * @throws FcpException
404 * if an FCP error occurs
406 private void addPeer(final AddPeer addPeer) throws IOException, FcpException {
407 new ExtendedFcpAdapter() {
413 @SuppressWarnings("synthetic-access")
414 public void run() throws IOException {
415 fcpConnection.sendMessage(addPeer);
422 public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
423 completionLatch.countDown();
429 * Modifies the given peer.
433 * @param allowLocalAddresses
434 * <code>true</code> to allow local address, <code>false</code>
435 * to not allow local address, <code>null</code> to not change
438 * <code>true</code> to disable the peer, <code>false</code> to
439 * enable the peer, <code>null</code> to not change the setting
441 * <code>true</code> to enable “listen only” for the peer,
442 * <code>false</code> to disable it, <code>null</code> to not
444 * @throws IOException
445 * if an I/O error occurs
446 * @throws FcpException
447 * if an FCP error occurs
449 public void modifyPeer(final Peer peer, final Boolean allowLocalAddresses, final Boolean disabled, final Boolean listenOnly) throws IOException, FcpException {
450 new ExtendedFcpAdapter() {
456 @SuppressWarnings("synthetic-access")
457 public void run() throws IOException {
458 fcpConnection.sendMessage(new ModifyPeer(peer.getIdentity(), allowLocalAddresses, disabled, listenOnly));
465 public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
466 completionLatch.countDown();
472 * Removes the given peer.
476 * @throws IOException
477 * if an I/O error occurs
478 * @throws FcpException
479 * if an FCP error occurs
481 public void removePeer(final Peer peer) throws IOException, FcpException {
482 new ExtendedFcpAdapter() {
488 @SuppressWarnings("synthetic-access")
489 public void run() throws IOException {
490 fcpConnection.sendMessage(new RemovePeer(peer.getIdentity()));
497 public void receivedPeerRemoved(FcpConnection fcpConnection, PeerRemoved peerRemoved) {
498 completionLatch.countDown();
504 // PEER NOTES MANAGEMENT
508 * Returns the peer note of the given peer.
511 * The peer to get the note for
512 * @return The peer’s note
513 * @throws IOException
514 * if an I/O error occurs
515 * @throws FcpException
516 * if an FCP error occurs
518 public PeerNote getPeerNote(final Peer peer) throws IOException, FcpException {
519 final ObjectWrapper<PeerNote> objectWrapper = new ObjectWrapper<PeerNote>();
520 new ExtendedFcpAdapter() {
526 @SuppressWarnings("synthetic-access")
527 public void run() throws IOException {
528 fcpConnection.sendMessage(new ListPeerNotes(peer.getIdentity()));
535 public void receivedPeerNote(FcpConnection fcpConnection, PeerNote peerNote) {
536 if (peerNote.getNodeIdentifier().equals(peer.getIdentity())) {
537 objectWrapper.set(peerNote);
545 public void receivedEndListPeerNotes(FcpConnection fcpConnection, EndListPeerNotes endListPeerNotes) {
546 completionLatch.countDown();
549 return objectWrapper.get();
553 * Replaces the peer note for the given peer.
558 * The new base64-encoded note text
560 * The type of the note (currently only <code>1</code> is
562 * @throws IOException
563 * if an I/O error occurs
564 * @throws FcpException
565 * if an FCP error occurs
567 public void modifyPeerNote(final Peer peer, final String noteText, final int noteType) throws IOException, FcpException {
568 new ExtendedFcpAdapter() {
574 @SuppressWarnings("synthetic-access")
575 public void run() throws IOException {
576 fcpConnection.sendMessage(new ModifyPeerNote(peer.getIdentity(), noteText, noteType));
583 public void receivedPeer(FcpConnection fcpConnection, Peer receivedPeer) {
584 if (receivedPeer.getIdentity().equals(peer.getIdentity())) {
585 completionLatch.countDown();
596 * Generates a new SSK key pair.
598 * @return The generated key pair
599 * @throws IOException
600 * if an I/O error occurs
601 * @throws FcpException
602 * if an FCP error occurs
604 public SSKKeypair generateKeyPair() throws IOException, FcpException {
605 final ObjectWrapper<SSKKeypair> sskKeypairWrapper = new ObjectWrapper<SSKKeypair>();
606 new ExtendedFcpAdapter() {
612 @SuppressWarnings("synthetic-access")
613 public void run() throws IOException {
614 fcpConnection.sendMessage(new GenerateSSK());
621 public void receivedSSKKeypair(FcpConnection fcpConnection, SSKKeypair sskKeypair) {
622 sskKeypairWrapper.set(sskKeypair);
623 completionLatch.countDown();
626 return sskKeypairWrapper.get();
630 // REQUEST MANAGEMENT
634 * Returns all currently visible persistent get requests.
637 * <code>true</code> to return get requests from the global
638 * queue, <code>false</code> to only show requests from the
640 * @return All get requests
641 * @throws IOException
642 * if an I/O error occurs
643 * @throws FcpException
644 * if an FCP error occurs
646 public Collection<Request> getGetRequests(final boolean global) throws IOException, FcpException {
647 return Filters.filteredCollection(getRequests(global), new Filter<Request>() {
652 public boolean filterObject(Request request) {
653 return request instanceof GetRequest;
659 * Returns all currently visible persistent put requests.
662 * <code>true</code> to return put requests from the global
663 * queue, <code>false</code> to only show requests from the
665 * @return All put requests
666 * @throws IOException
667 * if an I/O error occurs
668 * @throws FcpException
669 * if an FCP error occurs
671 public Collection<Request> getPutRequests(final boolean global) throws IOException, FcpException {
672 return Filters.filteredCollection(getRequests(global), new Filter<Request>() {
677 public boolean filterObject(Request request) {
678 return request instanceof PutRequest;
684 * Returns all currently visible persistent requests.
687 * <code>true</code> to return requests from the global queue,
688 * <code>false</code> to only show requests from the client-local
690 * @return All requests
691 * @throws IOException
692 * if an I/O error occurs
693 * @throws FcpException
694 * if an FCP error occurs
696 public Collection<Request> getRequests(final boolean global) throws IOException, FcpException {
697 final Map<String, Request> requests = Collections.synchronizedMap(new HashMap<String, Request>());
698 new ExtendedFcpAdapter() {
704 @SuppressWarnings("synthetic-access")
705 public void run() throws IOException {
706 fcpConnection.sendMessage(new ListPersistentRequests());
713 public void receivedPersistentGet(FcpConnection fcpConnection, PersistentGet persistentGet) {
714 if (!persistentGet.isGlobal() || global) {
715 GetRequest getRequest = new GetRequest(persistentGet);
716 requests.put(persistentGet.getIdentifier(), getRequest);
723 * @see net.pterodactylus.fcp.FcpAdapter#receivedDataFound(net.pterodactylus.fcp.FcpConnection,
724 * net.pterodactylus.fcp.DataFound)
727 public void receivedDataFound(FcpConnection fcpConnection, DataFound dataFound) {
728 Request getRequest = requests.get(dataFound.getIdentifier());
729 if (getRequest == null) {
732 getRequest.setComplete(true);
733 getRequest.setLength(dataFound.getDataLength());
734 getRequest.setContentType(dataFound.getMetadataContentType());
740 * @see net.pterodactylus.fcp.FcpAdapter#receivedGetFailed(net.pterodactylus.fcp.FcpConnection,
741 * net.pterodactylus.fcp.GetFailed)
744 public void receivedGetFailed(FcpConnection fcpConnection, GetFailed getFailed) {
745 Request getRequest = requests.get(getFailed.getIdentifier());
746 if (getRequest == null) {
749 getRequest.setComplete(true);
750 getRequest.setFailed(true);
751 getRequest.setFatal(getFailed.isFatal());
752 getRequest.setErrorCode(getFailed.getCode());
758 * @see net.pterodactylus.fcp.FcpAdapter#receivedPersistentPut(net.pterodactylus.fcp.FcpConnection,
759 * net.pterodactylus.fcp.PersistentPut)
762 public void receivedPersistentPut(FcpConnection fcpConnection, PersistentPut persistentPut) {
763 if (!persistentPut.isGlobal() || global) {
764 PutRequest putRequest = new PutRequest(persistentPut);
765 requests.put(persistentPut.getIdentifier(), putRequest);
772 * @see net.pterodactylus.fcp.FcpAdapter#receivedSimpleProgress(net.pterodactylus.fcp.FcpConnection,
773 * net.pterodactylus.fcp.SimpleProgress)
776 public void receivedSimpleProgress(FcpConnection fcpConnection, SimpleProgress simpleProgress) {
777 Request request = requests.get(simpleProgress.getIdentifier());
778 if (request == null) {
781 request.setTotalBlocks(simpleProgress.getTotal());
782 request.setRequiredBlocks(simpleProgress.getRequired());
783 request.setFailedBlocks(simpleProgress.getFailed());
784 request.setFatallyFailedBlocks(simpleProgress.getFatallyFailed());
785 request.setSucceededBlocks(simpleProgress.getSucceeded());
786 request.setFinalizedTotal(simpleProgress.isFinalizedTotal());
793 public void receivedEndListPersistentRequests(FcpConnection fcpConnection, EndListPersistentRequests endListPersistentRequests) {
794 completionLatch.countDown();
797 return requests.values();
805 * Creates a unique request identifier.
808 * The basename of the request
809 * @return The created request identifier
811 private String createIdentifier(String basename) {
812 return basename + "-" + System.currentTimeMillis() + "-" + (int) (Math.random() * Integer.MAX_VALUE);
816 * Checks whether the connection is in the required state.
819 * The required connection state
820 * @throws FcpException
821 * if the connection is not in the required state
823 private void checkConnected(boolean connected) throws FcpException {
824 if (this.connected != connected) {
825 throw new FcpException("Client is " + (connected ? "not" : "already") + " connected.");
830 * Tells the client that it is now disconnected. This method is called by
831 * {@link ExtendedFcpAdapter} only.
833 private void setDisconnected() {
838 * Implementation of an {@link FcpListener} that can store an
839 * {@link FcpException} and wait for the arrival of a certain command.
841 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
843 private abstract class ExtendedFcpAdapter extends FcpAdapter {
845 /** The count down latch used to wait for completion. */
846 protected final CountDownLatch completionLatch = new CountDownLatch(1);
848 /** The FCP exception, if any. */
849 protected FcpException fcpException;
852 * Creates a new extended FCP adapter.
854 public ExtendedFcpAdapter() {
859 * Executes the FCP commands in {@link #run()}, wrapping the execution
860 * and catching exceptions.
862 * @throws IOException
863 * if an I/O error occurs
864 * @throws FcpException
865 * if an FCP error occurs
867 @SuppressWarnings("synthetic-access")
868 public void execute() throws IOException, FcpException {
869 checkConnected(true);
870 fcpConnection.addFcpListener(this);
875 completionLatch.await();
877 } catch (InterruptedException ie1) {
878 /* ignore, we’ll loop. */
881 } catch (IOException ioe1) {
885 fcpConnection.removeFcpListener(this);
887 if (fcpException != null) {
894 * The FCP commands that actually get executed.
896 * @throws IOException
897 * if an I/O error occurs
899 public abstract void run() throws IOException;
905 public void connectionClosed(FcpConnection fcpConnection, Throwable throwable) {
906 fcpException = new FcpException("Connection closed", throwable);
907 completionLatch.countDown();
914 public void receivedCloseConnectionDuplicateClientName(FcpConnection fcpConnection, CloseConnectionDuplicateClientName closeConnectionDuplicateClientName) {
915 fcpException = new FcpException("Connection closed, duplicate client name");
916 completionLatch.countDown();
923 public void receivedProtocolError(FcpConnection fcpConnection, ProtocolError protocolError) {
924 fcpException = new FcpException("Protocol error (" + protocolError.getCode() + ", " + protocolError.getCodeDescription());
925 completionLatch.countDown();