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;
85 * Creates an FCP client with the given name.
88 * The name of the FCP client
89 * @throws UnknownHostException
90 * if the hostname “localhost” is unknown
92 public FcpClient(String name) throws UnknownHostException {
93 this(name, "localhost");
97 * Creates an FCP client.
100 * The name of the FCP client
102 * The hostname of the Freenet node
103 * @throws UnknownHostException
104 * if the given hostname can not be resolved
106 public FcpClient(String name, String hostname) throws UnknownHostException {
107 this(name, hostname, FcpConnection.DEFAULT_PORT);
111 * Creates an FCP client.
114 * The name of the FCP client
116 * The hostname of the Freenet node
118 * The Freenet node’s FCP port
119 * @throws UnknownHostException
120 * if the given hostname can not be resolved
122 public FcpClient(String name, String hostname, int port) throws UnknownHostException {
123 this(name, InetAddress.getByName(hostname), port);
127 * Creates an FCP client.
130 * The name of the FCP client
132 * The host address of the Freenet node
134 public FcpClient(String name, InetAddress host) {
135 this(name, host, FcpConnection.DEFAULT_PORT);
139 * Creates an FCP client.
142 * The name of the FCP client
144 * The host address of the Freenet node
146 * The Freenet node’s FCP port
148 public FcpClient(String name, InetAddress host, int port) {
150 fcpConnection = new FcpConnection(host, port);
158 * Connects the FCP client.
160 * @throws IOException
161 * if an I/O error occurs
162 * @throws FcpException
163 * if an FCP error occurs
165 public void connect() throws IOException, FcpException {
166 new ExtendedFcpAdapter() {
172 @SuppressWarnings("synthetic-access")
173 public void run() throws IOException {
174 fcpConnection.connect();
175 ClientHello clientHello = new ClientHello(name);
176 fcpConnection.sendMessage(clientHello);
177 WatchGlobal watchGlobal = new WatchGlobal(true);
178 fcpConnection.sendMessage(watchGlobal);
185 public void receivedNodeHello(FcpConnection fcpConnection, NodeHello nodeHello) {
186 completionLatch.countDown();
192 * Disconnects the FCP client.
194 public void disconnect() {
195 synchronized (syncObject) {
196 fcpConnection.close();
197 syncObject.notifyAll();
206 * Returns all peers that the node has.
208 * @param withMetadata
209 * <code>true</code> to include peer metadata
210 * @param withVolatile
211 * <code>true</code> to include volatile peer data
212 * @return A set containing the node’s peers
213 * @throws IOException
214 * if an I/O error occurs
215 * @throws FcpException
216 * if an FCP error occurs
218 public Collection<Peer> getPeers(final boolean withMetadata, final boolean withVolatile) throws IOException, FcpException {
219 final Set<Peer> peers = Collections.synchronizedSet(new HashSet<Peer>());
220 new ExtendedFcpAdapter() {
222 /** The ID of the “ListPeers” request. */
223 @SuppressWarnings("synthetic-access")
224 private String identifier = createIdentifier("list-peers");
230 @SuppressWarnings("synthetic-access")
231 public void run() throws IOException {
232 fcpConnection.sendMessage(new ListPeers(identifier, withMetadata, withVolatile));
239 public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
240 if (peer.getIdentifier().equals(identifier)) {
249 public void receivedEndListPeers(FcpConnection fcpConnection, EndListPeers endListPeers) {
250 if (endListPeers.getIdentifier().equals(identifier)) {
251 completionLatch.countDown();
259 * Returns all darknet peers.
261 * @param withMetadata
262 * <code>true</code> to include peer metadata
263 * @param withVolatile
264 * <code>true</code> to include volatile peer data
265 * @return A set containing the node’s darknet peers
266 * @throws IOException
267 * if an I/O error occurs
268 * @throws FcpException
269 * if an FCP error occurs
271 public Collection<Peer> getDarknetPeers(boolean withMetadata, boolean withVolatile) throws IOException, FcpException {
272 Collection<Peer> allPeers = getPeers(withMetadata, withVolatile);
273 Collection<Peer> darknetPeers = new HashSet<Peer>();
274 for (Peer peer : allPeers) {
275 if (!peer.isOpennet() && !peer.isSeed()) {
276 darknetPeers.add(peer);
283 * Returns all opennet peers.
285 * @param withMetadata
286 * <code>true</code> to include peer metadata
287 * @param withVolatile
288 * <code>true</code> to include volatile peer data
289 * @return A set containing the node’s opennet peers
290 * @throws IOException
291 * if an I/O error occurs
292 * @throws FcpException
293 * if an FCP error occurs
295 public Collection<Peer> getOpennetPeers(boolean withMetadata, boolean withVolatile) throws IOException, FcpException {
296 Collection<Peer> allPeers = getPeers(withMetadata, withVolatile);
297 Collection<Peer> opennetPeers = new HashSet<Peer>();
298 for (Peer peer : allPeers) {
299 if (peer.isOpennet() && !peer.isSeed()) {
300 opennetPeers.add(peer);
307 * Returns all seed peers.
309 * @param withMetadata
310 * <code>true</code> to include peer metadata
311 * @param withVolatile
312 * <code>true</code> to include volatile peer data
313 * @return A set containing the node’s seed peers
314 * @throws IOException
315 * if an I/O error occurs
316 * @throws FcpException
317 * if an FCP error occurs
319 public Collection<Peer> getSeedPeers(boolean withMetadata, boolean withVolatile) throws IOException, FcpException {
320 Collection<Peer> allPeers = getPeers(withMetadata, withVolatile);
321 Collection<Peer> seedPeers = new HashSet<Peer>();
322 for (Peer peer : allPeers) {
331 * Adds the given peer to the node.
335 * @throws IOException
336 * if an I/O error occurs
337 * @throws FcpException
338 * if an FCP error occurs
340 public void addPeer(Peer peer) throws IOException, FcpException {
341 addPeer(peer.getNodeRef());
345 * Adds the peer defined by the noderef to the node.
348 * The noderef that defines the new peer
349 * @throws IOException
350 * if an I/O error occurs
351 * @throws FcpException
352 * if an FCP error occurs
354 public void addPeer(NodeRef nodeRef) throws IOException, FcpException {
355 addPeer(new AddPeer(nodeRef));
359 * Adds a peer, reading the noderef from the given URL.
362 * The URL to read the noderef from
363 * @throws IOException
364 * if an I/O error occurs
365 * @throws FcpException
366 * if an FCP error occurs
368 public void addPeer(URL url) throws IOException, FcpException {
369 addPeer(new AddPeer(url));
373 * Adds a peer, reading the noderef of the peer from the given file.
374 * <strong>Note:</strong> the file to read the noderef from has to reside on
375 * the same machine as the node!
378 * The name of the file containing the peer’s noderef
379 * @throws IOException
380 * if an I/O error occurs
381 * @throws FcpException
382 * if an FCP error occurs
384 public void addPeer(String file) throws IOException, FcpException {
385 addPeer(new AddPeer(file));
389 * Sends the given {@link AddPeer} message to the node. This method should
390 * not be called directly. Use one of {@link #addPeer(Peer)},
391 * {@link #addPeer(NodeRef)}, {@link #addPeer(URL)}, or
392 * {@link #addPeer(String)} instead.
395 * The “AddPeer” message
396 * @throws IOException
397 * if an I/O error occurs
398 * @throws FcpException
399 * if an FCP error occurs
401 private void addPeer(final AddPeer addPeer) throws IOException, FcpException {
402 new ExtendedFcpAdapter() {
408 @SuppressWarnings("synthetic-access")
409 public void run() throws IOException {
410 fcpConnection.sendMessage(addPeer);
417 public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
418 completionLatch.countDown();
424 * Modifies the given peer.
428 * @param allowLocalAddresses
429 * <code>true</code> to allow local address, <code>false</code>
430 * to not allow local address, <code>null</code> to not change
433 * <code>true</code> to disable the peer, <code>false</code> to
434 * enable the peer, <code>null</code> to not change the setting
436 * <code>true</code> to enable “listen only” for the peer,
437 * <code>false</code> to disable it, <code>null</code> to not
439 * @throws IOException
440 * if an I/O error occurs
441 * @throws FcpException
442 * if an FCP error occurs
444 public void modifyPeer(final Peer peer, final Boolean allowLocalAddresses, final Boolean disabled, final Boolean listenOnly) throws IOException, FcpException {
445 new ExtendedFcpAdapter() {
451 @SuppressWarnings("synthetic-access")
452 public void run() throws IOException {
453 fcpConnection.sendMessage(new ModifyPeer(peer.getIdentity(), allowLocalAddresses, disabled, listenOnly));
460 public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
461 completionLatch.countDown();
467 * Removes the given peer.
471 * @throws IOException
472 * if an I/O error occurs
473 * @throws FcpException
474 * if an FCP error occurs
476 public void removePeer(final Peer peer) throws IOException, FcpException {
477 new ExtendedFcpAdapter() {
483 @SuppressWarnings("synthetic-access")
484 public void run() throws IOException {
485 fcpConnection.sendMessage(new RemovePeer(peer.getIdentity()));
492 public void receivedPeerRemoved(FcpConnection fcpConnection, PeerRemoved peerRemoved) {
493 completionLatch.countDown();
499 // PEER NOTES MANAGEMENT
503 * Returns the peer note of the given peer.
506 * The peer to get the note for
507 * @return The peer’s note
508 * @throws IOException
509 * if an I/O error occurs
510 * @throws FcpException
511 * if an FCP error occurs
513 public PeerNote getPeerNote(final Peer peer) throws IOException, FcpException {
514 final ObjectWrapper<PeerNote> objectWrapper = new ObjectWrapper<PeerNote>();
515 new ExtendedFcpAdapter() {
521 @SuppressWarnings("synthetic-access")
522 public void run() throws IOException {
523 fcpConnection.sendMessage(new ListPeerNotes(peer.getIdentity()));
530 public void receivedPeerNote(FcpConnection fcpConnection, PeerNote peerNote) {
531 if (peerNote.getNodeIdentifier().equals(peer.getIdentity())) {
532 objectWrapper.set(peerNote);
540 public void receivedEndListPeerNotes(FcpConnection fcpConnection, EndListPeerNotes endListPeerNotes) {
541 completionLatch.countDown();
544 return objectWrapper.get();
548 * Replaces the peer note for the given peer.
553 * The new base64-encoded note text
555 * The type of the note (currently only <code>1</code> is
557 * @throws IOException
558 * if an I/O error occurs
559 * @throws FcpException
560 * if an FCP error occurs
562 public void modifyPeerNote(final Peer peer, final String noteText, final int noteType) throws IOException, FcpException {
563 new ExtendedFcpAdapter() {
569 @SuppressWarnings("synthetic-access")
570 public void run() throws IOException {
571 fcpConnection.sendMessage(new ModifyPeerNote(peer.getIdentity(), noteText, noteType));
578 public void receivedPeer(FcpConnection fcpConnection, Peer receivedPeer) {
579 if (receivedPeer.getIdentity().equals(peer.getIdentity())) {
580 completionLatch.countDown();
591 * Generates a new SSK key pair.
593 * @return The generated key pair
594 * @throws IOException
595 * if an I/O error occurs
596 * @throws FcpException
597 * if an FCP error occurs
599 public SSKKeypair generateKeyPair() throws IOException, FcpException {
600 final ObjectWrapper<SSKKeypair> sskKeypairWrapper = new ObjectWrapper<SSKKeypair>();
601 new ExtendedFcpAdapter() {
607 @SuppressWarnings("synthetic-access")
608 public void run() throws IOException {
609 fcpConnection.sendMessage(new GenerateSSK());
616 public void receivedSSKKeypair(FcpConnection fcpConnection, SSKKeypair sskKeypair) {
617 sskKeypairWrapper.set(sskKeypair);
618 completionLatch.countDown();
621 return sskKeypairWrapper.get();
625 // REQUEST MANAGEMENT
629 * Returns all currently visible persistent get requests.
632 * <code>true</code> to return get requests from the global
633 * queue, <code>false</code> to only show requests from the
635 * @return All get requests
636 * @throws IOException
637 * if an I/O error occurs
638 * @throws FcpException
639 * if an FCP error occurs
641 public Collection<Request> getGetRequests(final boolean global) throws IOException, FcpException {
642 return Filters.filteredCollection(getRequests(global), new Filter<Request>() {
647 public boolean filterObject(Request request) {
648 return request instanceof GetRequest;
654 * Returns all currently visible persistent put requests.
657 * <code>true</code> to return put requests from the global
658 * queue, <code>false</code> to only show requests from the
660 * @return All put requests
661 * @throws IOException
662 * if an I/O error occurs
663 * @throws FcpException
664 * if an FCP error occurs
666 public Collection<Request> getPutRequests(final boolean global) throws IOException, FcpException {
667 return Filters.filteredCollection(getRequests(global), new Filter<Request>() {
672 public boolean filterObject(Request request) {
673 return request instanceof PutRequest;
679 * Returns all currently visible persistent requests.
682 * <code>true</code> to return requests from the global queue,
683 * <code>false</code> to only show requests from the client-local
685 * @return All requests
686 * @throws IOException
687 * if an I/O error occurs
688 * @throws FcpException
689 * if an FCP error occurs
691 public Collection<Request> getRequests(final boolean global) throws IOException, FcpException {
692 final Map<String, Request> requests = Collections.synchronizedMap(new HashMap<String, Request>());
693 new ExtendedFcpAdapter() {
699 @SuppressWarnings("synthetic-access")
700 public void run() throws IOException {
701 fcpConnection.sendMessage(new ListPersistentRequests());
708 public void receivedPersistentGet(FcpConnection fcpConnection, PersistentGet persistentGet) {
709 if (!persistentGet.isGlobal() || global) {
710 GetRequest getRequest = new GetRequest(persistentGet);
711 requests.put(persistentGet.getIdentifier(), getRequest);
718 * @see net.pterodactylus.fcp.FcpAdapter#receivedDataFound(net.pterodactylus.fcp.FcpConnection,
719 * net.pterodactylus.fcp.DataFound)
722 public void receivedDataFound(FcpConnection fcpConnection, DataFound dataFound) {
723 Request getRequest = requests.get(dataFound.getIdentifier());
724 if (getRequest == null) {
727 getRequest.setComplete(true);
728 getRequest.setLength(dataFound.getDataLength());
729 getRequest.setContentType(dataFound.getMetadataContentType());
735 * @see net.pterodactylus.fcp.FcpAdapter#receivedGetFailed(net.pterodactylus.fcp.FcpConnection,
736 * net.pterodactylus.fcp.GetFailed)
739 public void receivedGetFailed(FcpConnection fcpConnection, GetFailed getFailed) {
740 Request getRequest = requests.get(getFailed.getIdentifier());
741 if (getRequest == null) {
744 getRequest.setComplete(true);
745 getRequest.setFailed(true);
746 getRequest.setFatal(getFailed.isFatal());
747 getRequest.setErrorCode(getFailed.getCode());
753 * @see net.pterodactylus.fcp.FcpAdapter#receivedPersistentPut(net.pterodactylus.fcp.FcpConnection,
754 * net.pterodactylus.fcp.PersistentPut)
757 public void receivedPersistentPut(FcpConnection fcpConnection, PersistentPut persistentPut) {
758 if (!persistentPut.isGlobal() || global) {
759 PutRequest putRequest = new PutRequest(persistentPut);
760 requests.put(persistentPut.getIdentifier(), putRequest);
767 * @see net.pterodactylus.fcp.FcpAdapter#receivedSimpleProgress(net.pterodactylus.fcp.FcpConnection,
768 * net.pterodactylus.fcp.SimpleProgress)
771 public void receivedSimpleProgress(FcpConnection fcpConnection, SimpleProgress simpleProgress) {
772 Request request = requests.get(simpleProgress.getIdentifier());
773 if (request == null) {
776 request.setTotalBlocks(simpleProgress.getTotal());
777 request.setRequiredBlocks(simpleProgress.getRequired());
778 request.setFailedBlocks(simpleProgress.getFailed());
779 request.setFatallyFailedBlocks(simpleProgress.getFatallyFailed());
780 request.setSucceededBlocks(simpleProgress.getSucceeded());
781 request.setFinalizedTotal(simpleProgress.isFinalizedTotal());
788 public void receivedEndListPersistentRequests(FcpConnection fcpConnection, EndListPersistentRequests endListPersistentRequests) {
789 completionLatch.countDown();
792 return requests.values();
800 * Creates a unique request identifier.
803 * The basename of the request
804 * @return The created request identifier
806 private String createIdentifier(String basename) {
807 return basename + "-" + System.currentTimeMillis() + "-" + (int) (Math.random() * Integer.MAX_VALUE);
811 * Implementation of an {@link FcpListener} that can store an
812 * {@link FcpException} and wait for the arrival of a certain command.
814 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
816 private abstract class ExtendedFcpAdapter extends FcpAdapter {
818 /** The count down latch used to wait for completion. */
819 protected final CountDownLatch completionLatch = new CountDownLatch(1);
821 /** The FCP exception, if any. */
822 protected FcpException fcpException;
825 * Creates a new extended FCP adapter.
827 public ExtendedFcpAdapter() {
832 * Executes the FCP commands in {@link #run()}, wrapping the execution
833 * and catching exceptions.
835 * @throws IOException
836 * if an I/O error occurs
837 * @throws FcpException
838 * if an FCP error occurs
840 @SuppressWarnings("synthetic-access")
841 public void execute() throws IOException, FcpException {
842 fcpConnection.addFcpListener(this);
847 completionLatch.await();
849 } catch (InterruptedException ie1) {
850 /* ignore, we’ll loop. */
854 fcpConnection.removeFcpListener(this);
856 if (fcpException != null) {
862 * The FCP commands that actually get executed.
864 * @throws IOException
865 * if an I/O error occurs
867 public abstract void run() throws IOException;
873 public void connectionClosed(FcpConnection fcpConnection, Throwable throwable) {
874 fcpException = new FcpException("Connection closed", throwable);
875 completionLatch.countDown();
882 public void receivedCloseConnectionDuplicateClientName(FcpConnection fcpConnection, CloseConnectionDuplicateClientName closeConnectionDuplicateClientName) {
883 fcpException = new FcpException("Connection closed, duplicate client name");
884 completionLatch.countDown();
891 public void receivedProtocolError(FcpConnection fcpConnection, ProtocolError protocolError) {
892 fcpException = new FcpException("Protocol error (" + protocolError.getCode() + ", " + protocolError.getCodeDescription());
893 completionLatch.countDown();