3 * Copyright (C) 2006 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 de.todesbaum.util.freenet.fcp2;
23 import java.io.FileOutputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.OutputStream;
27 import java.io.OutputStreamWriter;
28 import java.io.Writer;
29 import java.net.Socket;
30 import java.nio.charset.Charset;
31 import java.util.ArrayList;
32 import java.util.List;
34 import de.todesbaum.util.io.Closer;
35 import de.todesbaum.util.io.LineInputStream;
36 import de.todesbaum.util.io.StreamCopier;
37 import de.todesbaum.util.io.TempFileInputStream;
40 * A physical connection to a Freenet node.
42 * @author David Roden <droden@gmail.com>
45 public class Connection {
47 /** The listeners that receive events from this connection. */
48 private List<ConnectionListener> connectionListeners = new ArrayList<ConnectionListener>();
50 /** The node this connection is connected to. */
51 private final Node node;
53 /** The name of this connection. */
54 private final String name;
56 /** The network socket of this connection. */
57 private Socket nodeSocket;
59 /** The input stream that reads from the socket. */
60 private InputStream nodeInputStream;
62 /** The output stream that writes to the socket. */
63 private OutputStream nodeOutputStream;
65 /** The thread that reads from the socket. */
66 private NodeReader nodeReader;
68 /** A writer for the output stream. */
69 private Writer nodeWriter;
71 /** The NodeHello message sent by the node on connect. */
72 protected Message nodeHello;
74 /** The temp directory to use. */
75 private String tempDirectory;
78 * Creates a new connection to the specified node with the specified name.
81 * The node to connect to
83 * The name of this connection
85 public Connection(Node node, String name) {
91 * Adds a listener that gets notified on connection events.
93 * @param connectionListener
96 public void addConnectionListener(ConnectionListener connectionListener) {
97 connectionListeners.add(connectionListener);
101 * Removes a listener from the list of registered listeners. Only the first
102 * matching listener is removed.
104 * @param connectionListener
105 * The listener to remove
106 * @see List#remove(java.lang.Object)
108 public void removeConnectionListener(ConnectionListener connectionListener) {
109 connectionListeners.remove(connectionListener);
113 * Notifies listeners about a received message.
116 * The received message
118 protected void fireMessageReceived(Message message) {
119 for (ConnectionListener connectionListener : connectionListeners) {
120 connectionListener.messageReceived(this, message);
125 * Notifies listeners about the loss of the connection.
127 protected void fireConnectionTerminated() {
128 for (ConnectionListener connectionListener : connectionListeners) {
129 connectionListener.connectionTerminated(this);
134 * Returns the name of the connection.
136 * @return The name of the connection
138 public String getName() {
143 * Sets the temp directory to use for creation of temporary files.
145 * @param tempDirectory
146 * The temp directory to use, or {@code null} to use the default
149 public void setTempDirectory(String tempDirectory) {
150 this.tempDirectory = tempDirectory;
154 * Connects to the node.
156 * @return <code>true</code> if the connection succeeded and the node
157 * returned a NodeHello message
158 * @throws IOException
159 * if an I/O error occurs
160 * @see #getNodeHello()
162 public synchronized boolean connect() throws IOException {
164 nodeInputStream = null;
165 nodeOutputStream = null;
169 nodeSocket = new Socket(node.getHostname(), node.getPort());
170 nodeSocket.setReceiveBufferSize(65535);
171 nodeInputStream = nodeSocket.getInputStream();
172 nodeOutputStream = nodeSocket.getOutputStream();
173 nodeWriter = new OutputStreamWriter(nodeOutputStream, Charset.forName("UTF-8"));
174 nodeReader = new NodeReader(nodeInputStream);
175 Thread nodeReaderThread = new Thread(nodeReader);
176 nodeReaderThread.setDaemon(true);
177 nodeReaderThread.start();
178 ClientHello clientHello = new ClientHello();
179 clientHello.setName(name);
180 clientHello.setExpectedVersion("2.0");
181 execute(clientHello);
182 synchronized (this) {
185 } catch (InterruptedException e) {
188 return nodeHello != null;
189 } catch (IOException ioe1) {
196 * Returns whether this connection is still connected to the node.
198 * @return <code>true</code> if this connection is still valid,
199 * <code>false</code> otherwise
201 public boolean isConnected() {
202 return (nodeHello != null) && (nodeSocket != null) && (nodeSocket.isConnected());
206 * Returns the NodeHello message the node sent on connection.
208 * @return The NodeHello message of the node
210 public Message getNodeHello() {
215 * Disconnects from the node.
217 public void disconnect() {
218 if (nodeWriter != null) {
221 } catch (IOException ioe1) {
225 if (nodeOutputStream != null) {
227 nodeOutputStream.close();
228 } catch (IOException ioe1) {
230 nodeOutputStream = null;
232 if (nodeInputStream != null) {
234 nodeInputStream.close();
235 } catch (IOException ioe1) {
237 nodeInputStream = null;
239 if (nodeSocket != null) {
242 } catch (IOException ioe1) {
246 synchronized (this) {
249 fireConnectionTerminated();
253 * Executes the specified command.
256 * The command to execute
257 * @throws IllegalStateException
258 * if the connection is not connected
259 * @throws IOException
260 * if an I/O error occurs
262 public synchronized void execute(Command command) throws IllegalStateException, IOException {
263 if (nodeSocket == null) {
264 throw new IllegalStateException("connection is not connected");
266 nodeWriter.write(command.getCommandName() + Command.LINEFEED);
267 command.write(nodeWriter);
268 nodeWriter.write("EndMessage" + Command.LINEFEED);
270 if (command.hasPayload()) {
271 InputStream payloadInputStream = null;
273 payloadInputStream = command.getPayload();
274 StreamCopier.copy(payloadInputStream, nodeOutputStream, command.getPayloadLength());
276 Closer.close(payloadInputStream);
278 nodeOutputStream.flush();
283 * The reader thread for this connection. This is essentially a thread that
284 * reads lines from the node, creates messages from them and notifies
285 * listeners about the messages.
287 * @author David Roden <droden@gmail.com>
290 private class NodeReader implements Runnable {
292 /** The input stream to read from. */
293 @SuppressWarnings("hiding")
294 private InputStream nodeInputStream;
297 * Creates a new reader that reads from the specified input stream.
299 * @param nodeInputStream
300 * The input stream to read from
302 public NodeReader(InputStream nodeInputStream) {
303 this.nodeInputStream = nodeInputStream;
307 * Main loop of the reader. Lines are read and converted into
308 * {@link Message} objects.
311 LineInputStream nodeReader = null;
313 nodeReader = new LineInputStream(nodeInputStream);
315 Message message = null;
316 while (line != null) {
317 line = nodeReader.readLine();
318 // System.err.println("> " + line);
322 if (message == null) {
323 message = new Message(line);
326 if ("Data".equals(line)) {
327 /* need to read message from stream now */
328 File tempFile = null;
330 tempFile = File.createTempFile("fcpv2", "data", (tempDirectory != null) ? new File(tempDirectory) : null);
331 tempFile.deleteOnExit();
332 FileOutputStream tempFileOutputStream = new FileOutputStream(tempFile);
333 long dataLength = Long.parseLong(message.get("DataLength"));
334 StreamCopier.copy(nodeInputStream, tempFileOutputStream, dataLength);
335 tempFileOutputStream.close();
336 message.setPayloadInputStream(new TempFileInputStream(tempFile));
337 } catch (IOException ioe1) {
338 ioe1.printStackTrace();
341 if ("Data".equals(line) || "EndMessage".equals(line)) {
342 if (message.getName().equals("NodeHello")) {
344 synchronized (Connection.this) {
345 Connection.this.notify();
348 fireMessageReceived(message);
353 int equalsPosition = line.indexOf('=');
354 if (equalsPosition > -1) {
355 String key = line.substring(0, equalsPosition).trim();
356 String value = line.substring(equalsPosition + 1).trim();
357 if (key.equals("Identifier")) {
358 message.setIdentifier(value);
360 message.put(key, value);
364 /* skip lines consisting of whitespace only */
365 if (line.trim().length() == 0) {
368 /* if we got here, some error occured! */
369 throw new IOException("Unexpected line: " + line);
371 } catch (IOException ioe1) {
372 // ioe1.printStackTrace();
374 if (nodeReader != null) {
377 } catch (IOException ioe1) {
380 if (nodeInputStream != null) {
382 nodeInputStream.close();
383 } catch (IOException ioe1) {
387 Connection.this.disconnect();